uniapp开发app框架在提升开发效率中的独特优势与应用探索
1764
2022-12-07
spring boot中interceptor-未生效的解决
目录interceptor-未生效开始用的spring boot版本为1.5.6解决方案HandlerInterceptor实现登录失效拦截等首先写一个实现HandlerInterceptor的类然后把这个-注册到spring中
interceptor-未生效
搭建项目时发现-未生效
开始用的spring boot版本为1.5.6
代码如下:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
private TimeInterceptor timeInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.timeInterceptor);
super.addInterceptors(registry);
}
}
@Component
public class RequestParamInfoIntorceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(RequestParamInfoIntorceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
try {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
String beanName = handlerMethod.getBean().getClass().toString();//类
String methodName = handlerMethod.getMethod().getName();//方法名称
if(methodName.equals("error") || methodName.equals("success")) {
return super.preHandle(request, response, handler);
}
String uri = request.getRequeshttp://tURI();//请求路径
String remoteAddr = getIpAddr(request);//ip
String method = request.getMethod(); //请求方式
Map
StringBuffer sbf = new StringBuffer();
int count = 0;
String forCunt = "";
for(Map.Entry
forCunt = "[" + count + "]" + " : " ;
sbf.append( "paramName" + forCunt + entry.getKey() + " - "+ "paramValue" +
forCunt + request.getParameter(entry.getKey()) + "\n");
count ++;
}
logger.info(" { beanName : " + beanName + " | " + "methodName : " + methodName + " | " + "uri : "
+ uri + " | " + "remoteAddr : " + remoteAddr + " | " + "requestMethod : " +
method + "\n" + "param : " + sbf + "}");
}
} catch (Exception e) {
//出错
logger.error(e.toString());
}
return super.preHandle(request, response, handler);
}
//获取客户端IP
private String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
开始以为是版本问题,后升级为2.1.1,WebConfig改为实现WebMvcConfigurer,代码如下
@Configuration
@Component
public class WebConfig implements WebMvcConfigurer{
@Autowired
private RequestParamInfoIntorceptor requestParamInfoIntorceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**");
}
}
验证后还是不行,继续排查后发现,在添加版本控制时,有配置类继承了WebMvcConfigurationSupport,查询WebMvcConfigurationSupport源码发现其中有-注册方法addInterceptors(InterceptorRegistry registry),所以在版本控制配置类中重写此方法添加-,-生效,问题解决。
解决方案
代码如下:
@Configuration
public class ApiConfig extends WebMvcConfigurationSupport {
@Autowired
private RequestParamInfoIntorceptor requestParamInfoIntorceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
HandlerInterceptor实现登录失效拦截等
首先写一个实现HandlerInterceptor的类
代码如下:
public class SessionInterceptor implements HandlerInterceptor {
@Autowired
RedisTemplate
//private static String LOGIN_CODE = "/user/no_loginPage?Landingcode=" + UserResourcesHelper.LANDINGCODE_106;// 登录地址及code信息
//private static String LOGIN_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd11f95277f85e24b&redirect_uri=&response_type=code&scope=snsapi_userinfo&state=1234#wechat_redirect";
protected List
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 一些不需要过滤的方法
String url = request.getRequestURI();
if (isInclude(url) == true)
return true;
// 权限校验
Cookie cookie = getCookieByName(request, UserResourcesHelper.COOKIE_TOKEN_NAME);
String user = null;
if (cookie != null && !cookie.getValue().equals("")) {
user = redisTemplate.opsForValue().get(RedisKeyConstant.USER_WEB_TOKEN + cookie.getValue());
}
if (cookie == null || user == null) {// 判断用户是否经过了授权
// 判断是否是AJAX访问
if (request.getHeader("x-requested-with") != null
&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
response.setHeader("sessionstatus", "timeout");
response.setStatus(403);
return false;
} else {
response.sendRedirect(request.getContextPath()+"/home/no_index_toLoginSkip");
//response.sendRedirect(request.getContextPath() +UserResourcesHelper.LOGIN_URL); // 非AJAX访问,页面跳转
//response.sendRedirect(request.getContextPath() +"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd11f95277f85e24b&redirect_uri="+URLEncoder.encode("http://m.hobay-/user/no_loginPage", "utf-8")+"&response_type=code&scope=snsapi_base&state=123#wechat_redirect"); // 非AJAX访问,页面跳转
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 boolean isInclude(String url) {
for (String pattern : patterns) {
if (Pattern.matches(pattern, url)) {
return true;
}
}
return false;
}
/**
* 根据名字获取cookie
*
* @param request
* @param name
* cookie名字
* @return
*/
private static Cookie getCookieByName(HttpServletRequest request, String name) {
Map
if (cookieMap.containsKey(name)) {
Cookie cookie = (Cookie) cookieMap.get(name);
return cookie;
} else {
return null;
}
}
/**
* 将cookie封装到Map里面
*
* @param request
* @return
*/
private static Map
Map
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
然后把这个-注册到spring中
代码如下:
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Bean
SessionInterceptor sessioninterceptor() {
return new SessionInterceptor();
}
/**
* 配置-
* @author yuqingquan
* @param registry
*/
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(sessioninterceptor());
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~