SpringBoot2之web开发(下)——数据响应、模板引擎、拦截器、文件上传和异常处理

  • 一、数据响应和内容协商
  • 1.1 响应json数据
  • 1.2 内容协商(待写)
  • 二、模板引擎(Thymeleaf )
  • 2.1 模板引擎介绍
  • 2.2 Thymeleaf 语法
  • 2.2.1 常用th属性:
  • 2.2.2 标准表达式语法
  • 2.2.3 springBoot中使用thymeleaf
  • 三、拦截器
  • 3.1 拦截器的使用
  • 3.2 拦截器方法执行顺序
  • 3.3 拦截器源码分析(待补)
  • 四、文件上传
  • 4.1 单文件和多文件上传的使用
  • 4.2 文件上传源码分析(待补)
  • 五、异常处理
  • 5.1 自定义错误页面
  • 5.2 @ExceptionHandle 注解处理局部异常
  • 5.3 @ControllerAdvice+@ExceptionHandler 注解处理异常
  • 5.4 自定义异常处理器(HandlerExceptionResolver )
  • 5.5 异常处理原理(源码分析)(待补)
  • 六、Web原生组件注入(Servlet、Filter、Listener)
  • 七、替换为其他嵌入式web服务器
  • 八、 扩展SpringMVC


一、数据响应和内容协商

1.1 响应json数据

使用jackson.jar+@ResponseBody注解

web场景自动引入了json的相关依赖spring-boot-starter-json,所有我们只需要在方法或者类上添加@ResponseBody注解即可,点进spring-boot-starter-json可以看到如下代码:

springboot RequestMapping 前置拦截 springboot拦截请求和响应_代码块


即:Spring Boot 中默认使用的JSON解析框架是 Jackson

代码示例:

@Controller
public class ResponseTestController {

    /**
     * 处理器方法返回一个Student,通过框架转为json,响应请求
     * @return
     */
    @ResponseBody  //利用返回值处理器里面的消息转换器进行处理
    @GetMapping(value = "/test/person")
    public Person getPerson(){
        Person person = new Person();
        person.setAge(28);
        person.setBirth(new Date());
        person.setUserName("zhangsan");
        return person; //会被框架转为json
    }
}

结果:

springboot RequestMapping 前置拦截 springboot拦截请求和响应_模板引擎_02

1.2 内容协商(待写)

P39-40

二、模板引擎(Thymeleaf )

2.1 模板引擎介绍

  • 模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是模板引擎。
  • jsp就是一个模板引擎,支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况.SpringBoot这个项目首先是以jar的方式,不是war,我们用的还是嵌入式的Tomcat,所以他现在默认是不支持jsp的
  • 常见的模板引擎有JSPVelocityFreemarkerThymeleaf
  • SpringBoot推荐使用Thymeleaf

2.2 Thymeleaf 语法

参考:Thymeleaf3语法详解Thymeleaf语法总结

Thymeleaf官网:https://www.thymeleaf.org/

注意:在使用Thymeleaf时页面要引入名称空间: xmlns:th="http://www.thymeleaf.org"

2.2.1 常用th属性:

  1. th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。
  2. th:value:设置当前元素的value值,类似修改指定属性的还有th:srcth:href
  3. th:each:遍历循环元素,和th:text或th:value一起使用。注
  4. th:if:条件判断,类似的还有th:unlessth:switchth:case
  5. th:insert:代码块引入,类似的还有th:replaceth:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。
  6. th:fragment:定义代码块,方便被th:insert引用。

代码示例:

<!DOCTYPE html>
<!--名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf 语法</title>
</head>
<body>
<h2>ITDragon Thymeleaf 语法</h2>
<!--th:text 设置当前元素的文本内容,常用,优先级不高-->
<p th:text="${thText}"></p>
<p th:utext="${thUText}" ></p>

<!--th:value 设置当前元素的value值,常用,优先级仅比th:text高-->
<input type="text" th:value="${thValue}" />

