I am currently working on a rest api and I need to validate the HttpServletRequest object which my Controller method receives. Is there a way to validate it using the #Valid annotation? I need to check the content type, request body? I know we can use the #Valid annotation to validate user defined classes. Can we use the same for HttpServletRequest Class? If not what other options do i have?
thanks,
kayzid
Related
I'm building urls to my controller methods using tools that Spring HATEOAS provides. The problem I see now is that, I can't generate the link with necessary request parameters when I use #ModelAttribute to aggregate these parameters.
I use #ModelAttribute like this not to work with a lot of request parameters in my service:
#GetMapping("/entities")
public Resource<Entity> get(#ModelAttribute Criteria criteria) {
}
When I try to build a link to the method, it does not include accountId that I have in model attribute. I expect it to have as a request parameter.
linkTo(methodOn(MyController.class).get(new Criteria(accountId)))
Is there a way to add #ModelAttribute fields as request parameters? Usually they are sent as request parameters, thus I expected Spring to do it automatically.
I want a controller with the following mapping (incomplete):
#GetMapping(/searchitems)
public #ResponseBody Page<Item> get(Item probe)
From the Item probe parameter I want to query by example in a repository of items and return the result.
Question:
How can I complete the mapping above for a search URL? As search URL I was thinking something like /searchitems?itemAttributeA=foo&itemAttributeB=bar&...itemAttributeZ=xyz. How can I tell spring to inject the passed request parameters into the Item probe fields with the same names?
Adding #ModelAttribute should bind the individual request parameters into your Item POJO.
public #ResponseBody Page<Item> get(#ModelAttribute Item probe)
You can create a POJO and pass as a parameter in the controller class. Pojo should have the fields which you want to read and set. Spring will read and map those attributes in the Pojo which you will define as the request.
#GetMapping(/searchitems)
public ResponseEntity<List<Items>> searchItems(ItemRequest itemRequest) {
}
Only thing needs to be taken care is to check for binding result. If there are errors, we need to stop the request and handle or throw.
For e.g. All of the below attributes in the URL will be set in the Pojo.
https://domain/search-items?pageNumber=1&sortOrder=ascending&itemName=test&itemType=apparel&sortField=itemId&pageSize=5
You can use #RequestParam for this.
public #ResponseBody Page<Item> get(#RequestParam("itemAttributeA") String itemAttributeA ,
#RequestParam("itemAttributeB") String itemAttributeB,...)
Spring MVC controller methods accespt different parameters that are injected before the method is invoked. Like HttpServletRequest, HttpServletResponse, java.security.Principal, etc.
#RequestMapping("/test")
public String test(HttpServletRequest req, Principal user){}
How can I declare something that can be injected in a controlelr method?
#RequestMapping("/test")
public String test(MyCustomInjectable myInjectable){}
More on the specific case:
I want to parse the HttpServletRequest in some servlet filter and construct an object that will be used in the controller method. More precisely I will parse a JWT token and access the claims.
There is an option to create custom HandlerMethodArgumentResolver.
I am trying to avoid declaring/supplying same set of parameters to Spring MVC controller methods used throughout my application.
These are specific spring related parameters and not domain models/application objects.
These parameters include :
Device, Model, Principal, HttpServletRequest, HttpServletResponse.
Is there a way to encapsulate all these into single object (or probably custom annotation) to supply these to all controller methods?
I came across authentication code in my company's java code. The application is a set of several REST services built on Spring MVC. There is a method that gets called in one of the authentication services on the HttpServletRequest object called getHeader(). And the method retrieves an AuthId. Why would they use HttpServletRequest in a spring MVC application? What are the benefits of using this servlet type code in the spring app? What would this method do? Any alternatives?
Spring MVC provides a lot of fabulous abstractions on top of HttpServletRequest, so you can avoid its low-level implementation details. You rarely need to access it directly.
For example, you could get a header value like Content-Type like this:
#GET
#Path("/myService")
public Response doSomething(#HeaderParam("Content-Type") String contentType) {
...
}
But there are times when you do need to access the HttpServletRequest directly--usually when you are using another API that demands it. If you are using some other library with a method you need that takes HttpServletRequest, then you got to grab it from Spring MVC directly.
For example, check out this method in this random UrlUtil class:
public static String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
//Get a path segment
}
You have no choice but to grab HttpServletRequest from Spring MVC.
Spring MVC is built on the Servlet API. Anything you could do with a Servlet, you can therefore do with Spring MVC. What the Spring MVC framework provides is a wrapper to code a web application in a specific architectural style. This wrapper adds behavior and some times simplifies tasks.
Why would they use HttpServletRequest in a spring MVC application?
In this case, because it is the most direct way to get the header.
What are the benefits of using this servlet type code in the spring
app?
Spring doesn't have to wrap anything. You get it directly from the source.
What would this method do?
Read the javadoc.
Any alternatives?
In a #Controller class' handler method, you can declare a parameter annotated with #RequestHeader and have Spring pass an argument that it retrieves from the HttpServletRequest headers.
This is, by default, restricted to #Controller methods annotated with #RequestMapping. If your service class is a HandlerInterceptor, Filter, or other type of class and simply has a reference to the HttpServletRequest object, there is nothing more you can do than retrieve it directly with getHeader(String).
Here is an alternative : Spring MVC define the parameter annotation #RequestHeader to read httpServletRequest headers :
#RequestMapping(...)
public #ResponseBody String myMethod(#RequestHeader String AuthId){
//the value of the parameter AuthId is the value of request header named AuthId
...
}