spring boot 添加拦截器实现登陆检测

添加拦截其它挺简单的,直接上代码吧,我以简单的登陆验证拦截为例

1,先实现一个拦截器

package com.dk.game.manager.intecptors;

import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson.JSONObject;
import com.dk.game.manager.service.CommonService;

public class LoginFilter implements HandlerInterceptor {
    public static String SESSION_USER = "USER";
    private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);
    private CommonService commonService;

    public LoginFilter(CommonService commonService) {
        this.commonService = commonService;
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String path = req.getRequestURI();
        logger.debug("请求路径:{}", path);
        Object value = req.getSession(true).getAttribute(SESSION_USER);
        if (value == null) {
            if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {//如果ajax请求,走这里
                resp.setCharacterEncoding("utf-8");//防止返回中文乱码,它必须放在PrintWriter获取之前,否则不会生效
                resp.setContentType("text/html; charset=utf-8");
                PrintWriter out = resp.getWriter();
                JSONObject result = commonService.error(-100, "登陆已失效,请重新登陆!!");
                out.print(result.toJSONString());// session失效
                out.flush();
            } else {
                resp.sendRedirect("/dkgm/index");
            }
            return false;
        }
        logger.info("{} 操作 {}", value, path);
        return true;
    }
}

 

2,添加拦截器

 

package com.xinyue.interview;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.xinyue.interview.gm.filter.LoginFilter;
/**
 * 
 * @ClassName: WebMvcConfig 
 * @Description: webmvc的相关配置实现,可以添加拦截器
 * @author: wgs  QQ群:66728073,197321069,398808948
 * @date: 2018年10月26日 下午3:13:46
 */
@Configuration  //这里的@Configuration注解必须有,要不然这个类不起做用,网上有的文章没有这个注解,拦截器不起作用,让我查了半天
public class WebMvcConfig extends WebMvcConfigurerAdapter {

      @Autowired

     private CommonService commonService;

public LoginFilter getLoginFilter() {
        return new LoginFilter(commonService);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getLoginFilter()).addPathPatterns("/gm/**.gm").excludePathPatterns("/gm/login")
; //注意这里路径的匹配,必须以/开头,前面是要拦截的请求,后面是不需要拦截的请求。
    }
}

 


更多文章:http://www.coc88.com

原文地址:https://www.cnblogs.com/wgslucky/p/9856496.html