1.首先在springmvc.xml中添加配置
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/user/**" /> <bean class="com.kingdee.system.interceptor.SecurityInterceptor"> <!-- 定义不过滤的url,需要在拦截器中处理这些,spring不会自动处理 --> <property name="excludedUrls"> <list> <value>/logon</value> <value>/login</value> <value>/register</value> <value>/save</value> <value>/logout</value> </list> </property> </bean> </mvc:interceptor> </mvc:interceptors>
这里配置path的时候主要注意:path的路径写成/user/*只会匹配user下一级的url,如果要匹配以user开头的所有url,则要改成/user/**
2.拦截器代码
这是一个做登录验证的例子,如果验证失败返回到登录页面
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; import com.kingdee.system.exception.AuthorizationException; public class SecurityInterceptor implements HandlerInterceptor { private List<String> excludedUrls; public void setExcludedUrls(List<String> excludedUrls) { this.excludedUrls = excludedUrls; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("intercepter coming..."); //不过滤的url处理 String uri = request.getRequestURI(); for (String url : excludedUrls) { if (uri.endsWith(url)) { return true; } } //interceptor HttpSession session = request.getSession(); if (session.getAttribute("user") == null) { /** * 第一种方案,直接重定向到登录界面,这里需要注意重定向的路径,最好用绝对路径 * 相对于第二种方案,第一种方案好处是减少异常输出,更直观易理解;缺点是硬编码,用绝对路径才能适配所有url */ response.sendRedirect("/springmvc/user/logon"); return false; /*第二种方案,直接抛出异常,在spring配置文件中捕获异常并跳转到对应的url * throw new AuthorizationException(); * */ }else { return true; } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception { } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) throws Exception { } }
代码里的注释已经说明了,我这个demo试验了两种方案。这里的第一种方案的代码,第二种方案需要在springmvc.xml中添加如下配置
<!-- 异常处理 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="com.kingdee.system.exception.AuthorizationException">redirect:/user/logon</prop> </props> </property> </bean>
这里只记录了拦截器的主要代码,AuthorizationException直接继承Exception即可,这里不再贴出,如果有需要源码的可以私信我