Java tutorial
package com.miserablemind.butter.resolvers.user; import com.miserablemind.butter.domain.model.user.user.AppUser; import org.springframework.core.MethodParameter; import org.springframework.security.core.Authentication; import org.springframework.web.bind.support.WebArgumentResolver; 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; import java.security.Principal; /* * Miserable Mind * http://www.butter.miserablemind.com * The MIT License (MIT) */ /** * Method Argument Resolver for @{@link ActiveUser}. It allows to wire authenticated user to controller methods via * {code @ActiveUser} annotated method argument. * * @author <a href="http://www.miserablemind.com" target="_blank">miserablemind</a> */ public class ActiveUserMethodArgumentResolver implements HandlerMethodArgumentResolver { /** * Checks if parameter is of the right type and has correct annotation (@ActiveUser in this case) * * @param methodParameter parameter being resolved. * @return {@code true} if parameter is supported. */ @Override public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.getParameterAnnotation(ActiveUser.class) != null && methodParameter.getParameterType().equals(AppUser.class); } /** * Resolves the method parameter. Overrides {@link HandlerMethodArgumentResolver} method resolveArgument. * * @param methodParameter parameter being resolved. Value is used for passing to supportsParameter method. * @param mavContainer model and view container. In this instance it is not used for anything. * @param webRequest web request used for getting the principal. * @param binderFactory WebDataBinderFactory. In this case it is not used for anything. * @return {@link AppUser} app user if there is an authenticated user. {@code null} if there is no authenticated user, * {@code WebArgumentResolver.UNRESOLVED} if method parameter is not supported. * @throws Exception */ @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { if (this.supportsParameter(methodParameter)) { Principal principal = webRequest.getUserPrincipal(); if (null != principal) { return ((Authentication) principal).getPrincipal(); } else { return null; } } return WebArgumentResolver.UNRESOLVED; } }