拦截器作用:可以用于用户操作的安全检查,如:登录、权限等
package com.tool; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class SecurityInterceptor implements HandlerInterceptor { private List<String> excludedUrls; public void setExcludedUrls(List<String> excludedUrls) { this.excludedUrls = excludedUrls; } @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1, Object arg2) throws Exception { String requestUri = request.getRequestURI(); if (excludedUrls == null || excludedUrls.size() == 0) return true; for (String url : excludedUrls) { if (requestUri.endsWith(url)) { return true; } } //这里可以判断用记是否登录、用户权限 HttpSession session = request.getSession(); if (session.getAttribute("user") == null) { throw new Exception("我是来自拦截器的方法"); } else { return true; } } }
mvc配置
<!--定义拦截器,验证登录,验证权限都可以在这里玩耍了--> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="com.tool.SecurityInterceptor"> <!--定义不需要拦截的url集合--> <property name="excludedUrls"> <list> <!-- <value>/HelloWorld/myhello.do</value>--> </list> </property> </bean> </mvc:interceptor> </mvc:interceptors>