Spring MVC如何添加自定义注解

  提问: 5 年 前 最后更新: 4 年 前 浏览数: 18781

Can anyone explain what I need to do to implement my own annotation that would add functionality to my web requests?

For example:

@Controller public class MyController { 
    @RequestMapping("/abc") 
    @RequiresSomeSpecialHandling 
    public void handleSecureRequest() { 
    } } 

Here @RequiresSomeSpecialHandling would be my own annotation that causes some special work to be done before or after the given web request /abc.

I know that on a very high level I would need to write a bean post processor, scan classes for my annotations, and inject custom mvc interceptors when needed. But are there any shortcuts to simplify this task? Especially for the two examples above.

Thanks in advance,

Spring框架介绍

Can anyone explain what I need to do to implement my own annotation that would add functionality to my web requests?

For example:

@Controller public class MyController { 
    @RequestMapping("/abc") 
    @RequiresSomeSpecialHandling 
    public void handleSecureRequest() { 
    } } 

Here @RequiresSomeSpecialHandling would be my own annotation that causes some special work to be done before or after the given web request /abc.

I know that on a very high level I would need to write a bean post processor, scan classes for my annotations, and inject custom mvc interceptors when needed. But are there any shortcuts to simplify this task? Especially for the two examples above.

Thanks in advance,
http://luju.me/spring/reference/overview.html

提问时间 2012-08-08 15:32

luju.me的头像

luju.me
16 0 3
答案被采用率: 0.0%


不错,不错!

回答于 2013-11-17 11:40

hongzheng的头像

hongzheng
0 0 5
答案被采用率: 0.0%

拦截器实现方式覆盖preHandle方法

public boolean preHandle(HttpServletRequest request,   
            HttpServletResponse response, Object handler) throws Exception {
    try{
    Method m = AnnotationMethodHandlerAdapter.class.getDeclaredMethod("getMethodResolver", Object.class);
    m.setAccessible(true);
    HandlerMethodResolver resolver = (HandlerMethodResolver)m.invoke(annotationMethodHandlerAdapter, handler);
    Method resolveHandlerMethod = resolver.getClass().getMethod("resolveHandlerMethod", HttpServletRequest.class);
    resolveHandlerMethod.setAccessible(true);
    Method currentMethod = (Method)resolveHandlerMethod.invoke(resolver, request);
    AccessPermission AccessPermission = currentMethod.getAnnotation(AccessPermission.class);
    System.out.println(currentMethod.getName() + "="+AccessPermission);
                //获取到自定义注解AccessPermission,处理后续逻辑
    }catch(Exception e){
    e.printStackTrace();
    }

回答于 2013-11-28 11:53

a282149042的头像

a282149042
0 0 1
答案被采用率: 0.0%

注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DuplicateSubmitToken {
	 boolean bindToken() default true;
	 boolean unbindToken() default true;

}
拦截器:
package com.auspiciousclouds.support.spring.mvc.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.support.HandlerMethodResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.auspiciousclouds.config.Configuration;
import com.auspiciousclouds.kit.UUIDKit;
import com.auspiciousclouds.model.domain.UserDomain;
import com.auspiciousclouds.support.spring.mvc.annotation.DuplicateSubmitToken;

public class DuplicateSubmitTokenInterceptor  extends HandlerInterceptorAdapter implements ApplicationContextAware{
	private  ApplicationContext applicationContext ;
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		UserDomain sessionUser = UserDomain.get( request);
		 if (sessionUser != null) {
			 Method method = org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.class.getDeclaredMethod("getMethodResolver", Object.class); 
			 	method.setAccessible(true); 
			    HandlerMethodResolver resolver = (HandlerMethodResolver)method.invoke(applicationContext.getBean("annotationMethodHandlerAdapter"), handler);
			    Method resolveHandlerMethod = resolver.getClass().getMethod("resolveHandlerMethod", HttpServletRequest.class); 
			    resolveHandlerMethod.setAccessible(true); 
			    Method executorMethod = (Method)resolveHandlerMethod.invoke(resolver, request); 
	            DuplicateSubmitToken annotation = executorMethod.getAnnotation(DuplicateSubmitToken.class);
	            if (annotation != null) {
	                boolean bindSession = annotation.bindToken();
	                if (bindSession) {
	                    request.getSession(false).setAttribute(Configuration.SystemConstant.DUPLICATETOKEN, UUIDKit.getUUID());
	                }
	                boolean unbindSession = annotation.unbindToken();
	                if (unbindSession) {
	                    if (isDuplicateSubmitToken(request)) {
	                    	System.out.println("--------------------------------------------------------------------------DuplicateSubmitTokenInterceptor-----------------------------------------------------------------------------");
	                        return false;
	                    }
	                    request.getSession(false).removeAttribute(Configuration.SystemConstant.DUPLICATETOKEN);
	                }
	            }
	        }
	        return true;
	}
	/**
	 * 
	 * isDuplicateSubmitToken 判断是否是重复提交
	 *  
	 * @param request
	 * @return 
	 * boolean
	 * @exception 
	 * @since  1.0.0
	 */
	 private boolean isDuplicateSubmitToken(HttpServletRequest request) {
	        String serverToken = (String) request.getSession(false).getAttribute(Configuration.SystemConstant.DUPLICATETOKEN);
	        if (serverToken == null) {
	            return true;
	        }
	        String clinetToken = request.getParameter(Configuration.SystemConstant.DUPLICATETOKEN);
	        if (clinetToken == null) {
	            return true;
	        }
	        if (!serverToken.equals(clinetToken)) {
	            return true;
	        }
	        return false;
	    }

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

}



使用 :
	@RequestMapping("/home")
	@DuplicateSubmitToken
	public String home(ModelMap model){}

回答于 2014-01-17 15:46

Leon_Open的头像

Leon_Open
0 0 1
答案被采用率: 0.0%

您的回答:

  

powered by Open-Open.com