基于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请求起作用,而过滤 ...
随机推荐
- spring security使用自定义登录界面后,不能返回到之前的请求界面的问题
昨天因为集成spring security oauth2,所以对之前spring security的配置进行了一些修改,然后就导致登录后不能正确跳转回被拦截的页面,而是返回到localhost根目录. ...
- [51nod1355] 斐波那契的最小公倍数
Description 给定 \(n\) 个正整数 \(a_1,a_2,...,a_n\),求 \(\text{lcm}(f_{a_1},f_{a_2},...,f_{a_n})\).其中 \(f_i ...
- WPF DesiredSize & RenderSize
DesiredSize DesiredSize介绍 关于DesiredSize的介绍,可以查看最新微软文档对DesiredSize的介绍 DesiredSize,指的是元素在布局过程中计算所需要的大小 ...
- 【WebAPI No.3】API的访问控制IdentityServer4
介绍: IdentityServer是一个OpenID Connect提供者 - 它实现了OpenID Connect和OAuth 2.0协议.是一种向客户发放安全令牌的软件. 官网给出的功能解释是: ...
- JAVA_接口_默认方法&静态方法
1.小结(注意): 1.接口中无法定义成员变量,但是可以定义常量,其值不可以改变,默认使用public static final修饰 2.接口中,没有构造方法,不能创建对象 3.接口中,没有静态代码块 ...
- spring boot 2.0 整合 elasticsearch6.5.3,spring boot 2.0 整合 elasticsearch NoNodeAvailableException
原文地址:spring boot 2.0 整合 elasticsearch NoNodeAvailableException 原文说的有点问题,下面贴出我的配置: 原码云项目地址:https://gi ...
- Flexbox弹性布局
Flexbox,一种CSS3的布局模式,也叫做弹性盒子模型,用来为盒装模型提供最大的灵活性.最新版本兼容IE11+.firefox.safari.chrome.opera及移动端,但移动端ios7.1 ...
- 怎么打开iPhone的开发者模式
1.需要连接Xcode 2.打开一个app就有了
- 自定义一个全屏的AlertDialog。
........... final MyDialog dialog = new MyDialog(this); LayoutInflater inflater = getLayoutInflater( ...
- 关于如何使用xposed来hook某支付软件
由于近期有业务上的需要,所以特地花时间去研究了一下如何使用hook技术.但是当我把xposed环境和程序编写完成时,突然发现手机上的某个支付软件无法使用了.这个时候我意识到,应该是该软件的安全机制在起 ...