<!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入-->
<!--th:each 修饰在div上,则div层重复出现,若只想p标签遍历,则修饰在p标签上-->
<div th:each="message : ${thEach}"> <!-- 遍历整个div-p,不推荐-->
    <p th:text="${message}" />
</div>
<p>---------</p>
<div> <!--只遍历p,推荐使用-->
    <p th:text="${message}" th:each="message : ${thEach}" />
</div>

<!--th:if 条件判断,类似的有th:switch,th:case, 其中#strings是变量表达式的内置方法-->
<p th:text="${thIf}" th:if="${#strings.isEmpty(thIf)}"></p>
<p>==========</p>
<p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p>
</body>
</html>

Controller代码:

@Controller
public class ThymeleafController {

    @RequestMapping("thymeleaf")
    public String thymeleaf(ModelMap map) {
        map.put("thText", "th:text 设置文本内容 <b>加粗</b>");
        map.put("thUText", "th:utext 设置文本内容 <b>加粗</b>");
        map.put("thValue", "thValue 设置当前元素的value值");
        map.put("thEach", Arrays.asList("th:each", "遍历列表"));
        map.put("thIf", "msg is not null");
        return "test";
    }
}

执行结果:

springboot RequestMapping 前置拦截 springboot拦截请求和响应_spring_03

2.2.2 标准表达式语法

${...} 变量表达式,Variable Expressions
@{...} 链接表达式,Link URL Expressions
#{...} 消息表达式,Message Expressions
~{...} 代码块表达式,Fragment Expressions
*{...} 选择变量表达式,Selection Variable Expressions

  1. ${…}变量表达式
    变量表达式功能:
1、可以获取对象的属性和方法
 2、可以使用ctx,vars,locale,request,response,session,servletContext内置对象
 	1)ctx :上下文对象。
 	2)vars :上下文变量。
 	3)locale:上下文的语言环境。
 	4)request:(仅在web上下文)的 HttpServletRequest 对象。
 	5)response:(仅在web上下文)的 HttpServletResponse 对象。
 	6)session:(仅在web上下文)的 HttpSession 对象。
 	7)servletContext:(仅在web上下文)的 ServletContext 对象
 3、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法

这里以常用的Session举例,用户刊登成功后,会把用户信息放在Session中,Thymeleaf通过内置对象将值从session中获取。

// java 代码将用户名放在session中
session.setAttribute("userinfo",username);
// Thymeleaf通过内置对象直接获取
th:text="${session.userinfo}"
  1. @{…} 链接表达式
    不管是静态资源的引用,form表单的请求,凡是链接都可以用@{...} 。其中/可以动态获取项目路径,即便项目名变了,依然可以正常访问
#修改项目名,链接表达式会自动修改路径,避免资源文件找不到
server.context-path=/itdragon # 此时@{/}表示/itdragon

链接表达式的使用:

无参:@{/xxx} 有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2 引入本地资源:@{/项目本地的资源路径} 引入外部资源:@{/webjars/资源在jar包中的路径}

代码示例:

<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<link th:href="@{/main/css/itdragon.css}" rel="stylesheet">
<form class="form-login" th:action="@{/user/login}" th:method="post" >
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
  1. ~{…} 代码块表达式

