【spring】spring拦截器 - - - spring mvc 拦截器
1.配置文件注入Bean
<!-- 权限拦截 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**/save/**"/>
<bean class="com.proengine.partner.common.interceptor.PromotionStoreAuthInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
2.拦截器类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.proengine.partner.common.interceptor; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; /** * @Author: SXD * @Description: 拦截器 * @Date: create in 2020/1/7 15:47 */ public class PromotionStoreAuthInterceptor extends BaseController implements HandlerInterceptor { /** * 该方法在进入控制器的处理请求方法前执行,其返回值表示是否中断后续操作,返回 true 表示继续向下执行,返回 false 表示中断后续操作。 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Map<String, String[]> parameterMap = request.getParameterMap();//获取请求参数 StringBuilder errMsg = new StringBuilder(); if (errMsg.length() > 0 ){ response(request,response,errMsg.toString()); return false;//拦截请求 } return true;//放过请求 } /** * 该方法在控制器的处理请求方法调用之后、解析视图之前执行,可以通过此方法对请求域中的模型和视图做进一步的修改。 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 该方法在控制器的处理请求方法执行完成后执行,即视图渲染结束后执行,可以通过此方法实现一些资源清理、记录日志信息等工作。 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } //返回拦截消息给前端,解决跨域,编码问题 private void response(HttpServletRequest request, HttpServletResponse response, String message) throws Exception{ String origin = request.getHeader("Origin"); if (StringUtils.isNotBlank(origin)) { if (origin.toLowerCase().indexOf(".XXX.com") > 0) { response.setHeader("Access-Control-Allow-Origin", origin); // 允许访问的域 response.setHeader("Access-Control-Allow-Methods", "POST,GET");// 允许GET、POST的外域请求 response.setHeader("Access-Control-Allow-Credentials", "true"); // 允许请求带cookie到服务器 response.setContentType("text/html; charset=utf-8"); // 设定JSON格式标准输出、及编码 } } PrintWriter pw = response.getWriter(); pw.write(JSON.toJSONString(message)); pw.flush(); pw.close(); } }