基于SpringMVC拦截器和注解实现controller中访问权限控制
SpringMVC的拦截器HandlerInterceptorAdapter对应提供了三个preHandle,postHandle,afterCompletion方法。
- preHandle在业务处理器处理请求之前被调用;
- postHandle在业务处理器处理请求执行完成后,生成视图之前执行;
- afterCompletion在DispatcherServlet完全处理完请求后被调用,可用于清理资源等;
所以要想实现自己的权限管理逻辑,需要继承HandlerInterceptorAdapter并重写其三个方法。
一、自定义拦截器配置方法
- 在sping的xml配置中可以用<mvc:interceptors>和<mvc:interceptor>来配置拦截器类(实现HandlerInterceptorAdapter)
- 在javaConfig中配置通过WebMvcConfiguration的实现类配置拦截器类(实现HandlerInterceptorAdapter)
二、示例
2.1、javaconfig中配置SpringMVC示例
1、新建一个springboot项目auth-demo2
2、权限校验相关的注解

package com.dxz.authdemo2.web.auth; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Permission {
/** 检查项枚举 */
PermissionEnum[] permissionTypes() default {}; /** 检查项关系 */
RelationEnum relation() default RelationEnum.OR;
} package com.dxz.authdemo2.web.auth; import java.io.PrintWriter;
import java.lang.annotation.Annotation; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /**
* 权限检查拦截器
*/
@Component
public class PermissionCheckInterceptor extends HandlerInterceptorAdapter {
/** 权限检查服务 */
@Autowired
private PermissionCheckProcessor permissionCheckProcessor;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//Class<?> clazz = handler.getClass();
Class<?> clazz = ((HandlerMethod)handler).getBeanType();
System.out.println("PermissionCheckInterceptor.preHandle()" + clazz);
for(Annotation a : clazz.getAnnotations()){
System.out.println(a);
}
if (clazz.isAnnotationPresent(Permission.class)) {
Permission permission = (Permission) clazz.getAnnotation(Permission.class);
return permissionCheckProcessor.process(permission, request, response);
}
return true;
} public boolean preHandle2(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("SecurityInterceptor:"+request.getContextPath()+","+request.getRequestURI()+","+request.getMethod());
HttpSession session = request.getSession();
if (session.getAttribute("uid") == null) {
System.out.println("AuthorizationException:未登录!"+request.getMethod());
if("POST".equalsIgnoreCase(request.getMethod())){
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.write("未登录!");
out.flush();
out.close();
}else{
response.sendRedirect(request.getContextPath()+"/login");
}
return false;
} else {
return true;
}
}
} package com.dxz.authdemo2.web.auth; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component;
@Component
public class PermissionCheckProcessor {
public boolean process(Permission permission, HttpServletRequest request, HttpServletResponse response) {
PermissionEnum[] permissionTypes = permission.permissionTypes();
try {
String uid = request.getParameter("uid");
if ("duanxz".equals(uid)) {
System.out.println("认证成功");
return true;
} else {
System.out.println("认证失败");
return false;
}
} catch (Exception e) {
return false;
}
}
} package com.dxz.authdemo2.web.auth; public enum PermissionEnum {
DEVELOPER_VALID, DEVELOPER_FREEZE;
} package com.dxz.authdemo2.web.auth; public enum RelationEnum {
OR, AND;
}

3、SpringMVC拦截器配置

package com.dxz.authdemo2.web.auth; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter { @Autowired
PermissionCheckInterceptor permissionCheckInterceptor; @Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
// 映射为 user 的控制器下的所有映射
registry.addInterceptor(permissionCheckInterceptor).addPathPatterns("/admin/*").excludePathPatterns("/index", "/");
super.addInterceptors(registry);
}
}

4、测试controller

package com.dxz.authdemo2.web; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; import com.dxz.authdemo2.web.auth.Permission;
import com.dxz.authdemo2.web.auth.PermissionEnum; @Controller
@RequestMapping("/admin")
@Permission(permissionTypes = { PermissionEnum.DEVELOPER_VALID })
public class AppDetailController {
@RequestMapping(value="/appDetail", method = RequestMethod.GET)
public String doGet(ModelMap modelMap, HttpServletRequest httpServletRequest) {
//1. 业务操作,此处省略
System.out.println("appDetail.htm 处理中...");
return "appDetail";
}
} package com.dxz.authdemo2.web; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import com.dxz.authdemo2.web.auth.Permission;
import com.dxz.authdemo2.web.auth.PermissionEnum; @Controller
@RequestMapping("index")
public class IndexController {
@RequestMapping(method = RequestMethod.GET)
public void doGet(ModelMap modelMap, HttpServletRequest httpServletRequest) {
System.out.println("index");
}
}

cotroller中的jsp文件appDetail.jsp
<html>
<h1>appDetail</h1>
</html>
启动类:

package com.dxz.authdemo2; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver; @EnableWebMvc
@EnableAutoConfiguration
@SpringBootApplication
public class AuthDemo2Application { public static void main(String[] args) {
SpringApplication.run(AuthDemo2Application.class, args);
} // 配置JSP视图解析器
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}

结果:
访问:http://localhost:8080/admin/appDetail?uid=duanxz2

访问:http://localhost:8080/admin/appDetail?uid=duanxz

