十三、springBoot 配置自定义拦截器及配置web项目static静态资源访问

1、自定义拦截器,实现HandlerInterceptor或者继承WebMvcConfigurerAdapter

import com.alibaba.fastjson.JSON;
import com.trgis.www.manage.entity.TRUser;
import com.trgis.www.manage.service.TRUserService;
import com.trgis.www.util.BeanUtil;
import com.trgis.www.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @Author: zhao
 * @CreateDate: 2019/10/17$ 18:57$
 */
@Controller
public class UserTokenInterceptor implements HandlerInterceptor{

    @Autowired
    private TRUserService trUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        TRUser user = (TRUser) session.getAttribute("user");
        if (BeanUtil.isEmpty(user)) {
            Result result = new Result();
            result.setError("登录超时", -1);
            returnResult(result, response);
            return false;
        } else {
            Result result = new Result();
            String username = user.getUsername();
            TRUser trUser = trUserService.findByUsername(username);
            if (BeanUtil.isNotEmpty(trUser)) {
                if (!trUser.getPassword().equals(user.getPassword())) {
                    result.setError("用户密码已更改");
                    returnResult(result, response);
                    return false;
                }
            } else {
                result.setError("用户不存在");
                returnResult(result, response);
                return false;
            }
        }
        return true;
    }

    private void returnResult(Result result, HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String json = JSON.toJSONString(result);
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (Exception e) {

        } finally {
            if (null != writer) {
                writer.close();
            }
        }
    }
}

2、配置静态资源、以及自定义拦截器对部分接口不拦截,配置如下

import com.trgis.www.framework.interceptor.UserTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @Author: zhao
 * @CreateDate: 2019/10/17$ 18:50$
 */
@Component
public class WebMvcConfig extends WebMvcConfigurationSupport{

    @Autowired
    private UserTokenInterceptor userTokenInterceptor;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //第一个方法设置访问路径前缀,第二个方法设置资源路径
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userTokenInterceptor)
                //addPathPatterns 用于添加拦截规则
                .addPathPatterns("/**")
                //项目启动测试接口
                .excludePathPatterns("/")
                // 静态资源
                .excludePathPatterns("/static/**")
                // SwaggerUI
                .excludePathPatterns("/swagger-ui.html","/v2/api-docs","/webjars/**","/swagger-resources/**")
                // 用户登录不拦截
                .excludePathPatterns("/login")
                // public为前缀的访问都取消验证
                .excludePathPatterns("/public/**");

    }
}

3、配置web静态文件,访问不带static前缀

说明:配置文件中application.yml不用配置spring.mvc.static-path-pattern及spring.resources.static-locations

@Component
public class TokenInterceptorConfig extends WebMvcConfigurationSupport {

	private ApplicationContext applicationContext;

	/**
	 * 配置拦截器的Bean
	 * @return
	 */
	@Autowired
	private OperationLogInterceptor operationLogInterceptor;

	@Autowired
	private SessionInterceptor sessionInterceptor;


	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**")
				.addResourceLocations("classpath:/static/")
				.addResourceLocations("classpath:/resources/")
				.addResourceLocations("classpath:/META-INF/resources/")
				.addResourceLocations("classpath:/templates/");
		registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		super.addResourceHandlers(registry);
	}

	/**
	 * c重写addInterceptors方法,注册拦截器
	 * @param registry
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 多个拦截器组成一个拦截器链
		registry.addInterceptor(sessionInterceptor).addPathPatterns("/**")
			.excludePathPatterns(
				"/*.html", "/**/*.ico", // 配置static根目录文件访问
				"/assets/**", "/css/**", "/html/**", "/images/**", "/InHouseApp/**", "/js/**", "/libs/**", "/mail/**", "/res/**", "/ueditor1_4_3_3/**", "/zhaopin/**", // 配置static根目录文件夹下的文件访问
				"/", "/static/**", // 静态资源
                "/doc.html**","/v2/api-docs","/webjars/**","/swagger-resources","/swagger-ui.html", // SwaggerUI
				"/login","/ajaxLogin", // 用户登录
				"/editor","/index","/error","/index.html","/downFile","/public/**"
			);
		registry.addInterceptor(operationLogInterceptor).addPathPatterns("/**")
			.excludePathPatterns(
				"/*.html", "/**/*.ico", // 配置static根目录文件访问
				"/assets/**", "/css/**", "/html/**", "/images/**", "/InHouseApp/**", "/js/**", "/libs/**", "/mail/**", "/res/**", "/ueditor1_4_3_3/**", "/zhaopin/**", // 配置static根目录文件夹下的文件访问
				"/", "/static/**", // 静态资源
                "/doc.html**","/v2/api-docs","/webjars/**","/swagger-resources","/swagger-ui.html", // SwaggerUI
				"/login","/ajaxLogin", // 用户登录
				"/editor","/index","/error","/index.html","/downFile","/public/**",
				"/logout"
			);
		super.addInterceptors(registry);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章