zoukankan      html  css  js  c++  java
  • http拦截器-HandlerInterceptor

    简介

      拦截器我想大家都并不陌生,最常用的登录拦截权限校验防重复提交记录日志等等,总之可以去做很多的事情。

    自定义拦截器HandlerInterceptorAdapter

    我们以记录日志为例,介绍拦截器

    1. preHandle:在业务处理器处理请求之前被调用,调用controller之前调用。预处理,可以进行编码、安全控制、权限校验等处理;
    2. postHandle:在业务处理器处理请求执行完成后,生成视图之前执行。后处理(调用了Service并返回ModelAndView,但未进行页面渲染),有机会修改ModelAndView ;
    3. afterCompletion:在DispatcherServlet完全处理完请求后被调用,可用于清理资源等。

    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.stereotype.Component;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    import com.alibaba.fastjson.JSON;
    import com.example.demo.util.RespUtil;
    
    @Component
    public class ReqInterceptor extends HandlerInterceptorAdapter {
     
        /**
         * 在方法被调用前执行。在该方法中可以做类似校验的功能。如果返回true,
         * 则继续运行下去。如果返回false,则中断执行。
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          log.info("进入调单方法controller层之前");
          String insuranceId = httpServletRequest.getParameter("insuranceId");
          try {
            FanHuaBack fanHuaBackOld = insureListService.getinsure(insuranceId);
            String oldData = JSON.toJSONString(fanHuaBackOld);
            httpServletRequest.setAttribute("dataBefore", oldData);
            super.preHandle(httpServletRequest,httpServletResponse,o);
          } catch (Exception e) {
            log.error("车险投保信息查询异常", e.getMessage());
          } finally {
            return true;
          }
    
    }
        /**
         * 在方法执行后调用。
         */
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) 
                                                                  throws Exception {       log.info("进入调单方法controller层之后-----------日志记录开始");       InsuranceOperatLog insuranceOperatLog = new InsuranceOperatLog();//日志类       int status = 0;       try {         //从request请求中获取信息         String requestURI = httpServletRequest.getRequestURI();         String insuranceId = httpServletRequest.getParameter("insuranceId");         String empNo = httpServletRequest.getParameter("empNo");         String empName = httpServletRequest.getParameter("empName");         int opeStatus = (int) httpServletRequest.getAttribute("status");         FanHuaBack fanHuaBackNew = insureListService.getinsure(insuranceId);         String newData = JSON.toJSONString(fanHuaBackNew);         String oldData = (String) httpServletRequest.getAttribute("dataBefore");         Map<String, String> map = new HashMap<>();         map.put("empNum", empNo);         map.put("empName", empName);         map.put("insuranceId", insuranceId);         String reqObj = JSON.toJSONString(map);         insuranceOperatLog.setInsuranceId(insuranceId);         insuranceOperatLog.setCreateTime(DateUtil.format(new Date(), DateUtil.Formatter.yyyyMMddHHmmss));         insuranceOperatLog.setDataBefore(oldData);         insuranceOperatLog.setDataAfter(newData);         insuranceOperatLog.setReq_json(reqObj);         insuranceOperatLog.setReq_url(requestURI);         insuranceOperatLog.setOperatorType("调单");         insuranceOperatLog.setStatus(opeStatus == 1 ? "成功" : "失败");         SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();         if (sysUser != null) {           insuranceOperatLog.setOperatorName(sysUser.getLoginName());           insuranceOperatLog.setOperatorNo(sysUser.getUserNo());         }         insuranceOperatRepository.save(insuranceOperatLog);         super.postHandle(httpServletRequest,httpServletResponse,o,modelAndView);       } catch (Exception ex) {         log.error("调单操作异常日志保存异常{}", ex.getMessage());       }       log.info("调单操作日志记录结束{}"); } /** * 在整个请求处理完毕后进行回调,也就是说视图渲染完毕或者调用方已经拿到响应。 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                                                          throws Exception { System.out.println("在整个请求处理完毕后进行回调"); super.afterCompletion(request, response, handler, ex); } }
  • 相关阅读:
    二叉搜索树的建树与遍历
    SpringBoot Mybatis 读写分离配置(山东数漫江湖)
    Spring注解概览(数漫江湖)
    Spring Cloud的基本认识和使用Spring Cloud的基本教程(山东数漫江湖)
    全面了解Nginx主要应用场景(数漫江湖)
    Spring boot集成RabbitMQ(山东数漫江湖)
    Spring 事务管理(山东数漫江湖)
    透彻理解Spring事务设计思想之手写实现(山东数漫江湖)
    Spring整合Quartz分布式调度(山东数漫江湖)
    Spring归纳小结(山东数漫江湖)
  • 原文地址:https://www.cnblogs.com/FondWang/p/12037141.html
Copyright © 2011-2022 走看看