全局拦截器

在springmvc.xml文件中配置

拦截器

/**的意思是所有文件夹及里面的子文件夹
/*是所有文件夹,不含子文件夹
/是web项目的根目录

创建两个拦截器
拦截器
拦截器

那么这两个类文件怎么知道是拦截器啊
所以这两个类需要实现拦截器的接口
Interceptor1 implements HandlerInterceptor

拦截器有三个方法
拦截器

一个是最先执行的,一个是最后执行,还有个在二者之间执行

通常我们使用public boolean preHandle
就可以了,在最早执行的时候我们判断用户登录是否正确

测试
测试场景:第一个拦截器放行,第二个拦截器也放行:
当改为true就为放行,当用户输入用户名密码不对就不放行。

拦截器
运行

拦截器

第一个拦截器放行,第二个不放行:

Springmvc官方文档规定:凡是preHandle返回true,afterCompletion必须执行。

这是第一个拦截器Interceptor1。。。preHandle
这是第二个拦截器Interceptor2。。。preHandle
这是第一个拦截器Interceptor1。。。afterCompletion
拦截器

拦截指定路由

拦截器

        <mvc:exclude-mapping path="/login.html" />
        <mvc:exclude-mapping path="/account/login.do" />
        <mvc:exclude-mapping path="/account/regist.do" />

设置拦截所有,但除了edit.do请求

拦截器
拦截器

上面设置之后
在浏览器中输入下面,则无法访问,因为被拦截了
http://localhost:8080/items/list.do
但访问下面则会成功,因为排除拦截了
http://localhost:8080/items/edit.do

实战

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

System.out.println("这是第一个拦截器Interceptor1。。。preHandle");

// 打印请求url地址
System.out.println("===="+request.getServletPath());

//1、请求到登录页面 放行
if(request.getServletPath().startsWith("/user/list.do")) {

    System.out.println("通行");
    return true;
}

//3、如果用户已经登录 放行
if(request.getSession().getAttribute("username") != null) {
    //更好的实现方式的使用cookie
    return true;
}

System.out.println("----"+request.getParameter("id")); // 打印请求参数值
System.out.println("----"+request.getMethod()); // 打印GET

//重定向到登录页面
response.sendRedirect(request.getContextPath() + "/user/list.do");


return true;

}

相关文章:

  • 2021-09-14
  • 2021-09-14
  • 2021-09-14
  • 2018-01-04
  • 2018-06-30
  • 2018-07-10
  • 2018-11-13
  • 2021-02-24
猜你喜欢
  • 2021-10-12
  • 2021-09-14
  • 2019-11-12
  • 2019-07-02
  • 2020-06-16
  • 2021-06-16
  • 2021-09-14
  • 2021-09-14
相关资源
相似解决方案