推荐:~{templatename::fragmentname} 支持:~{templatename::#id}

templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。

fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment="fragmentname"

id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。

代码块表达式的使用:

代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。
th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,
th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,
th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中,

代码示例:

<!--th:fragment定义代码块标识-->
<footer th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</footer>

<!--三种不同的引入方式-->
<div th:insert="common :: copy"></div><!--common表示所定义代码块的路径-->
<div th:replace="common :: copy"></div>
<div th:include="common :: copy"></div>

<!--th:insert是在div中插入代码块,即多了一层div-->
<div>
    <footer>
    © 2011 The Good Thymes Virtual Grocery
    </footer>
</div>
<!--th:replace是将代码块代替当前div,其html结构和之前一致-->
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<!--th:include是将代码块footer的内容插入到div中,即少了一层footer-->
<div>
© 2011 The Good Thymes Virtual Grocery
</div>

2.2.3 springBoot中使用thymeleaf

1、引入Starter

<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、springboot自动配置好了thymeleaf

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration { }

Thymeleaf的自动配置类:ThymeleafProperties

springboot RequestMapping 前置拦截 springboot拦截请求和响应_模板引擎_04


我们可以在其中看到默认的前缀和后缀! 我们只需要把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了。

3、代码示例,一般放在templates文件夹下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}">哈哈</h1>
<a th:href="@{/link}">去百度2</a>
<table >
    <tr>
        <th>#</th>
        <th>用户名</th>
        <th>密码</th>
    </tr>
    <tr class="gradeX" th:each="user,status:${users}">
        <td th:text="${status.count}">Trident</td>
        <td th:text="${user.userName}"></td>
        <td>[[${user.password}]]</td>
    </tr>
</table>
</body>
</html>

Controller方法:

@Controller
public class ViewTestController {

    @RequestMapping("hello")
    public String goSuccess(Model model){
        //model中的数据会被放在请求域中 request.setAttribute("a",aa)
        model.addAttribute("msg","你好");
        model.addAttribute("link","https://www.baidu.com");
        //表格内容的遍历
        List<User> users = Arrays.asList(new User("zhangsan", "123456"),
                new User("lisi", "123444"),
                new User("haha", "aaaaa"),
                new User("hehe ", "aaddd"));
        model.addAttribute("users", users);
        return "success";
    }
}

结果:

springboot RequestMapping 前置拦截 springboot拦截请求和响应_springboot_05

三、拦截器

3.1 拦截器的使用

用户可以自定义拦截器来实现特定的功能,自定义的拦截器必须实现HandlerInterceptor接口 preHandle(request,response,Object handler):这个方法在业务处理器处理请求之前被调用,在该方法中对用户请求 request 进行处理。如果程序员决定该拦截器对请求进行拦截处理后还要调用其他的拦截器,或者是业务处理器去进行处理,则返回true;如果程序员决定不需要再调用其他的组件去处理请求,则返回false。 postHandle(request,response, Object handler,modelAndView):这个方法在业务处理器处理完请求后,但是DispatcherServlet 向客户端返回响应前被调用,在该方法中对用户请求request进行处理。该方法参数中包含 ModelAndView,所以该方法可以修改处理器方法的处理结果数据,且可以修改跳转方向 afterCompletion(request,response, Object handler, Exception ex):这个方法在 DispatcherServlet完全处理完请求后被调用,可以在该方法中进行一些资源清理的操作。

即:

preHandle:在目标方法运行之前调用;返回boolean;return true;(chain.doFilter())放行; return false;不放行
postHandle:在目标方法运行之后调用:目标方法调用之后
afterCompletion:在请求整个完成之后;来到目标页面之后;chain.doFilter()放行;资源响应之后;

代码示例:(以登录检查功能为例)

  1. 实现HandlerInterceptor接口
/**
 * 登录检查
 * 1、配置好拦截器要拦截哪些请求
 * 2、把这些配置放在容器中
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截的请求路径是:"+requestURI);

        //登录检查逻辑
        HttpSession session = request.getSession();

        Object loginUser = session.getAttribute("loginUser");
        if(loginUser != null){
            //放行
            return true;
        }
        //拦截住,未登录跳转到登录页面
//        response.sendRedirect("/");
        session.setAttribute("msg","请先登录");
        request.getRequestDispatcher("/").forward(request,response);
        return false;
    }

    /**
     * 目标方法执行完成以后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle执行{}",modelAndView);
    }

    /**
     * 页面渲染以后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行异常{}",ex);
    }
}
  1. 将配置好的拦截器放到容器里
/**
 * 1、编写一个拦截器实现HandlerInterceptor接口
 * 2、拦截器注册到容器中(实现WebMvcConfigurer的addInterceptors)
 * 3、指定拦截规则【如果是拦截所有,静态资源也会被拦截】
 *
 */
