简体   繁体   中英

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. 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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