I recently stumbled upon some code that I had not seen in this form before. Maybe someone here can help me understand better what's going on.
Namely, I found a method annotated both with #RequestMapping and #ExceptionHandler. I thought that the former were for handling requests, while the latter were for handling exceptions, so I would have thought one normally uses either of both annotations, but not both at the same time.
I found the code snippet here: https://github.com/shopizer-ecommerce/shopizer/blob/2.5.0/sm-shop/src/main/java/com/salesmanager/shop/store/api/exception/RestErrorHandler.java#L24
The code snippet is:
#RequestMapping(produces = "application/json")
#ExceptionHandler(Exception.class)
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public #ResponseBody ErrorEntity handleServiceException(Exception exception) {
log.error(exception.getMessage(), exception);
ErrorEntity errorEntity = createErrorEntity(null, exception.getMessage(),
exception.getLocalizedMessage());
return errorEntity;
}
I have two questions:
According to the Spring documentation on #RequestMapping, un-annotated method parameters (that are not of some special type) of a #RequestMapping method are implicitly annotated with #ModelAttribute (see "Any other argument" at the end of the table under the above link). So in the above code snippet, is the Exception parameter implicitly annotated with #ModelAttribute as well? And if yes, does that make sense?
Can it generally make sense to annotate a method with both #RequestMapping and #ExceptionHandler (e.g., to handle both requests and exceptions), or would that be bad form?
good question.
I would say try this. on a controller, take two methods. on one method use just RequestMethod and write a code by accepting a model attribute from page.
On this method, create a scenario for a NullPointerException.
On method 2, annotate both RequestMapping and ExceptionHandler. And you can see whether you are getting the request, response with ModelAttributes from method one to method 2.
if yes, then this would help us evaluate the exception and handle invalid scenarios where we would need the model attribute values.
Also as per the explanation that you have pasted above, ModelAttribute is implicit for RequestMapping, not for all annotations on a controller method.
Please let us know.
Related
I have a method annotated with #PreAuthorize(...) with some logic that goes away and queries an API for some information about what the user can view. However, I have this endpoint that I need to add this #PreAuthorize annotation into which receives in a more "complex" object which I want to transform slightly (the object contains an array that is some cases I want to add/remove data from).
#PostMapping("/search")
#PreAuthorize("#Service.isAuth(#searchParam)")
public ResponseEntity<Response> search(SearchParams searchParam) {
return service.getSearchResult(searchParam);
}
Is there a way I can modify searchParam inside the #PreAuthorize annotation then have it passed into the method body, I know that this is probably is not the correct way to do this and maybe isn't something that #PreAuthorize wasn't designed for but is there any way of doing this even with a different type of annotation. Obviously worst case I can move the logic into the method body but I would prefer to use an annotation-based solution like #PreAuthorize offers if possible. Thanks for any help even links to other relevant things would be useful I've not found much on google related to this.
I think the best solution is to make a handler/interceptor and then annotate it with #PreAuthorize. So I think you are in the right track but you need to make sure that you modify your code to implement the HandlerMapping interface to create the interceptor and then override the prehandle method. After you need to annotate it with #PreAuthorize programatically. The last thing will be to use a wrapper to modify the HttpWrapper, it cannot be done manually. Here links to the relevant resources in order:
Creating a Handler/Interceptor: https://www.baeldung.com/spring-mvc-handlerinterceptor
Using PreAuthorise in the interceptor: How can I require that all request handlers in my Spring application have #PreAuthorize
To modify the HttpServlet request you will need a wrapper: How to modify HttpServletRequest body in java?
Have a try, hopefully that works.
Snippet of code taken from second link uses a programatic PreAuthorize rather than annotation:
public class PreAuthorizeChecker implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler;
PreAuthorize annotation = AnnotationUtils.findAnnotation(hm.getMethod(), PreAuthorize.class);
//TODO use the technique shown on the third link to wrap and modify the HttpServletRequest
if (annotation == null) {
// prevent access to method wihout security restrictions
throw new RuntimeException("Rights are not defined for this handler");
}
}
return true;
}
.....
I'm developing a REST webservice with Spring MVC and I've implemented a custom annotation in order to annotate controller methods with it. This annotation may include a SpEL expression which I must evaluate considering controller method argument values. So, my idea is to implement a Spring MVC interceptor for this but the parameter HandlerMethod in the preHandle method is just a way to identify the method and does not provide access to controller method argument values. So, the only approach I can think of is to develop a Spring AOP aspect and intercept all the calls to annotated methods. By the way, I need access to the request, so if I go by the AOP way, all the annotated methods should include an argument with the request.
So, my question is: Is there any way to access the method argument values from thr Spring MVC interceptor or should I go the Spring AOP way?.
Thanks in advance.
You cannot use the controller method parameter in the preHandle method of an interceptor, because at the time of calling it, the parameters of the controller method have not been constructed (except for request and response).
So you will have to go the AOP way (do not forget to implement a method in your controllers ...) like explained in JavaBond answer. But thanks to spring framework, you can avoid that all the annotated methods should include an argument with the request. RequestContextHolder.getRequestAttributes() gives you a RequestAttributes object. If you know that your request is a HttpServletRequest, you can cast it to a ServletRequestAttributes and then access the native request via the getRequest() method :
RequestAttributes reqAttr = RequestContextHolder.getRequestAttributes();
HttpServletRequest req = ((ServletRequestAttributes) reqAttr).getRequest();
You should go the AOP way.
Write an Around advice against your custom annotation. The around advice should have a ProceedingJoinPoint argument. Using this you can get the annotated methods arguments values via proceedingJoinPoint.getArgs()
Sample advice shown below
#Around("#annotation(yourCustomAnnotation)")
public Object arooundAdvice(ProceedingJoinPoint joinpoint,
YourCustomAnnotation yourCustomAnnotation) throws Throwable {
Object args[] = joinpoint.getArgs();
// iterate over the args[] array to get the annotated method arguments
return joinpoint.proceed();
}
I have tried to find the answer to this, but I cannot seem to find what I am looking for. So I apologize if this question already exists.
PROBLEM:
I want to be able to access the request type of a request inside of a generic method within my Controller.
DESCRIPTION:
Using Spring ROO and Spring MVC, I have developed a small web service that will respond with certain tidbits from a database when queried. In one of my controller classes, I have some methods that handle some variety of GET, PUT, POST, etc., for the URIs that are mapped within the #RequestMapping parameter.
For example:
#RequestMapping(method = RequestMethod.Get, value = "/foo/bar")
#ResponseBody
public ResponseEntity<String> getFooBar() {
// stuff
}
If a request is made to the web service that it is not currently mapped, a 405 error is returned (which is correct), but I want to return more information along with a 405 response. Maybe respond with something like:
"I know you tried to execute a [some method], but this path only handles [list of proper methods]."
So I wrote a short method that only has the RequestMapping:
#RequestMapping(value = "/foo/bar")
I have found that the method with this mapping will catch all unhandled request types. But I am having trouble accessing the information of the request, specifically the type, from within the method.
QUESTION:
A. How can I access the request type from within the method? OR
B. Is this the right approach? What would be the right approach?
EDIT
ANSWER:
I added a HttpServletRequestobject to the method parameters. I was able to access the method type from that.
I tried using HttpRequest, but it didn't seem to like that much.
Thanks all!
You can add a method parameter of HttpServletRequest, but I think you'd be better off continuing to reply with 405. A client should then make an HTTP OPTIONS call (see How to handle HTTP OPTIONS with Spring MVC?) and you can return the list of allowed methods there.
A. you can access request if you mentioned it as parameter in controller method
public ... getFooBar(HttpRequest request) {
...
}
B. you do not need to add any other description as the 405 status is descriptive.
In answer to "A", just add "HttpRequest req" as an additional argument to your controller methods. Spring will automatically inject a reference to the request, and you can play with headers to your heart's content.
In answer to "B" - "What would be the right approach", how about this?
In order to return that 405, Spring has raised a MethodArgumentNotValidException. You can provide custom handling for this like so:
#ExceptionHandler(MethodArgumentNotValidException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ResponseBody
public MyMethodArgumentMessage handleMathodArgumentNotValidException(
MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
MyMethodArgumentMessage myMessage =
new MyMethodArgumentMessage(result.getFieldErrors());
return myMessage;
}
You should take a look at the #ExceptionHandler annotation. This lets you add methods such as the following to your controller. You can define your own exceptions and appropriate custom handlers for them. I use it to return well-structured XML and JSON from REST services. Although for it to work, you need to throw specific exceptions from your controller methods.
A good walk-through of using this was provided by Petri Kainulkainen in his blog:
http://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-adding-validation-to-a-rest-api/
According to Spring documentation, this annotation indicates that a method return value should be bound to the web response body. I understand that, and I've been using this for my ajax calls. However, I recently came across code that doesn't use the annotation.
So I guess my question really is why it works without the annotation?
Without the annotation, a different process takes place. Depending on the return type (you can find the defaults in this document) the response will be generated differently.
For example, if your return type is String, then, by default, the return value will be resolved as a View name, a ViewResolver will try to resolve and create a View object, and a RequestDispatcher will forward/include/redirect to it (ex. a jsp) so that the Servlet container can handle generating the response.
The actual interface that handles the return type is HandlerMethodReturnValueHandler and there are many implementations for each type. See here for more information.
We've got a couple of #RequestMapping annotated controllers methods that do stuff. They each have more than 1 argument that we would like to be bound. For example:
#RequestMapping(value = "/a/b", method = RequestMethod.GET)
#ResponseBody
public Response getAB(ARequest aRequest, BRequest bRequest) throws ServiceException {
...
}
This obviously works fine. However, one quirk in our requirements is that we get request parameters that contain underscores. For example; on the endpoint above we'd get a request that looks like: http://x:8000/a/b?req_param=1. This causes default Spring binding to fail, because in our objects we'd like to have bound we define req_param camel-cased (reqParam) rather than use underscores in our Java code.
To solve this we have implemented our own annotation (#Camelize) and our own custom WebArgumentResolver, which we've registered in the Spring context. We then annotate our controller method arguments with #Camelize, which causes our custom WebArgumentResolver to step in and correct the binding. This also works fine.
Now the issues arise, more specifically it would appear that when we want to also validate our arguments this fails. For example, continuing with the example above:
#RequestMapping(value = "/a/b", method = RequestMethod.GET)
#ResponseBody
public Response getAB(#Camelize #Valid ARequest aRequest, Errors aRequestErrors, BRequest bRequest) throws ServiceException {
...
}
This fails with the exception: java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!.
It would appear that we cannot use our custom WebArgumentResolver and validate using #Valid at the same time. We have narrowed it down to the custom WebArgumentResolver, in the sense that as soon as this doesn't return UNRESOLVED, Spring MVC will just not bother with validation and throw the exception above.
Can anyone confirm that this is the expected behaviour?
Is there a work-around for this? Currently we're thinking about removing the custom WebArgumentResolver and replacing it with a filter, but this seems very intrusive for what we need.
Thanks!
Edit: we're using Spring 3.0.5.