@Configuration
public class AdminWebConfig implements WebMvcConfigurer { //定值web功能都需要实现该接口

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**") //所有请求都被拦截包括静态资源
                .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**",
                        "/js/**","/aa/**"); //放行的请求
        
    }
}

注意:拦截器对于静态资源也会拦截,所以需要我们排除静态资源的路径

3.2 拦截器方法执行顺序

  1. 当个拦截器正常的执行顺序

springboot RequestMapping 前置拦截 springboot拦截请求和响应_模板引擎_06


springboot RequestMapping 前置拦截 springboot拦截请求和响应_html_07

正常运行流程:
拦截器的preHandle------目标方法-----拦截器postHandle-----页面-------拦截器的afterCompletion;

  1. 多拦截器正常执行

springboot RequestMapping 前置拦截 springboot拦截请求和响应_spring_08


springboot RequestMapping 前置拦截 springboot拦截请求和响应_html_09


执行结果:

MyFirstInterceptor...preHandle...MySecondInterceptor...preHandle...hello....MySecondInterceptor...postHandle... MyFirstInterceptor...postHandle... success.jsp.... MySecondInterceptor...afterCompletion... MyFirstInterceptor...afterCompletion

  1. 多拦截器异常流程

springboot RequestMapping 前置拦截 springboot拦截请求和响应_模板引擎_10

执行结果:

MyFirstInterceptor...preHandle...MySecondInterceptor...preHandle...MyFirstInterceptor...afterCompletion

总结:

拦截器的preHandle:是按照顺序执行
拦截器的postHandle:是按照逆序执行
拦截器的afterCompletion:是按照逆序执行;
如果某块的拦截器return false,那他前面已经放行了的拦截器的afterCompletion总会执行

3.3 拦截器源码分析(待补)

四、文件上传

4.1 单文件和多文件上传的使用

1、依赖导入:

<!-- spring boot web支持 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- thymeleaf模板依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、 form表单:

<form th:action="@{/upload}" method="post" enctype="multipart/form-data"><!--注意multipart/form-data-->
	邮箱:<input type="email" name="email">
	用户名:<input type="text"  name="username">
	头像:<input type="file" name="headerImg"><!--单文件上传-->
	生活照:<input type="file" name="photos" multiple><!--多文件上传-->
	<button type="submit" >Submit</button>
</form>

3、Controller层方法

@Slf4j
@Controller
public class FormTestController {

    @PostMapping("upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {

        if(!headerImg.isEmpty()){
            //对文件进行保存
            String originalFilename = headerImg.getOriginalFilename();//获取上传的文件名字
            headerImg.transferTo(new File("E:\\test\\"+originalFilename));
        }

        if(photos.length > 0){
            for(MultipartFile photo : photos){
                //对多个文件进行保存
                String originalFilename = photo.getOriginalFilename();
                photo.transferTo(new File("E:\\test\\"+originalFilename));
            }
        }
        return "main";
    }
}

4、设置上传文件的大小

spring:
  servlet:
    multipart:
      max-request-size: 5GB  # 上传文件总的最大值
      max-file-size: 1GB #单个文件最大值

springboot RequestMapping 前置拦截 springboot拦截请求和响应_spring_11

4.2 文件上传源码分析(待补)

五、异常处理

好的博客:玩转springboot:自定义异常处理和深入异常处理原理SpringBoot——错误处理机制 & 定制错误页面 (源码分析)

当访问一个不存在的页面,或者程序抛出异常时

1、默认效果
浏览器返回一个默认的错误页面, 注意看浏览器发送请求的请求头:
在这里插入图片描述
其他(Postman)客户端返回的是json数据,注意看请求头
在这里插入图片描述

