至於建議的fateddy,要做到這一點最簡單的方法是通過實施HandlerMethodArgumentResolver。
public class UsernameHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(Username.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) throws Exception {
String username = nativeWebRequest.getParameter("username");
if (username == null && nativeWebRequest.getUserPrincipal() != null) {
username = nativeWebRequest.getUserPrincipal().getName();
}
return new Username(username);
}
}
這需要一個簡單的用戶名類:
public class Username {
private String username;
public Username(String username) {
this.username = username;
}
public String getValue() {
return this.username;
}
}
以及註釋
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface UserRequest {}
爲了得到這個配置得當,這需要到WebMvcConfigurerAdapter一個非常微小的變化:
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new UsernameHandlerMethodArgumentResolver());
}
就是這樣。很好去。現在,我們可以簡單地拖放參數到控制器端點:
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody ResponseEntity<WebUser> getUser(@UserRequest Username username) {
return ResponseEntity.ok(service.getUser(username, username.toLowerCase()));
}
你可以寫你自己的'HandlerMethodArgumentResolver'(http://docs.spring.io/spring/docs/current/javadoc-api/org/ springframework/web/method/support/HandlerMethodArgumentResolver.html) - 或者如果您使用spring-security - 查看'@ AuthenticationPrincipal'註釋(http://docs.spring.io/autorepo/docs/spring-security/4.0。 3.RELEASE/apidocs/org/springframework/security/core/annotation/AuthenticationPrincipal.html) – fateddy
我認爲HandlerMethodArgumentResolver可能是我最好的選擇。感謝提示 - 我將繼續努力。 – cscan