I'm trying to add a request parameter with a default value - however I'd like that default value to be the logged in user's name.
I have a method getUsername() which returns the current user's name but I can't set the value of an annotation to a method call (or a class attribute). Here's my method:
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody ResponseEntity<WebUser> getUser(
#RequestParam(value = "username", defaultValue = getUsername()) String username) {
return ResponseEntity.ok(service.getUser(getUsername(), username.toLowerCase()));
}
I can make the RequestParam not required and populate it if null - but this doesn't feel very elegant (or spring-ish). Is there another way to accomplish this?
As suggested by fateddy, the easiest way to do this is by implementing a 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);
}
}
This requires a simple username class:
public class Username {
private String username;
public Username(String username) {
this.username = username;
}
public String getValue() {
return this.username;
}
}
as well as an annotation
#Target(ElementType.PARAMETER)
#Retention(RetentionPolicy.RUNTIME)
public #interface UserRequest {}
In order to get this configured properly this requires a very minor change to the WebMvcConfigurerAdapter:
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new UsernameHandlerMethodArgumentResolver());
}
And that's it. Good to go. Now we can be simply drop the argument into a controller endpoint:
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody ResponseEntity<WebUser> getUser(#UserRequest Username username) {
return ResponseEntity.ok(service.getUser(username, username.toLowerCase()));
}
I am not sure whether you can call method in annotation or not,but you can get user name value just before the #RequestMapping call execution by something like below.
I think this can be achieved using #ModelAttribute.
#ModelAttribute("username")
public String getUserName() {
String name = "XYZ";
return name;
}
And in your #RequestMapping do like below.
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody ResponseEntity<WebUser> getUser(
#ModelAttribute("username") String username) {
return ResponseEntity.ok(service.getUser(username, username.toLowerCase()));
}
Further reading
Related
#RestController()
#RequestMapping(path = "/users")
public class UserController {
#GetMapping()
public #ResponseBody Page<User> getAllUsers(#RequestParam Integer pageSize, UserRequest userRequest) {
//TODO: some implementation
}}
public class UserRequest{
public String name;
public String age;
}
send the request with invalid parameter, like localhost:8800/users?name1=1234, I want to return error. but in fact it ignore the invalid parameter name1.
I tried to add the user defined annotation on the method parameter and on the class , codes like below
#RestController()
#RequestMapping(path = "/users")
#Validated
public class UserController {
#GetMapping()
public #ResponseBody Page<User> getAllUsers(#RequestParam #Validated Integer pageSize, #Validated UserRequest userRequest} {
//TODO: some implementation
}
}
But it does not working.
I think it is happened because framework has ignore the invalid parameter before the method was called.
where did framework handle the url and how can I do to make it return error instead of ignore?
You can reject parameters that are not valid. You can do so in a HandlerInterceptor class.
Reference: Rejecting GET requests with additional query params
In addition to what is done in the above reference, in your addInterceptors, you can specify the path that is intercepted.
Like this:
#Configuration
public class WebConfig implements WebMvcConfigurer {
private String USERS_PATH = "/users";
// If you want to cover all endpoints in your controller
// private String USERS_PATH = List.of("/users", "/users/**");
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FooHandlerInterceptor()).addPathPatterns(USERS_PATH);
}
}
I have a web application with spring, one rest endpoint receives a value encrypted like this:
#RequestMapping(value = "/welcome", method = RequestMethod.GET)
public resp welcome(
#RequestHeader(name = "user") String user,
#Encripted #RequestHeader(name = "password") String password
I'm creating the annotation #Encripted like this:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.PARAMETER)
public #interface Encripted {
}
now I need to manipulate the String that got annotated and change its value, how could I override or implement to achieve this goal? I can't find example with ElementType.PARAMETER,
Lets say you created WelcomeController and Encrypted classes in com.example.controller like so,
package com.example.controller;
public class WelcomeController {
#RequestMapping(value = "/welcome", method = RequestMethod.GET)
public void welcome(
#RequestHeader(name = "user") String user,
#Encrypted #RequestHeader(name = "password") String password
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.PARAMETER)
public #interface Encrypted {
String value() default "";
}
In order to process the Annotation you need to create an Aspect class like so --
#Aspect
public class MyAspect {
#Pointcut("execution(#com.example.controller.WelcomeController * *(#com.example.controller.Encrypted (*), ..)) && args(password)")
public void encryptedMethod(String password) {}
#Around("encryptedMethod(password)")
public Object encryptedMethod(ProceedingJoinPoint pjp, String password) throws Throwable {
// process the password string ...
return pjp.proceed();
}
}
Check more on the AOP with Spring here -- https://www.baeldung.com/spring-aop
I have a flag DISABLE_FLAG and I want to use it to control multiple specific APIs in different controllers.
#RestController
public final class Controller1 {
#RequestMapping(value = "/foo1", method = RequestMethod.POST)
public String foo1()
}
#RestController
public final class Controller2 {
#RequestMapping(value = "/foo2", method = RequestMethod.POST)
public String foo2()
}
I can use an interceptor to handle all the urls. Is there a easy way to do that like annotation?
You could use AOP to do something like that.
Create your own annotation...
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Maybe { }
and corresponding aspect...
#Aspect
public class MaybeAspect {
#Pointcut("#annotation(com.example.Maybe)")
public void callMeMaybe() {}
#Around("callMeMaybe()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// do your logic here..
if(DISABLE_FOO) {
// do nothing ? throw exception?
// return null;
throw new IllegalStateException();
} else {
// process the request normally
return joinPoint.proceed();
}
}
}
I don't think there is direct way to disable a constructed request mapping but We can disable API in many ways with some condition.
Here is the 2 ways disabling by spring profile or JVM properties.
public class SampleController {
#Autowired
Environment env;
#RequestMapping(value = "/foo", method = RequestMethod.POST)
public String foo(HttpServletResponse response) {
// Using profile
if (env.acceptsProfiles("staging")) {
response.setStatus(404);
return "";
}
// Using JVM options
if("true".equals(System.getProperty("DISABLE_FOO"))) {
response.setStatus(404);
return "";
}
return "";
}
}
If you are thinking futuristic solution using cloud config is the best approach. https://spring.io/guides/gs/centralized-configuration/
Using Conditional components
This allows to build bean with conditions, if the condition failed on startup, the entire component will never be built. Group all your optional request mapping to new controller and add conditional annotation
#Conditional(ConditionalController.class)
public class SampleController {
#Autowired
Environment env;
#RequestMapping(value = "/foo", method = RequestMethod.POST)
public String foo(HttpServletResponse response) {
return "";
}
public static class ConditionalController implements Condition {
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().acceptsProfiles("staging"); // Or whatever condition
}
}
}
You can solve this with annotations by utilizing spring profiles. You define two profiles one for enabled flag and another profile for the disabled flag. Your example would look like this:
#Profile("DISABLED_FLAG")
#RestController
public final class Controller1 {
#RequestMapping(value = "/foo1", method = RequestMethod.POST)
public String foo1()
}
#Profile("ENABLED_FLAG")
#RestController
public final class Controller2 {
#RequestMapping(value = "/foo2", method = RequestMethod.POST)
public String foo2()
}
Here is the link to the spring framework documentation for this feature: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Profile.html
I did it as follows :
#Retention(RUNTIME)
#Target(ElementType.METHOD)
public #interface DisableApiControl {
}
This class is my customization statement. After could use AOP :
for AbstractBaseServiceImpl :
public abstract class AbstractBaseServiceImpl {
private static boolean disableCheck = false;
public void setDisableChecker(boolean checkParameter) {
disableCheck = checkParameter;
}
public boolean getDisableChecker() {
return disableCheck;
}
}
NOTE : The above class has been prepared to provide a dynamic structure.
#Aspect
#Component
public class DisableApiControlAspect extends AbstractBaseServiceImpl {
#Autowired
private HttpServletResponse httpServletResponse;
#Pointcut(" #annotation(disableMe)")
protected void disabledMethods(DisableApiControl disableMe) {
// comment line
}
#Around("disabledMethods(disableMe)")
public Object dontRun(ProceedingJoinPoint joinPoint, DisableApiControl disableMe) throws Throwable {
if (getDisableChecker()) {
httpServletResponse.sendError(HttpStatus.NOT_FOUND.value(), "Not found");
return null;
} else {
return joinPoint.proceed();
}
}
}
checker parameter added global at this point. The rest will be easier when the value is given as true / false when needed.
#GetMapping("/map")
#DisableApiControl
public List<?> stateMachineFindMap() {
return new ArrayList<>;
}
Is there a way to allow a field as input but exclude it from output in JAX-B? I added #XMLTransient, but that prevents the field from being used as an input field. I'm using Jersey 2.25.1 and Moxy.
The scenario is a password field on a user record. I want to allow it to be passed in when creating a new user record, but I don't want to include it in any responses as part of the user POJO.
EDIT:
I tried the #XmlReadOnly attribute and it seems to have done the trick. It is part of the org.eclipse.persistence.oxm.annotations package.
One way would be to use an XmlAdapter. You could return the result on the unmarshal() and return null on the marhsall()
public class OnlyInputAdapter extends XmlAdapter<String, String> {
#Override
public String unmarshal(String s) throws Exception {
return s;
}
#Override
public String marshal(String v) throws Exception {
return null;
}
}
Then just annotate the password property on the model
#XmlJavaTypeAdapter(OnlyInputAdapter.class)
public String getPassword() {
return this.password;
}
Here's a test
public class PasswordSerializationTest extends JerseyTest {
private User serverUser;
#Path("test")
#Produces("application/json")
#Consumes("application/json")
public class TestResource {
#POST
public User postUser(User user) {
serverUser = user;
return user;
}
}
#Override
public ResourceConfig configure() {
return new ResourceConfig().register(new TestResource());
}
#Test
public void doIt() {
User clientUser = target("test")
.request()
// post string; can't post User as the
// password field wouldn't serialize
.post(Entity.json("{\"password\":\"secret\"}"), User.class);
assertThat(serverUser.getPassword()).isEqualTo("secret");
assertThat(clientUser.getPassword()).isEqualTo(null);
}
}
I want to check if user exists in ControllerAdvice and treat user as #ModelAttribute if user exists. On the other hand, I also want to access user object in #Controller directly. So I add #ModelAttribute annotation on the parameter of #RequestMapping method.
I'm using #ControllerAdvice like:
#ControllerAdvice
public class UserAdvice {
#Autowired
private UserService userService;
#ModelAttribute("user")
public User user(#PathVariable("username") String username) {
User user = userService.findByUsername(username);
if (user != null) {
return user;
}
user = userService.findById(username);
if (user == null) {
throw new ResourceNotFoundException("user not found");
}
return user;
}
}
And UserController Like:
#RestController
#RequestMapping("/users/{username}")
public class UserController {
public static final Logger logger = LoggerFactory.getLogger(UserCourseListController.class);
#Autowired
private CourseService courseService;
#RequestMapping(value = "", method = RequestMethod.GET)
public void getUser(#ModelAttribute("user") User user, Model model) {
logger.info("{}", user);//user is null
logger.info("{}", model.asMap().get("user"));// not null
}
}
But now, the parameter user that annotated with #ModelAttribute is null while there is a "user" obj in Model Map.
Is there any mistakes I've made in this scenario? Or any misunderstanding of the concepts of #ModelAttribute and #ControllerAdvice?
Thanks very much!
Update
From Docs of Springframework:
Once present in the model, the argument’s fields should be populated from all request parameters that have matching names.
So We cannot add #ModelAttribute to method parameters annotated by #RequestMapping directly because Spring will do data binding from request(not Model)。
Finally I found a solution——HandlerMethodArgumentResolver. It can resolve method arguments on each #RequestMapping method and do some work on resolving arguments. An example of Java Config is below:
public class Config extends WebMvcConfigurerAdapter {
#Bean(name = "auditorBean")
public AuditorAware<User> auditorAwareBean() {
return () -> null;
}
#Bean
public HttpMessageConverters customConverters() {
return new HttpMessageConverters(new MappingJackson2HttpMessageConverter());
}
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new HandlerMethodArgumentResolver() {
#Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(User.class);
}
#Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return mavContainer.getDefaultModel().get(parameter.getParameterName());
}
});
}
}
We resolve method arguments from model via parameter.getParameterName(). It mean that the name of method argument(user) must be equal to the value of #ModelAttrubute defined in #ControllerAdvice. You can also use any other naming conventions to implement the binding.