5.1 自定义错误页面

  • 有模板引擎(thymeleaf等)的情况下;将错误页面命名为 错误状态码.html放在模板引擎文件夹(templates)里面的error文件夹下发生此状态码的错误就会来到这里找对应的页面;
  • 比如我们在templates文件夹下创建error/404.html当浏览器请求是404错误,就会使用我们创建的404.html页面响应,如果是其他状态码错误,还是使用默认的视图,但是如果404.html没有找到就会替换成4xx.html再查找一次

springboot RequestMapping 前置拦截 springboot拦截请求和响应_springboot_12


DefaultErrorViewResolver中的静态代码块


springboot RequestMapping 前置拦截 springboot拦截请求和响应_代码块_13


springboot RequestMapping 前置拦截 springboot拦截请求和响应_html_14

5.2 @ExceptionHandle 注解处理局部异常

只能处理使用 @ExceptionHandler注解的方法的 Controller 的异常,对于其他 Controller 的异常就不起作用了。

@Controller
public class UserController {

    /**
     * 模拟 NullPointerException
     * @return
     */
    @RequestMapping("/show1")
    public String showInfo(){
        String str = null;
        str.length();
        return "index";
    }

    /**
     * 模拟 ArithmeticException
     * @return
     */
    @RequestMapping("/show2")
    public String showInfo2(){
        int a = 10/0;
        return "index";
    }
    /**
     * java.lang.ArithmeticException
     * 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视图的指定
     * 参数 Exception e:会将产生异常对象注入到方法中
     */
    @ExceptionHandler(value={java.lang.ArithmeticException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString());
        mv.setViewName("error1");
        return mv;
    }
    /**
     * java.lang.NullPointerException
     * 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视
     图的指定
     * 参数 Exception e:会将产生异常对象注入到方法中
     */
    @ExceptionHandler(value={java.lang.NullPointerException.class})
    public ModelAndView nullPointerExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString());
        mv.setViewName("error2");
        return mv;
    }
}

error1.html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>错误页面</title>
</head>
<body>
出错了,请与管理员联系。。。错误提示页面-ArithmeticException<br>
<span th:text="${error}"></span>
</body>
</html>

error2.html页面

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title>错误页面</title>
</head>
<body>
出错了,请与管理员联系。。。错误提示页面-NullPointerException <br>
<span th:text="${error}"></span>
</body>
</html>

演示效果:

springboot RequestMapping 前置拦截 springboot拦截请求和响应_springboot_15


springboot RequestMapping 前置拦截 springboot拦截请求和响应_spring_16


springboot RequestMapping 前置拦截 springboot拦截请求和响应_html_17

5.3 @ControllerAdvice+@ExceptionHandler 注解处理异常

第二种处理方式中,异常处理的代码和业务代码放在一个类中了,这种方式耦合性太强了,最好是将业务和异常处理的代码分离开,这时我们可以定义一个专门的异常处理类,通过注解@ControllerAdvice来实现。具体如下:

异常处理类:

@ControllerAdvice
public class GlobalException {
    /**
     * java.lang.ArithmeticException
     * 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视图的指定
     * 参数 Exception e:会将产生异常对象注入到方法中
     */
    @ExceptionHandler(value={java.lang.ArithmeticException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString()+" -- advice");
        mv.setViewName("error1");
        return mv;
    }
    /**
     * java.lang.NullPointerException
     * 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视
     图的指定
     * 参数 Exception e:会将产生异常对象注入到方法中
     */
    @ExceptionHandler(value={java.lang.NullPointerException.class})
    public ModelAndView nullPointerExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString()+" -- advice");
        mv.setViewName("error2");
        return mv;
    }
}

Controller:

@Controller
public class UserController {

    /**
     * 模拟 NullPointerException
     * @return
     */
    @RequestMapping("/show1")
    public String showInfo(){
        String str = null;
        str.length();
        return "index";
    }

    /**
     * 模拟 ArithmeticException
     * @return
     */
    @RequestMapping("/show2")
    public String showInfo2(){
        int a = 10/0;
        return "index";
    }
}

演示效果:


5.4 自定义异常处理器(HandlerExceptionResolver )

