全国免费服务热线:

18982081108
✕

成都网站维护公司,网站安全维护,网站SEO优化,网站内容运营

SpringMVC拦截器实现-创新互联

自定义拦截器类
public class SessionInterceptor extends HandlerInterceptorAdapter {

成都创新互联专注于百色网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供百色营销型网站建设,百色网站制作、百色网页设计、百色网站官网定制、微信平台小程序开发服务,打造百色网络公司原创品牌,更为您提供百色网站排名全网营销落地服务。
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下即可;

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。