Implementation of annotation-based permission verification in SpringMVC Learning Series (9)

Source: Internet
Author: User

For most systems, permission management is required to determine what users can see. How can we implement permission verification in Spring MVC? Of course, we can continue to use the Filter in servlet for implementation. However, with the help of the action interceptor in Spring MVC, we can implement annotation-based permission verification.

I. first introduce the action Interceptor:

HandlerInterceptor is the interceptor interface provided by Spring MVC for us to implement our own processing logic. The content of HandlerInterceptor is as follows:

public interface HandlerInterceptor {      boolean preHandle(              HttpServletRequest request, HttpServletResponse response,               Object handler)               throws Exception;        void postHandle(              HttpServletRequest request, HttpServletResponse response,               Object handler, ModelAndView modelAndView)               throws Exception;        void afterCompletion(              HttpServletRequest request, HttpServletResponse response,               Object handler, Exception ex)              throws Exception;  }

The interface has three methods, which have the following meanings:

PreHandle: The preHandle is executed before the processing logic in the execution action. It returns a boolean value. If true is returned, the postHandle and afterCompletion are executed. If false is returned, the execution is interrupted.

PostHandle: this operation is executed before the logic in the action is returned to the view.

AfterCompletion: executed after the action returns to the view.

HandlerInterceptorAdapter is the default Implementation of HandlerInterceptor for Spring MVC to facilitate our use of HandlerInterceptor. The three methods in HandlerInterceptor are not processed, and true is directly returned in the preHandle method, in this way, we inherit the HandlerInterceptorAdapter and then only need to implement the methods we need in three methods. Unlike inheriting HandlerInterceptor, whether or not three methods are required must be implemented.

Of course, with HandlerInterceptor, we can implement many other functions, such as logging and request processing time analysis. Permission verification is only one of them.

 

2. Next we will take a step-by-step approach to complete the annotation-based permission verification function.

First, add an account Controller and logon Action and view to simulate the jump to the login page without permission. The content is as follows:

AccountController. java in the com. demo. web. controllers package:

package com.demo.web.controllers;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controller@RequestMapping(value = "/account")public class AccountController {        @RequestMapping(value="/login", method = {RequestMethod.GET})    public String login(){                return "login";    }    }

View login. jsp in the views Folder:

<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 

Create the com. demo. web. auth package and add the custom annotation AuthPassport. The content is as follows:

package com.demo.web.auth;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Documented@Inherited@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface AuthPassport {    boolean validate() default true;}

Add your own Interceptor to implement AuthInterceptor inherited from HandlerInterceptorAdapter. The content is as follows:

Package com. demo. web. auth; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. springframework. web. method. handlerMethod; import org. springframework. web. servlet. handler. handlerInterceptorAdapter; 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); // you do not need to declare the permission, or declare that the permission is not verified if (authPassport = null | authPassport. validate () = false) return true; else {// here implement your own permission verification logic if (false) // If the verification succeeds, return true (here, false is directly written to simulate the processing of the verification failure) return true; else // If the verification fails {// return to the logon interface response. sendRedirect ("account/login"); return false ;}} else return true ;}}

Add the following content to the springservlet-config.xml for configuration items:

<Mvc: interceptors> <! -- If the international operation interceptor is based on (Request/Session/Cookie), you must configure --> <bean class = "org. springframework. web. servlet. i18n. LocaleChangeInterceptor"/> <! -- If mvc is not defined: mapping path will intercept all URL requests --> <bean class = "com. demo. web. auth. authInterceptor "> </bean> </mvc: interceptors>

In this way, the AuthInterceptor will be called to process each action method. When the AuthPassport annotation is defined on the action, the permission verification logic will be executed.

Run the project:

<! -- If the current request is "/", it is forwarded to "/helloworld/index" --> <mvc: view-controller path = "/" view-name = "forward: /helloworld/index "/>

Next we will add the custom annotation AuthPassport to the index method of HelloworldController:

@AuthPassport@RequestMapping(value={"/index","/hello"})public ModelAndView index(){        ModelAndView modelAndView = new ModelAndView();      modelAndView.addObject("message", "Hello World!");      modelAndView.setViewName("index");      return modelAndView;}

Re-run the project:

We can see that the permission judgment logic is correctly executed, so we only need to add this annotation on the action that requires permission verification to implement the permission control function.

 

The content of annotation-based permission verification ends here.

 

Code download: http://pan.baidu.com/s/1ntFOB3N

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.