博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springmvc拦截器
阅读量:4228 次
发布时间:2019-05-26

本文共 2320 字,大约阅读时间需要 7 分钟。

用一个例子来说明,一个小网站,只有用户登录后才可访问,否则被拦截。

要定义拦截器,需要实现Spring的HandleIntercetor接口或者继承抽象类HanlerInterceptorAdater

中间有三个方法,通过例子说明:

public class AuthorizationInterceptor implements HandlerInterceptor {    private static final String[] IGNGRE_URI={
"/loginForm","/login"}; /** * 该方法在Controller处理之前执行。当返回值为true才执行controller,否则不执行。 * @param httpServletRequest * @param httpServletResponse * @param o * @return * @throws Exception */ public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("AuthorizationInterceptor preHandle --> "); boolean flag=false; String servletPath=httpServletRequest.getServletPath(); for(String s:IGNGRE_URI){ if(servletPath.contains(s)){ flag=true; break; } } if(!flag){ User user=(User)httpServletRequest.getSession().getAttribute("user"); if(user==null){ System.out.println("AuthorizationInterceptor 拦截请求:"); httpServletRequest.setAttribute("message","请先登录再访问网站"); httpServletRequest.getRequestDispatcher("loginForm").forward(httpServletRequest,httpServletResponse); }else { System.out.println("AuthorizationInterceptor 放行请求:"); flag=true; } } return flag; } /** * 在controller的方法调用之后执行,方法中可以多modelAndview进行操作 * @param httpServletRequest * @param httpServletResponse * @param o * @param modelAndView * @throws Exception */ public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("AuthorizationInterceptor postHandle -->"); } /** * 该方法在整个请求完成之后执行,主要作用是用于清理资源 * @param httpServletRequest * @param httpServletResponse * @param o * @param e * @throws Exception */ public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("AuthorizationInterceptor afterCompletion --> "); }}
设置拦截所有请求。

转载地址:http://sojqi.baihongyu.com/

你可能感兴趣的文章
利用selenium爬取《西虹市首富影评》
查看>>
Python验证码识别
查看>>
机器学习、NLP和Python教程分享
查看>>
AWS Serverless培训分享
查看>>
python生成二维码
查看>>
在ubuntu上搭建文件服务器
查看>>
ServiceFabric: 在Windows上创建容器应用并部署到ServiceFabric中
查看>>
paramiko——一个专门为Linux设计的模块
查看>>
一个有趣的python项目---一个好玩的网站
查看>>
git常用命令总结
查看>>
Protobuf了解一下?
查看>>
超越Selenium的存在---Pyppeteer
查看>>
复仇者联盟4:终局之战剧透
查看>>
Msgpack有没有兴趣了解一下?
查看>>
探索一家神秘的公司
查看>>
PDF转Word完全免费?这么好的事情我怎么不知道????
查看>>
数据解读---B站火过蔡徐坤的“鬼畜“区巨头们
查看>>
Squid代理服务器搭建亿级爬虫IP代理池
查看>>
JupyterNotebook‘s Magic
查看>>
在Linux 上部署Jenkins和项目
查看>>