Spring MVC method Annotation Blocker

Source: Internet
Author: User
Tags python decorator

The application scenario, at the method level to authenticate the call, such as the API interface has a user uniquely labeled Accesstoken, for each request with Accesstoken can be added to the method of an interceptor, the user to obtain this request, stored in requests or session domain.

In python , the adorner can be used in Python flask to preprocess the method for permission handling

Take a look at an example and use @access_required to intercept:

?
12345678 @api.route(‘/post_apply‘)@access_requireddefapply():    """     活动报名    """    print‘报名者是:‘+g.user    returnjsonify(response_data)

The implementation is simple:

?
12345678910111213 # 验证access_token并保存当前用户到g中defaccess_required(f):    @wraps(f)    defdecorated_func(*args, **kwargs):        access_token = request.values.get(‘access_token‘)        ifaccess_token ==None:            returnerror_msg(‘500‘‘access_token required‘)        ifaccess_token =="":            returnerror_msg(‘500‘‘access_token can not empty‘)        ifis_access_token(access_token) ==False:            returnerror_msg(‘500‘‘invalid_access_token‘)        returnf(*args, **kwargs)    returndecorated_func

in Java , a custom annotation interceptor is implemented to add an annotation to the required interception method @accessrequired

Examples of usages in the Spring MVC controller

?
123456789 /**     * 注解拦截器方法     * @return     */    @RequestMapping(value="/urlinter",method=RequestMethod.GET)    @AccessRequired    public @ResponseBodyString urlInterceptorTest() {        return"通过拦截器:user"+request.getAttribute("currUser");    }

How to implement the above example?

Define an annotation:

?
12345678910 import  < Code class= "Java plain" >java.lang.annotation.elementtype; import  java.lang.annotation.retentionpolicy; import  java.lang.annotation.target; import  java.lang.annotation.retention;   @Target (elementtype.method) @Retention (retentionpolicy.runtime) public   @interface   accessrequired { &NBSP;&NBSP;&NBSP;&NBSP;  

Engage an Interceptor:

?
12345678910111213141516171819202122232425 /** * 拦截url中的access_token * @author Nob  */publicclassUserAccessApiInterceptor extends HandlerInterceptorAdapter {    publicbooleanpreHandle(HttpServletRequest request,            HttpServletResponse response, Object handler) throwsException {        HandlerMethod handlerMethod = (HandlerMethod) handler;        Method method = handlerMethod.getMethod();        AccessRequired annotation = method.getAnnotation(AccessRequired.class);        if(annotation != null) {           System.out.println("你遇到了:@AccessRequired");           String accessToken = request.getParameter("access_token");            /**             * Do something             */            response.getWriter().write("没有通过拦截,accessToken的值为:"+ accessToken);        }        // 没有注解通过拦截        returntrue;    }}

In the spring MVC configuration file:

?
123456789101112 <!-- 拦截器 -->    <mvc:interceptors>        <mvc:interceptor>            <!-- 对所有的请求拦截使用/** ,对某个模块下的请求拦截使用:/myPath/* -->            <mvc:mappingpath="/**"/>            <refbean="userAccessInterceptor" />        </mvc:interceptor>    </mvc:interceptors>    <beanid="userAccessInterceptor"        class="com.banmacoffee.web.interceptor.UserAccessApiInterceptor">    </bean>

When you're done, you can do whatever you want in the interceptor, and load it up any way you like the controller request.

Spring MVC method Annotation Blocker

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.