| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx

Spring MVC如何添加自定义注解

0
HTML Spring MVC C/C++ Go 27220 次浏览

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

6个答案

0
0

 

I hope that you found the information you were looking for. If you still need help with this implementation, let me finish the live career reviews, and then I can help you. I have experience with these annotations.

0

Playing the victor version that is being named as "Road Fighter V" is causing me to feel glad. Now you can gat code here  online. From my own perception and experience of messing around, I think the victor release is the best portion that has been presented for this arrangement.

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){}
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();
    }

0
不错,不错!