springmvc利用拦截器进行权限校验Jackson数据传输
2021-03-08 23:28
标签:定义 set writer als defaults tor efault convert intercept 需要了解拦截器 springmvc利用拦截器进行权限校验Jackson数据传输 标签:定义 set writer als defaults tor efault convert intercept 原文地址:https://www.cnblogs.com/x-i-n/p/14192120.html
自定义一个类 实现HandlerInterceptor 或 继承HandlerInterceptorAdapter
重写下面三个方法 顺序依次如下
//在 handler执行之前执行 返回值为ture才会执行 拦截器或handler
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setContentType("application/json;charset=utf-8");//设置响应编码
User user = (User) request.getSession().getAttribute("user");
if (user==null){
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();//需要导入jackson依赖
String result = objectMapper.writeValueAsString(new Result(false, "未登录!"));//将对象转换为json字符串
out.write(result);//响应给用户
return false;
}
return true;
}
//在 handler执行之后执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
//在 响应前执行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
拦的执行需要在spring-mvc.xml中配置拦截器[因具体情况配置响应编码]
文章标题:springmvc利用拦截器进行权限校验Jackson数据传输
文章链接:http://soscw.com/index.php/essay/62027.html