本文主要是介绍springboot day4 异常处理与servlet3.0注解过滤器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1 异常处理
类添加注解
@ControllerAdvice ,如果需要返回 json 数据,则⽅法需要加 @ResponseBody
@RestControllerAdvice, 默认返回 json 数据,⽅法不需要加 @ResponseBody
⽅法添加处理器
捕获全局异常 , 处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
package com.test.utils;/*** 接口返回工具类*/
public class JsonData {private int code;private Object data;private String msg;public int getCode() {return code;}public void setCode(int code) {this.code = code;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public JsonData(){}public JsonData(int code, Object data){this.code = code;this.data = data;}public JsonData(int code, Object data, String msg){this.code = code;this.data =data;this.msg = msg;}public static JsonData buildSuccess(Object data){return new JsonData(0,data);}public static JsonData buildError(String msg){return new JsonData(-1,"",msg);}public static JsonData buildError(String msg,int code){return new JsonData(code,"",msg);}@Overridepublic String toString() {return "JsonData{" +"code=" + code +", data=" + data +", msg='" + msg + '\'' +'}';}
}/*** 标记这是个异常处理类*/
@RestControllerAdvice
public class CustomExtHandler {@ExceptionHandler(value = Exception.class)JsonData handlerException(Exception e, HttpServletRequest request){return JsonData.buildError("服务端出问题了", -2);}
}
2 ⾃定义全局异常返回⻚⾯
返回⾃定义异常界⾯,需要引⼊ thymeleaf 依赖 ( ⾮必须,如果是简单的 html 界⾯则不⽤ )
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
resource ⽬录下新建 templates, 并新建 error.html
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMessage());
return modelAndView;
3. 过滤器
SpringBoot2.X ⾥⾯的过滤器
ApplicationContextHeaderFilter
OrderedCharacterEncodingFilter
OrderedFormContentFilter
OrderedRequestContextFilter
Ordered.HIGHEST_PRECEDENCE Ordered.LOWEST_PRECEDENCE
低位值意味着更⾼的优先级 Higher values are interpreted as lower priority
⾃定义 Filter ,避免和默认的 Filter 优先级⼀样,不然会冲突
注册 Filter 配置两种⽅式
bean FilterRegistrationBean
Servlet3.0 webFileter
使⽤Servlet3.0的注解进⾏配置步骤
启动类⾥⾯增加 @ServletComponentScan ,进⾏扫描
新建⼀个Filter 类, implements Filter ,并实现对应的接⼝
@WebFilter 标记⼀个类为 fifilter ,被 spring 进⾏扫描
urlPatterns:拦截规则,⽀持正则
控制chain.doFilter 的⽅法的调⽤,来实现是否通过放⾏
不放⾏,web 应⽤ resp.sendRedirect("/index.html") 或者 返回 json 字符串
权限控制、⽤户登录状态控制,也可以交给拦截器处理等
@WebFilter(urlPatterns = "/api/v1/pri/*", filterName = "loginFilter")
public class LoginFilter implements Filter {/*** 容器加载的时候* @param filterConfig* @throws ServletException*/@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("init LoginFilter======");}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("doFilter LoginFilter======");HttpServletRequest req = (HttpServletRequest) servletRequest;HttpServletResponse resp = (HttpServletResponse) servletResponse;String token = req.getHeader("token");if(StringUtils.isEmpty(token)){token = req.getParameter("token");}if(StringUtils.isEmpty(token)){return;}else {//判断token是否合法}}/*** 容器销毁的时候*/@Overridepublic void destroy() {System.out.println("destroy LoginFilter======");}
}
Servlet3.0返回未登录错误码
private void renderJson(HttpServletResponse response,String json){response.setCharacterEncoding("UTF-8");response.setContentType("application/json");try(PrintWriter writer = response.getWriter()){writer.print(json);}catch (Exception e){e.printStackTrace();}
}
Servlet3.0注解开发原⽣Servlet更轻量级
@WebServlet(name = "userServlet", urlPatterns = "/api/v1/test/customs" )
class UserServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {PrintWriter writer = resp.getWriter();writer.write("this is my custom servlet");writer.flush();writer.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {this.doGet(req,resp);}
}
Servlet3.0+SpringBoot2.X 注解Listener常⽤监听器
监听器:应⽤启动监听器,会话监听器,请求监听器
ServletContextListener 应⽤启动监听
HttpSessionLisener 会话监听(前后端分离架构不再用)
ServletRequestListener 请求监听
@WebListener
public class RequestListener implements ServletRequestListener {@Overridepublic void contextDestroyed(ServletContextEvent sce) {System.out.println("======contextDestroyed========");}@Overridepublic void contextInitialized(ServletContextEvent sce) {System.out.println("======contextInitialized========");}
}
4 拦截器
SpringBoot2.x 使⽤步骤
SpringBoot2.X 新版本配置拦截器 implements WebMvcConfifigurer
⾃定义拦截器 HandlerInterceptor
preHandle:调⽤Controller 某个⽅法之前
postHandle:Controller 之后调⽤,视图渲染之前,如果控制器 Controller 出现了异常,则不会执⾏此⽅法
afterCompletion:不管有没有异常,这个afterCompletion 都会被调⽤,⽤于资 源清理
按照注册顺序进⾏拦截,先注册,先被拦截
注意
-是否有加 @Configuration
-拦截路径是否有问题 ** 和 *
-拦截器最后路径⼀定要 /** 如果是⽬录的话则是 /*/
Filter和 Interceptor ⼆者都是 AOP 编程思想的体现,功能基本都可以实现
拦截器功能更强⼤些,Filter 能做的事情它都能做
Filter在只在 Servlet 前后起作⽤,⽽ Interceptor 够深⼊到⽅法前后、异常抛出前后等
filter依赖于 Servlet 容器即 web 应⽤中,⽽ Interceptor 不依赖于 Servlet 容器所以可以运⾏在多种环境。
在接⼝调⽤的⽣命周期⾥,Interceptor 可以被多次调⽤,⽽ Filter 只能在容器初始化时调⽤⼀ 次。
Filter和 Interceptor 的执⾏顺序
过滤前->拦截前 ->action 执⾏ -> 拦截后 -> 过滤后
配置不拦截路径
registry.addInterceptor(new LoginIntercepter()).addPathPatterns("/api/v1/pri/**")
// 配置不拦截某些路径,⽐如静态资源
.excludePathPatterns("/**/*.html","/**/*.js");
5 SpringBoot2.X 整合模板引擎
JSP(后端渲染,消耗性能)
Freemarker
Freemarker 相关 maven 依赖
<!-- 引⼊freemarker模板引擎的依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>
Freemarker 基础配置
# 是否开启thymeleaf缓存,本地为false,⽣产建议为truespring.freemarker.cache=falsespring.freemarker.charset=UTF-8spring.freemarker.allow-request-override=falsespring.freemarker.check-template-location=true#类型spring.freemarker.content-type=text/htmlspring.freemarker.expose-request-attributes=truespring.freemarker.expose-session-attributes=true#⽂件后缀spring.freemarker.suffix=.ftl#路径spring.freemarker.template-loader-path=classpath:/templates/
Thymeleaf
thymeleaf相关maven依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
thymeleaf 基础配置
#开发时关闭缓存,不然没法看到实时⻚⾯spring.thymeleaf.cache=falsespring.thymeleaf.mode=HTML5#前缀spring.thymeleaf.prefix=#编码spring.thymeleaf.encoding=UTF-8#类型spring.thymeleaf.content-type=text/html#名称的后缀spring.thymeleaf.suffix=.html
Getting started with the Standard dialects in 5 minutes - Thymeleaf
这篇关于springboot day4 异常处理与servlet3.0注解过滤器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!