Spring MVC 利用WebArgumentResolver设置controller方法参数

这个接口可以用来设置参数。当然也可以实现它的子接口。
例如:
@Controller
@RequestMapping("test")
public class TestController {
    
    @RequestMapping(value = "login" , method = RequestMethod.GET)
    public String testLogin(HttpSession session){
        session.setAttribute("user", new User("test"));
        return "redirect:/test/user";
    }
    
    @RequestMapping(value = "user" , method = RequestMethod.GET)
    public void testUserResolver(@UserResolver User user){
        System.out.println(user.toString());
    }

}

这里通过了UserResolver annotation来获取User, 而实现WebArgumentResolver,正可以办到这一点。

public class UserArgumentResolver implements WebArgumentResolver{

    @Override
    public Object resolveArgument(MethodParameter parameter, NativeWebRequest req)
            throws Exception {
        UserResolver userResolver = parameter.getParameterAnnotation(UserResolver.class);
        if(userResolver != null){
            return (User)req.getAttribute("user", RequestAttributes.SCOPE_SESSION);
        }
        return UNRESOLVED;
    }

}


配置:

  <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="me.qyh.test.UserArgumentResolver"/>
        </mvc:argument-resolvers>
    </mvc:annotation-driven>