Spring 注解拦截器使用详解
2024-10-01 12:30:08
Spring mvc拦截器
平时用到的拦截器通常都是xml的配置方式。今天就特地研究了一下注解方式的拦截器。
配置Spring环境这里就不做详细介绍。本文主要介绍在Spring下,基于注解方式的拦截器。
第一步:定义Interceptor 实现类
public class AuthInterceptor extends HandlerInterceptorAdapter { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class); //没有声明需要权限,或者声明不验证权限
if(authPassport == null || authPassport.validate() == false)
return true;
else{
//在这里实现自己的权限验证逻辑,判断使用session中是否有username,有的话,则验证通过,不拦截。
String username = (String) request.getSession().getAttribute("username");
if(username != null )//如果验证成功返回true
return true;
else//如果验证失败
{
//返回到登录界面
response.sendRedirect(request.getContextPath()+"/account/login");
return false;
}
}
}
else
return true;
}
}
第二步:自定义Annotation实现类,添加于具体某个需要拦截的Controller。
@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthPassport {
boolean validate() default true;
}
第三步:把定义的拦截器加到Spring MVC的拦截体系中。
(1):在SpringMVC的配置文件添加拦截器所需要的schema,
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd" >
(2):添加完schema后,便可以在springMVC的配置文件中直接使用标签:<mvc:interceptors>进行声明拦截器。拦截器声明配置文件代码如下:
<mvc:interceptors>
<!-- 如果不定义 mvc:mapping path 将拦截所有的URL请求 -->
<bean class="com.demo.web.auth.AuthInterceptor"></bean>
</mvc:interceptors>
第四步:在Controller的方法中添加自定义拦截注解。只需要在具体的方法中添加@AuthPassport皆可
@AuthPassport
@RequestMapping(value={"/index","/hello"})
public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", "Hello World!");
modelAndView.setViewName("index");
return modelAndView;
}
通过上面的四步,便可以实现基于注解的方式对url进行拦截。
代码下载地址:http://pan.baidu.com/s/1sjp5B1z
最新文章
- 【转】Python numpy库的nonzero函数用法
- 【Hibernate 6】常用的hql语句以及N+1问题
- 基于WebForm+EasyUI的业务管理系统形成之旅 -- ParamQueryGrid行、列合并(Ⅸ)
- 【转】NDK编译可执行文件在Android L中运行显示error: only position independent executables (PIE) are supported.失败问题解决办法。
- 编译安装mysql5.7.9
- flume日志采集框架使用
- iOS开发之判断用户是否打开APP通知开关
- python实现散列表的链表法
- web前端开发工程师工资多少
- Linux的eth0,eth1,eth2,lo详解
- MySQL数据库、表常用操作
- JavaScript进阶系列1:performace和console.time性能测试
- php中print、echo、print_r、var_dump的区别
- windows 10 透明毛玻璃,winform和wpf方法
- MySQL的GROUP_CONCAT函数
- 51nod 1277 字符串中的最大值
- 2.11 C++转型构造函数
- hadoop分布式集群的搭建
- linux 使用spinlock的配对关系问题
- Alpha冲刺&;总结报告(12/12)(麻瓜制造者)
热门文章
- android 退出系统
- [JZOJ 5895] [NOIP2018模拟10.5] 旅游 解题报告 (欧拉回路+最小生成树)
- Linux mount挂载umount卸载
- System.IO.FileLoadException异常
- jqGrid系列知识
- DotNetCore.1.0.1-VS2015Tools.Preview2.0.2 安装错误分析及解决办法(so far)
- Thread-local storage
- [Python随笔]>;>;range()函数?
- django 获得请求头
- 关于python return 和 print 的区别