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

2024-04-06

我想创建自定义注释并使用该注释将该注释置于方法级别HttpServletRequest目的。到目前为止我这样做了:

已创建注释

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

创建处理程序类

@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;
    }
    
}

创建了一个控制器来调用这样的注释。

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

我的 applicationContext.xml 文件配置为自动组件扫描,但我的注释类仍然没有被调用。任何人都可以让我知道我的错误。


您仍然需要在应用程序上下文中配置拦截器(尽管有自动扫描):

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

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="defaultHandler">
        <ref bean="checkSession"/>
    </property>
</bean>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 spring mvc 中创建自定义注释并获取 httpservletrequest 对象 的相关文章

随机推荐