可以通过实现HandlerExceptionResolver 接口来根据不同异常类型来动态处理异常

@Order(value= Ordered.HIGHEST_PRECEDENCE)  //优先级,数字越小优先级越高
@Component
public class CustomerHandlerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler, Exception ex) {

        ModelAndView mv = new ModelAndView();
        //判断不同异常类型,做不同视图跳转
        if (ex instanceof ArithmeticException) {
            mv.setViewName("error1");
        }
        if (ex instanceof NullPointerException) {
            mv.setViewName("error2");
        }
        mv.addObject("error", ex.toString());
        
        return new ModelAndView();
    }
}

注意:需要设置优先级,否则可能别的异常处理器先执行。

5.5 异常处理原理(源码分析)(待补)

六、Web原生组件注入(Servlet、Filter、Listener)

以Servlet为例介绍如何注入。

1、创建Servlet

public class MyServlet extends HttpServlet {
	//处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("66666");
    }
}

2、进行配置

  1. 方法一:使用@Bean注册Servlet
    新建MyRegisterConfig 类,在类上使用@Configuration注解,使用ServletRegistrationBean类进行Servlet注册
@Configuration
public class MyRegisterConfig {
    @Bean
    public ServletRegistrationBean myServlet() {
        MyServlet myServlet = new MyServlet();
        return new ServletRegistrationBean(myServlet,"/my","/my02");
    }
}

测试:

springboot RequestMapping 前置拦截 springboot拦截请求和响应_html_18

  1. 方法二:注解自动扫描
    在MyServlet类上增加@WebServlet注解
@WebServlet(urlPatterns = "/my")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("66666");
    }
}

然后在配置类上增加@ServletComponentScan注解,放在启动类上比较方便,无需配置扫描路径(不配置路径默认扫描当前路径类及其子路径类)。

@ServletComponentScan(basePackages = "com.zb.admin.servlet")
@SpringBootApplication
public class Boot05WebAdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(Boot05WebAdminApplication.class, args);
    }
}

FilterListener的配置方法和Servlet基本相同,不同的就是使用@Bean的方法进行配置,下面是Filter和Listener使用@Bean进行配置的代码:

@Configuration
public class MyRegisterConfig {

    @Bean
    public ServletRegistrationBean myServlet() {
        MyServlet myServlet = new MyServlet();
        return new ServletRegistrationBean(myServlet,"/my","/my02");
    }

    @Bean
    public FilterRegistrationBean myFilter(){
        MyFilter myFilter = new MyFilter();
//        return new FilterRegistrationBean(myFilter,myServlet());//方法一
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
        return filterRegistrationBean; //方法二
    }

    @Bean
    public ServletListenerRegistrationBean myListener(){
        MyServletContextListener myServletContextListener = new MyServletContextListener();
        return new ServletListenerRegistrationBean(myServletContextListener);
    }

}

七、替换为其他嵌入式web服务器

SpringBoot默认使用的是Tomcat,如果要换成其他的就把Tomcat的依赖排除掉,然后引入其他嵌入式Servlet容器的以来,如JettyUndertow

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <artifactId>spring-boot-starter-jetty</artifactId>
    <groupId>org.springframework.boot</groupId>
</dependency>

八、 扩展SpringMVC

以前的配置文件中的配置

<!-- 视图请求映射(当发送/hello请求,会跳转到success页面) -->
<mvc:view-controller path="/hello" view-name="success"/>

使用SpringBoot的方式来替代上面配置文件中的配置,需要扩展SpringMVC

  • 编写一个配置类(@Configuration)实现WebMvcConfigurer接口;不能标注@EnableWebMvc既保留了所有的自动配置,也能用我们扩展的配置;
// 配置类
@Configuration
// 使用WebMvcConfigurer用来扩展SpringMVC的功能
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    	// 浏览器发送/sunny请求,就会来到test页面(也是通过模板引擎(thymeleaf)解析的)
        registry.addViewController("/sunny").setViewName("test");
    }
}