自定义拦截器判断用户是否有权限访问
1、关于权限系统,对于用户是否有权限对系统进行访问,设置自定义拦截器,来拦截用户的请求
1 package org.slsale.interceptor; 2 3 import javax.annotation.Resource; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 import javax.servlet.http.HttpSession; 7 8 import org.apache.log4j.Logger; 9 import org.slsale.common.Constants; 10 import org.slsale.common.RedisAPI; 11 import org.slsale.pojo.User; 12 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 13 14 /** 15 * 自定义拦截器,拦截请求(是否有权限访问) 16 * @author lzw 17 * 2017-7-11 18 * 每个人都有自己的梦想。努力拼搏吧!不要让自己后悔! 19 */ 20 public class SysInterceptor extends HandlerInterceptorAdapter { 21 private Logger logger = Logger.getLogger(SysInterceptor.class); 22 @Resource 23 private RedisAPI redisAPI; 24 25 @Override 26 public boolean preHandle(HttpServletRequest request, 27 HttpServletResponse response, Object handler) throws Exception { 28 HttpSession session = request.getSession(); 29 String urlPath = request.getRequestURI(); 30 31 User user = (User) session.getAttribute(Constants.SESSION_USER); 32 if (null == user) {// 如果session中user为空,返回登录页面 33 response.sendRedirect("/"); 34 return false; 35 } else { 36 String key = "Role" + user.getRoleId() + "UrlList"; 37 String urls = redisAPI.get(key); 38 if (urls != null && !"".equals(urls) && urls.indexOf(urlPath) > 0) { 39 return true; 40 } else { 41 response.sendRedirect("/401.html"); 42 return false; 43 } 44 } 45 } 46 47 }
2、SpringMVC文件里配置
1 <!-- 配置interceptors --> 2 <mvc:interceptors> 3 <mvc:interceptor> 4 <mvc:mapping path="/backend/**"/> 5 <mvc:mapping path="/member/**"/> 6 <mvc:mapping path="/message/**"/> 7 <mvc:mapping path="/informanage/**"/> 8 <bean class="org.slsale.interceptor.SysInterceptor"/> 9 </mvc:interceptor> 10 </mvc:interceptors>