ssm框架拦截器
Posted 孟夏草木长
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ssm框架拦截器相关的知识,希望对你有一定的参考价值。
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 (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 ; } }
以上是关于ssm框架拦截器的主要内容,如果未能解决你的问题,请参考以下文章
重温SSM框架系列9 - SpringMVC中的拦截器和异常处理