SpringVC interceptor + custom annotation for permission interception, springvc permission

Source: Internet
Author: User

SpringVC interceptor + custom annotation for permission interception, springvc permission

1. springmvc configuration file

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemaLocation = "http://www.springframework.org/schema/beanshttp://w License http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <! -- Support for default annotation ing --> <mvc: annotation-driven/> <! -- Load springSwaggerConfig to the spring container --> <bean class = "com. mangofactory. swagger. configuration. SpringSwaggerConfig"/> <! -- Load the custom swagger configuration class to the spring container --> <bean class = "com. aisino. qysds. common. util. SwaggerConfig"/> <! -- Static resource files are not intercepted by Spring MVC --> <mvc: resources mapping = "/api-doc/**" location = "/api-doc/"/> <mvc: resources mapping = "/js/**" location = "/js/"/> <! -- Automatically scans the package name --> <context: component-scan base-package = "com. controller"/> <! -- When IE executes AJAX, the downloaded file is returned in JSON --> <bean id = "mappingJacksonHttpMessageConverter" class = "org. springframework. http. converter. json. mappingJackson2HttpMessageConverter "> <property name =" supportedMediaTypes "> <list> <value> text/html; charset = UTF-8 </value> <value> text/plain; charset = UTF-8 </value> <! -<Value> application/x-www-form-urlencoded; charset = UTF-8 </value> --> </list> </property> </bean> <mvc: interceptors> <mvc: interceptor> <mvc: mapping path = "/**"/> <bean class = "AuthorityAnnotationInterceptor"/> </mvc: interceptor> </mvc: interceptors> <aop: aspectj-autoproxy/> </beans>

2. Customize the Interceptor to implement the HandlerInterceptor interface or inherit the HandlerInterceptor

Import java. util. list; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springframework. web. method. handlerMethod; import org. springframework. web. servlet. handler. handlerInterceptorAdapter; import com. alibaba. fastjson. JSON; public class AuthorityAnnotationInter Ceptor extends HandlerInterceptorAdapter {final Logger logger = LoggerFactory. getLogger (getClass (); @ SuppressWarnings ("unchecked") @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// when swagger is enabled, open // if (handler instanceof ResourceHttpRequestHandler) {// logger. error ("swagger OK"); // return true; //} Authority authority = Null; HandlerMethod handler2 = (HandlerMethod) handler; Class <?> Clazz = handler2.getBeanType (); // class annotation if (clazz. isAnnotationPresent (Authority. class) {authority = clazz. getAnnotation (Authority. class);} // method annotation if (handler2.getMethodAnnotation (Authority. class )! = Null) {authority = handler2.getMethodAnnotation (Authority. class);} if (null = authority) {// No declared permission, allow return true;} logger. debug ("fireAuthority", authority. toString (); HttpSession session = request. getSession (); boolean aflag = false; for (AuthorityType at: authority. authorityTypes () {List <String> role = (List <String>) session. getAttribute ("user permission"); if (role. contains (. getId () {aflag = true; if (aflag) {aflag = true; break ;}} if (false = aflag) {response. getWriter (). println ("no permission") ;}return aflag ;}}

3. Custom permission Annotation

Import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; // supports @ Target ({ElementType. TYPE, ElementType. METHOD}) @ Retention (RetentionPolicy. RUNTIME) @ Documentedpublic @ interface Authority {AuthorityType [] authorityTypes ();}

4. Permission Enumeration

Public enum AuthorityType {ONE ("Level 1", "1"), TWO ("Level 2", "2"), THREE ("Level 3", "3 "),; private String name; private String id; private AuthorityType (String name, String id) {this. name = name; this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getId () {return id;} public void setId (String id) {this. id = id ;}}

5. Controller

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping("/test/allow")@Authority(authorityTypes =AuthorityType.ONE)public class TestController extends BaseController {    @ResponseBody    @RequestMapping(value = "test", method = RequestMethod.GET)    @Authority(authorityTypes =AuthorityType.TWO)    public boolean test() {        return true;    }}

Each request for an interface with the permission needs to verify whether the current user has the permission. If yes, it passes. Otherwise, it fails. The springmvc execution process is attached.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.