需求:
只有用户登录才可访问指定URL的指定页面的数据,对一些URL进行保护。
方案:
采用SpringMVC中的Interceptor拦截器进行自定义拦截。
实施实例:
- 拦截器类方法:
/**
* preHandle方法是进行处理器拦截用的,该方法将在Controller处理之前进行调用,SpringMVC中的Interceptor拦截器是链式的,
* 可以同时存在多个Interceptor,然后SpringMVC会根据声明的前后顺序一个接一个的执行,而且所有的Interceptor中的preHandle
* 方法都会在Controller方法调用之前调用。SpringMVC的这种Interceptor链式结构也是可以进行中断的,
* 这种中断方式是令preHandle的返回值为false,当preHandle的返回值为false的时候整个请求就结束了。
* 当preHandle的返回值为true的时候,表明该资源可以不拦截或者用户已经登录,有访问这些资源的权限
* 说明:1、获取URL;2、通过判断该URL字符串中是否含有指定不需要拦截的资源,对这些资源
* 进行过滤;3、对拦截到的资源进行登录页面跳转;
*/
public class LoginInterceptor implements HandlerInterceptor{
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
//获取请求的URL
String url = request.getRequestURI();
//通过indexof函数扫描URL里面知否含有不用拦截的资源信息
if(url.indexOf("login")>=0){
return true;
}
//访问session里面的用户信息,看用户是否存在
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
//判断用户信息是否为null
if(user != null){
return true;
}
//不符合条件的,跳转到登录界面
request.getRequestDispatcher("/login.jsp").forward(request, response);
return false;
}
}
- SpringMVC配置方式①:
<!--SpringMVC拦截器配置-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.zlt.demo.controller.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
可以拦截此类URL:http://localhost:8080/test-web/test1/main
注意:test-web为项目名称,后面的为类方法映射名称
- SpringMVC配置方式②:
<!--SpringMVC拦截器配置-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*"/>
<bean class="com.zlt.demo.controller.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
可以拦截此类URL:http://localhost:8080/test-web/test1
拦截不住此类URL:http://localhost:8080/test-web/test1/main
注意:test-web为项目名称,后面的为类方法映射名称
- SpringMVC配置方式③:
<!--SpringMVC拦截器配置-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/test1/*"/>
<bean class="com.zlt.demo.controller.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
可以拦截此类URL:http://localhost:8080/test-web/test1
拦截不住此类URL:http://localhost:8080/test-web/test2/main
注意:test-web为项目名称,后面的为类方法映射名称