首页 > 编程语言 > 详细

Spring MVC拦截器

时间:2019-11-12 14:03:35      阅读:68      评论:0      收藏:0      [点我收藏+]

拦截器

什么是拦截器:

  Spring MVC中的拦截器(Interceptor)类似于Servlet中的过滤器(Filter)

  它主要用于拦截用户请求并作相应的处理。

  例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。

  在SpringMVC中通过实现HandlerInterceptor接口实现自定义拦截器类

自定义拦截器类

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器前");
        return true;
    }

    @Override
    public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器中");
    }

    @Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器后");
    }
}

大配置文件

    <!--配置拦截器-->
    <mvc:interceptors>
        <!--可多个 <mvc:interceptor>   -->
        <mvc:interceptor>
            <mvc:mapping path="/threeController/**"/>
            <bean class="com.xiao.Interceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

控制器

@Controller
@RequestMapping("/threeController")
public class threeController {
    @RequestMapping("/one")
    public ModelAndView one(String uname) {
        ModelAndView mv=new ModelAndView();
        System.out.println("进入Controller");
        mv.addObject("uname",uname);
        mv.setViewName("myform");
        return mv;
    }
}

表单

<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/threeController/one" method="post">
        账号:<input type="text" name="uname"><br>
        密码:<input type="password" name="upwd"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

目标页面

<html>
<head>
    <title>欢迎</title>
</head>
<body>
正常进入页面${uname}
</body>
</html>

技术分享图片

 

 

 

 

 

 

Spring MVC拦截器

原文:https://www.cnblogs.com/whtt/p/11841346.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!