2.2、xml中配置SpringMVC示例
首先在springmvc.xml中加入自己定义的拦截器我的实现逻辑PermissionCheckInterceptor,如下:
基于SpringMVC拦截器和注解实现controller中访问权限控制的更多相关文章
- SpringMVC之八:基于SpringMVC拦截器和注解实现controller中访问权限控制
SpringMVC的拦截器HandlerInterceptorAdapter对应提供了三个preHandle,postHandle,afterCompletion方法. preHandle在业务处理器 ...
- spring mvc:内部资源视图解析器2(注解实现)@Controller/@RequestMapping
spring mvc:内部资源视图解析器2(注解实现) @Controller/@RequestMapping 访问地址: http://localhost:8080/guga2/hello/goo ...
- SpringMVC拦截器+Spring自定义注解实现权限验证
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- SpringMVC拦截器(实现登录验证拦截器)
本例实现登陆时的验证拦截,采用SpringMVC拦截器来实现 当用户点击到网站主页时要进行拦截,用户登录了才能进入网站主页,否则进入登陆页面 核心代码 首先是index.jsp,显示链接 <%@ ...
- Spring+SpringMVC+MyBatis深入学习及搭建(十七)——SpringMVC拦截器
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7098753.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十六)--S ...
- SpringMVC拦截器与异常处理
点击查看上一章 在我们SpringMVC中也可以使用拦截器对用户的请求进行拦截,用户可以自定义拦截器来实现特定的功能.自定义拦截器必须要实现HandlerInterceptor接口 package c ...
- Java过滤器与SpringMVC拦截器的差异学习笔记
学习摘录地址:http://blog.csdn.net/chenleixing/article/details/44573495 今天学习和认识了一下,过滤器和SpringMVC的拦截器的区别,学到了 ...
- Springboot中SpringMvc拦截器配置与应用(实战)
一.什么是拦截器,及其作用 拦截器(Interceptor): 用于在某个方法被访问之前进行拦截,然后在方法执行之前或之后加入某些操作,其实就是AOP的一种实现策略.它通过动态拦截Action调用的对 ...
- Java过滤器(Filter)与SpringMVC拦截器(Interceptor)之间的关系与区别
过滤器和拦截器的区别: ①拦截器是基于java的反射机制的,而过滤器是基于函数回调. ②拦截器不依赖与servlet容器,过滤器依赖与servlet容器. ③拦截器只能对action请求起作用,而过滤 ...
随机推荐
- ELK-Logstash采集日志和输送日志流程测试
讲解Logstash采集日志和输送日志流程测试,包括input,filter和output元素的测试 配置一:从elasticsearch日志文件读取日志信息,输送到控制台 $ cd /home/es ...
- RDIFramework.NET ━ .NET快速信息化系统开发框架 V3.2-新增锁定用户与解除锁定用户的功能
锁定用户功能在现实应用场景中得到了大量的应用,当我们需要限制某用户的登录,又不能删除这个用户时就可以使用锁定功能,如:未授权的用户尝试错误密码错误过多可以尝试的用户进行锁定,又如ATM机上取钱时密码错 ...
- 多种Timer的场景应用
前言 今天讲讲各种Timer的使用. 三种Timer组件 .Net框架提供了三种常规Timer组件,分别是System.Windows.Forms.Timer.System.Timers.Timer和 ...
- 日志模块logging用法
一.常用日志记录场景及最佳解决方案: 日志记录方式 最佳记录日志方案 普通情况下,在控制台显示输出 print() 报告正常程序操作过程中发生的事件 logging.info()(或者更详细的logg ...
- Django 系列博客(十一)
Django 系列博客(十一) 前言 本篇博客介绍使用 ORM 来进行多表的操作,当然重点在查询方面. 创建表 实例: 作者模型:一个作者有姓名和年龄. 作者详细模型:把作者的详情放到详情表,包含生日 ...
- javascript小实例,阻止浏览器默认行为,真的能阻止吗?支持IE和标准浏览器的阻止默认行为的方法
看到这标题,是不是有点逆天的感觉,总感觉好狂拽炫酷,耳边隐隐约约传来一个声音:你这么叼,你咋不上天呢! ~~ 额,好吧! 话入正题,我为什么会提出这么一个问题呢? 阻止浏览器默认行为,真的能阻止吗?那 ...
- 解决ajax跨域问题
JQuery ajax支持get方式的跨域,采用了jsonp来完成.完成跨域请求的有两种方式实现.一种是使用Jquery ajax最底层的Api实现跨域的请求,而另一种则是JQuery ajax的高级 ...
- python-IO编程,文件读写
一.文件读写 1.打开文件 函数:open(name[. mode[. buffering]]) 参数: name:必须:文件的文件名(全路径或执行文件的相对路径.)) mode:可选:对文件的读写模 ...
- Java 学习笔记 两大集合框架Map和Collection
两大框架图解 Collection接口 由第一张图,我们可以知道,Collection接口的子接口有三种,分别是List接口,Set接口和Queue接口 List接口 允许有重复的元素,元素按照添加的 ...
- Echarts地图使用经验-地图变形和添加数据
关于echart2,echart3地图的使用一点人生经验: 1.echart3,echart2加载地图变形修复. 最近在使用echart2使用过程中,发现加载海南地图会产生变形.如下图,海南地图产生了 ...