1.ssm框架的拦截器是在springmvc-servlet.xml配置文件中进行配置
<!-- 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="cn.com.***.controller.common.SecurityInterceptor">
<!-- 不需要session验证的地址 -->
<property name="excludeUrls">
<list>
<value>/web/index</value>
<value>/web/aboutsPage</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
2.创建一个拦截器实体类,继承HandlerInterceptor,重写它的方法,preHandle是调用Controller具体方法之前拦截,postHandle是调用Controller具体方法之后拦截,afterCompletion是完成页面后调用,所以在preHandle里面写逻辑代码,如登入之后怎么做,没登录这么做,或者根据不同的登录平台进行跳转之类的逻辑
package cn.com.***.controller.common; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import cn.com.***.common.pojo.WSessionInfo; import cn.com.***.common.result.Constant; /** * 权限拦截器 */ public class SecurityInterceptor implements HandlerInterceptor { private List<String> excludeUrls;// 不需要拦截的资源 private List<String> wapUrls;//wapurl public List<String> getWapUrls() { return wapUrls; } public void setWapUrls(List<String> wapUrls) { this.wapUrls = wapUrls; } public List<String> getExcludeUrls() { return excludeUrls; } public void setExcludeUrls(List<String> excludeUrls) { this.excludeUrls = excludeUrls; } /** * 完成页面的render后调用 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception { } /** * 在调用controller具体方法后拦截 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception { } /** * 在调用controller具体方法前拦截 */ @SuppressWarnings("unchecked") @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { //请求的路径 String contextPath=request.getContextPath(); String url=request.getServletPath().toString(); StringBuffer realUrl = request.getRequestURL(); WSessionInfo sessionInfo = (WSessionInfo) request.getSession().getAttribute(Constant.SESSION_INFO);
if(excludeUrls.contains(url)){
return true ;
}
if (sessionInfo == null) { String isqian = url.substring(0, 4); if (isqian.equals("/wap")) { response.sendRedirect(contextPath + "/wap/adminLogin"); return true; }if (isqian.equals("/web")) { response.sendRedirect(contextPath + "/web/index"); } else if (realUrl.toString().equals(contextPath +"/web/index")) { response.sendRedirect(contextPath + "/wap/adminLogin"); return true; } } return true ; } }