1.首先编写拦截器代码
package com.sarnath.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Service; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.sarnath.constants.Constants; import com.sarnath.controller.BaseController; import com.sarnath.dto.output.UserOutput; /** * 自定义拦截器 * @Description * @author Sunny * @date 2018年1月15日 */ @Service public class CustomerInterceptor extends BaseController implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String url = request.getRequestURI().substring(1,request.getRequestURI().length()-1); /**登录和退出登录不做拦截*/ if(noLoginUrl.contains(url)){ return true; } //判断用户是否已登录 UserOutput user = getLoginUser(request, response); if(user == null || user.getUserId() == null){ response.sendRedirect("/index"); return false; } //判断当前用户请求路径是否拥有对应权限 boolean allowRequesst = false; if(user.getUserType() == Constants.USER_TYPE_ADMIN){ if(adminUrl.contains(url)){ allowRequesst = true; } }else if(user.getUserType() == Constants.USER_TYPE_TEACHER){ if(teacherUrl.contains(url)){ allowRequesst = true; } }else if(user.getUserType() == Constants.USER_TYPE_STUDENT){ if(studentUrl.contains(url)){ allowRequesst = true; } } if(allowRequesst){ return allowRequesst; } //默认跳转到登录页面 response.sendRedirect("/index"); return false; } @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 { } }
2.将拦截器增加到Spring Boot配置中
package com.sarnath.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.sarnath.interceptor.CustomerInterceptor; @Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { @Autowired private CustomerInterceptor interceptor; /** * 添加拦截器到Spring Boot配置中 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interceptor).addPathPatterns("/**"); } }
Ok,只需要这两部,设置好方法或路径的拦截业务逻辑即可
原文地址:https://www.cnblogs.com/sunny3096/p/8287664.html
时间: 2024-10-08 05:56:44