我想创建自定义控制器方法参数注释。
遵循这个问题How to pass a session attribute as method argument (parameter) with Spring MVC并遵循@Bozho的建议,我有这样的事情:
我的解析器
public class SessionAttributeAnnotationResolver implements WebArgumentResolver {
public Object resolveArgument(MethodParameter parameter,
NativeWebRequest request) throws Exception {
System.out.println("I am here");
Annotation[] parameterAnnotations = parameter.getParameterAnnotations();
Class<?> parameterType = parameter.getParameterType();
for (Annotation parameterAnnotation : parameterAnnotations) {
if (SessionAttribute.class.isInstance(parameterAnnotation)) {
SessionAttribute sessionAttribute = (SessionAttribute) parameterAnnotation;
String parameterName = sessionAttribute.value();
boolean required = sessionAttribute.required();
HttpServletRequest httprequest = (HttpServletRequest) request
.getNativeRequest();
HttpSession session = httprequest.getSession(false);
Object result = null;
if (session != null) {
result = session.getAttribute(parameterName);
}
if (result == null && required && session == null)
raiseSessionRequiredException(parameterName, parameterType);
if (result == null && required)
raiseMissingParameterException(parameterName, parameterType);
return result;
}
}
return WebArgumentResolver.UNRESOLVED;
}
protected void raiseMissingParameterException(String paramName,
Class<?> paramType) throws Exception {
throw new IllegalStateException("Missing parameter '" + paramName
+ "' of type [" + paramType.getName() + "]");
}
protected void raiseSessionRequiredException(String paramName,
Class<?> paramType) throws Exception {
throw new HttpSessionRequiredException(
"No HttpSession found for resolving parameter '" + paramName
+ "' of type [" + paramType.getName() + "]");
}
}
注释
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface SessionAttribute {
String value();
boolean required() default true;
}
简单的控制器来测试一切
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method= RequestMethod.GET)
public String t(@SessionAttribute("userEntity") UserEntity e2,Model model,HttpServletRequest req){
System.out.println(req.getSession().getId());
UserEntity e=(UserEntity) req.getSession().getAttribute("userEntity");
System.out.println(e.getName());
System.out.println(e2.getName());
return "login";
}
}
最后,Spring配置
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="customArgumentResolver" ref="sessionAttributeAnnotationResolver"/>
</beans:bean>
<beans:bean id="sessionAttributeAnnotationResolver" class="pl.meble.taboret.utils.SessionAttributeAnnotationResolver"/>
现在,一切对我来说似乎都是为了,但我可能犯了一些愚蠢的错误,因为当控制器被执行时,我得到
F0B282C93B74F8FA3F21A51F46D4D4D5
username
null