springMVC :HandlerMethodArgumentResolver+ 自定义注解,自定义解析器实现请求数据绑定方法入参

使用场景:

在接口请求的方法上添加bean参数user,在实际请求时不需要传数据,通过
HandlerMethodArgumentResolver 赋值到user;

sept1

 

package hotkidclub.base;


import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;


import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;


/**
 * 登录的会员(从会话取会员实例)
 * 
 * @author ming
 *
 */
@Documented
@Retention(RUNTIME)
@Target(PARAMETER)
public @interface LoggedinUser {

}

sept2

 


import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * 登錄的的用户(從會話裡面取用户實例)
 */
public class LoggedinUserResolver implements HandlerMethodArgumentResolver {


@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory)
throws Exception {
Member result = null;
try {
HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
if (request.getSession(false) != null) {
result = (User) request.getSession(false).getAttribute("user");
}
}
catch (Exception e) {
}
return result;
}


@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(User.class);
}

}

 

xml配置:


       
           
       

   

你可能感兴趣的:(java常用开发,Spring)