简体   繁体   English

在 spring mvc 中创建自定义注解并获取 httpservletrequest 对象

[英]creating custom annotation in spring mvc and getting httpservletrequest object

I want to create custom annotation and put that annotation on method level using HttpServletRequest object.我想创建自定义注释并使用HttpServletRequest对象将该注释放在方法级别。 so far I did this:到目前为止,我是这样做的:

Created annotation创建的注释

@Target(value={ElementType.METHOD,ElementType.PARAMETER})
@Retention(value=RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Mapping
public @interface CheckSession{
    boolean isAuthenticate() default false;
}

created handler class创建的处理程序类

@Component
public class CheckSessionClass implements HandlerMethodReturnValueHandler,HandlerMethodArgumentResolver {

    @Override
    public Object resolveArgument(MethodParameter arg0,
            ModelAndViewContainer arg1, NativeWebRequest arg2,
            WebDataBinderFactory arg3) throws Exception {
        logger.info("......MY ANNOTATION CALLEDD.....resolveArgument");
        return null;
    }


    @Override
    public boolean supportsParameter(MethodParameter arg0) {
        logger.info("......MY ANNOTATION CALLEDD.....supportsParameter");
        return false;
    }


    @Override
    public void handleReturnValue(Object retutnValue, MethodParameter returnType,
            ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        CheckSession annotation;
        annotation=returnType.getMethodAnnotation(CheckSession.class);
        if(annotation.isAuthenticate()){
logger.info("......got request is aurhenticated..true");
        }else{
            logger.info("......got request is aurhenticated..false");
        }
    }


    @Override
    public boolean supportsReturnType(MethodParameter arg0) {
        logger.info("......MY ANNOTAION CALLEDD.....supportsReturnType");
        return false;
    }
    
}

created a controller to invoke annotation like this.创建了一个控制器来调用这样的注释。

@Controller
public class MyController 
{
    @RequestMapping(method={RequestMethod.GET, RequestMethod.POST})
    @CheckSession(isAuthenticate=true)
    public ResponseEntity<String> mymethod (HttpServletRequest request)
    {
            ///my code here....
    }
}

My applicationContext.xml file is configured as auto component scan , but still my annotations class is not getting called.can anyone let me know my mistake.我的 applicationContext.xml 文件被配置为自动组件扫描,但我的注释类仍然没有被调用。谁能告诉我我的错误。

You still have to configure the interceptor in your application context (in spite of the auto-scan):您仍然需要在应用程序上下文中配置拦截器(尽管有自动扫描):

<bean id="checkSession" class="CheckSessionClass"/>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="defaultHandler">
        <ref bean="checkSession"/>
    </property>
</bean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM