Home > Java > javaTutorial > body text

SpringMVC Learning Series (9) Detailed explanation of the code to implement annotation-based permission verification

黄舟
Release: 2017-03-03 11:07:03
Original
2057 people have browsed it

Permission management is required for most systems to determine what content different users can see. So how to implement permission verification in Spring MVC? Of course we can continue to use the filter Filter in the servlet to achieve this. But with the help of the action interceptor in Spring MVC, we can implement annotation-based permission verification.

SpringMVC Learning Series (9) Detailed explanation of the code to implement annotation-based permission verification. First introduce the action interceptor:

HandlerInterceptor is the interceptor interface provided by Spring MVC to allow 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;  
}
Copy after login


You can see that the interface has 3 methods, their meanings are as follows:

preHandle: executed before executing the processing logic in the action, it returns boolean, here if we return true, we will continue to execute postHandle and afterCompletion, if we return false, we will interrupt the execution.

postHandle: Executed after executing the logic in the action before returning to the view.

afterCompletion: Executed after the action returns to the view.

HandlerInterceptorAdapter adapter is Spring MVC's default implementation of HandlerInterceptor in order to facilitate our use of HandlerInterceptor. The three methods inside do not do any processing. The preHandle method directly returns true, so that we only need to implement three after inheriting HandlerInterceptorAdapter. In the method, only the method we need is required, unlike inheriting HandlerInterceptor, which must be implemented regardless of whether three methods are needed.

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


# SpringMVC Learning Series (9) Detailed explanation of the code to implement annotation-based permission verification. Let’s complete the annotation permission verification function step by step.

First add an account Controller and login Action and view to simulate jumping to the login page when there is no permission. The contents are as follows:

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

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";
    }
    
}
Copy after login


View login.jsp under the views folder:

nbsp;html PUBLIC "-//W3C//DTD HTML 4.0SpringMVC Learning Series (9) Detailed explanation of the code to implement annotation-based permission verification Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><meta><title>Insert title here</title>
    这里是登录界面
Copy after login


New package com. demo.web.auth, 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;
}
Copy after login


#Add your own interceptor implementation AuthInterceptor inherits 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);            
            //没有声明需要权限,或者声明不验证权限
                if(authPassport == null || authPassport.validate() == false)                return true;            else{                
                //在这里实现自己的权限验证逻辑
                if(false)//如果验证成功返回true(这里直接写false来模拟验证失败的处理)
                    return true;                else//如果验证失败                {                    //返回到登录界面
                    response.sendRedirect("account/login");                    return false;
                }       
            }
        }        else
            return true;   
     }
}
Copy after login

Add the following content to the springservlet-config.xml of the configuration project:

<interceptors>  
    <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> 
    <bean learning series detailed explanation of the code to implement annotation-based permission verification8n.localechangeinterceptor></bean>  
    <!-- 如果不定义 mvc:mapping path 将拦截所有的URL请求 -->
    <bean></bean></interceptors>
Copy after login

In this way, AuthInterceptor processing will be called when executing each action method. When it is judged that the action has the AuthPassport annotation we defined The permission verification logic inside will be executed.

Run the project:

SpringMVC Learning Series (9) Detailed explanation of the code to implement annotation-based permission verification

You can see that the index method of HelloworldController we defined in springservlet-config.xml is executed.

<!-- 如果当前请求为“/”时,则转发到“/helloworld/index" --><view-controller></view-controller>
Copy after login

下面我们在HelloworldController的index方法上加上自定义注解AuthPassport:

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


重新运行项目:

SpringMVC Learning Series (9) Detailed explanation of the code to implement annotation-based permission verification

可以看到正确执行了权限判断逻辑,这样我们只需要在我们在需要权限验证的action上加上这个注解就可以实现权限控制功能了。

 

注解式权限验证的内容到此结束。

 以上就是SpringMVC学习系列(9) 之 实现注解式权限验证的代码详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template