自定义拦截器类
public class SessionInterceptor extends HandlerInterceptorAdapter {
创新互联是一家专业提供三门峡企业网站建设,专注与成都网站建设、成都网站制作、H5建站、小程序制作等业务。10年已为三门峡众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。
public SessionInterceptor() {
// TODO Auto-generated constructor stub
}
private List<String> excludedUrls;
//通过属性注册不需要过滤的url list
public void setExcludedUrls(List<String> excludedUrls) {
this.excludedUrls = excludedUrls;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String requestUrl = request.getRequestURI();
//排除不需要过滤的URL
for(String url:excludedUrls) {
if(requestUrl.endsWith(url)) {
return true;
}
}
//获取当前的会话session
HttpSession session = request.getSession();
if(session.getAttribute("userid") == null) {
//若登录session过期或不存在就跳转到login页面
request.getRequestDispatcher("/login.jsp").forward(request, response);
return false;
}
return true;
}
}
springmvc-servlet.xml 拦截器注册
<mvc:interceptors>
<mvc:interceptor>
<!--
/*的意思是所有文件夹及里面的子文件夹
/是所有文件夹,不含子文件夹
/是web项目的根目录
-->
<mvc:mapping path="/**" />
<!-- 需排除拦截的地址 -->
<!-- <mvc:exclude-mapping path="/login"/> -->
<bean id="commonInterceptor" class="com.skcc.chart.interceptor.SessionInterceptor">
<property name="excludedUrls">
<list>
<value>/login</value>
</list>
</property>
</bean> <!--这个类就是我们自定义的Interceptor -->
</mvc:interceptor>
<!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 -->
</mvc:interceptors>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" order="0" />
<mvc:resources mapping="/js/**" location="/js/" order="0" />
<mvc:resources mapping="/css/**" location="/css/" order="0" />
<!-- Spring MVC不处理静态资源 -->
<mvc:default-servlet-handler />
<!-- 配置注解的处理器映射器和处理器适配器 -->
<mvc:annotation-driven ></mvc:annotation-driven>
HandlerInterceptorAdapter不能拦截WEB-INF目录以外的jsp文件;若需拦截默认index.jsp;可以将index.jsp移动目录到WEB-INF下即可;
本文名称:SpringMVC拦截器实现
文章路径:https://www.cdcxhl.com/article44/jsoiee.html
成都网站建设公司_创新互联,为您提供网站收录、微信小程序、网站改版、响应式网站、App开发、企业建站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联