1.静态资源访问(必须)
- 静态资源:js,css,图片等
- 目录:main/resource/static/js
- 目录:main/resource/static/css
- 目录:main/resource/static/imgs
2.全局捕获异常
-
@ExceptionHandler 作为异常处理器表示 拦截异常 跟异常类型
-
@ControllerAdvice 作为全局异常处理的切面类
步骤:
- 1.在com.zjc.web.exception包中定义一个 全局异常处理类
- 下面代码说明ExceptionHandler 捕获的是运行时异常
@ControllerAdvice//切面 public class GlobalExceptionHandler { //捕获运行时异常 @ExceptionHandler(RuntimeException.class) @ResponseBody public Map<String,Object> exceptionHander(){ Map<String, Object> map = new HashMap<String, Object>(); map.put("errorCode", "101"); map.put("errorMsg", "系統错误!"); return map; } }
- 2.配置扫描包为com.zjc.web:目的是扫描到全局异常处理类所在的包
-
//扫描路径:包含全局异常处理类所在包 @ComponentScan("com.zjc.web") @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class,args); } }
- 3.在要调用controller的映射方法中添加个 int i = 99/0;代码
- 4.浏览器访问映射方法路径,页面会根据异常返回相应的处理结果(本案例是提交呈现异常 json格式:responsebody)
Spring Boot 模板引擎
- Thymeleaf
- FreeMarker
- Velocity
- Groovy
- Mustache
Spring Boot + freemarker 使用
- 默认的模板配置路径为:src/main/resources/templates
步骤1:配置freeMarker依赖
-
<!-- 引入freeMarker依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
- 步骤2:在templates中创建xxx.ftl 文件 ==jsp
- 步骤3:写好controller
- 步骤4:访问方法对应的映射路径
Spring Boot + JSP 使用 不推荐
- 步骤1:创建 maven工程 war 不是jar,jar没有web...目录
- 步骤2:文件引入依赖
-
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <!-- SpringBoot 核心组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> </dependencies>
- 步骤3:resources文件夹创建 application.properties 文件
-
spring.mvc.view.prefix=/WEB-INF/view/ spring.mvc.view.suffix=.jsp
- 步骤4:web/view创建jsp文件
- 步骤5:访问方法对应的映射路径