http拦截器-HandlerInterceptor

Posted fondwang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); } }

 

以上是关于http拦截器-HandlerInterceptor的主要内容,如果未能解决你的问题,请参考以下文章

Angular - http 拦截器 - http 速率限制器 - 滑动窗口

golang http 请求添加拦截器

AngularJs HTTP响应拦截器实现登陆权限校验

向 Angular 应用程序添加多个 HTTP 拦截器

如何使用angularJS拦截器只拦截特定的http请求?

拦截器中的角度 http 请求时间