Inject request URI RequestMapping - spring

I'm working on a stubbing tool where a user can provide a list of endpoints and their associated JSON response. The idea is they will include a config file containing URIs and a directory of all stubbed responses. So essentially the config file will include the list of URI's that typically would be set using #RequestMapping if this was being built for a specific use case. Is there a way to have Spring send a success response even if the associated #RequestMapping doesn't exist?
Something similar to a SQL query e.g.
#RequestMapping(value = "/*", method = arrayOf(RequestMethod.POST))
fun sendResponse() : ResponseEntity<String> {
//Fetched correct response from interceptor
return ResponseEntity<String>
}

Found out the answer. You need to use #RequestMapping(value = "/**", method = arrayOf(RequestMethod.POST)).

Related

how to apply post method to all request mappings in spring

How i can access to request POST data from different url-s to one controller method, for example I have /countries & /countries/{id} URL, It works very good with first one, because my code is
#RequestMapping(value = {"/{id}", "/{id}/"}, method = RequestMethod.GET)
public String getCountry(#PathVariable(value = "id", required = true) int id,ModelMap model) {
}
#RequestMapping(method = RequestMethod.POST)
public String deleteCountry(ModelMap model,HttpServletRequest request) {
}
And when I try to request POST data from second url I'm getting
HTTP Status 405 - Request method 'POST' not supported
Which is expectable because I haven't POST method with this mapping, but if I will be made one method for one mapping my code will be too ugly ant terrible, what solution I can use?
Hum why not add the "array" of value to your second method as well ?
#RequestMapping(value = {"", "/{id}"},method = RequestMethod.POST)
public String deleteCountry(ModelMap model,
HttpServletRequest request) {
Btw using POST verb to call an action that looks like it will delete the resource seems wrong, it should be a DELETE verb used
EDIT
But in reality, you should be creating 2 methods, as both those method are not supposed to do the same thing.
POST /countries should be creating country resources
POST /countries/{id} should be doing something else.
For an update prefer PUT /countries/{id}
And for a delete, prefer DELETE /countries/{id}
There is one way to have separate handler interceptors for different controllers.
Refer this link for details.
bind Spring HandlerInterceptor only to one controller
But I feel, it may be good you can create a common method to share business logic for this.
As Interceptor comes with proxy class for your controller which can be avoided unless you have complex logic.

How Do I configure Spring View Resolver to Ignore a Specific Url and Not Look for Its .jsp?

I am working on a web application using Spring MVC architecture. I have a controller method that will be called by an ajax post(). The request mapper in the controller has a ".html" (meant for some cleanup task)for which the Spring Internal view resolver is trying to find a matching .JSP file and throws a 404 Not Found error. I donot want to create a .JSP which is not useful in my case. I need some help to determine if there is any setting in Spring Context xml to let the view resolver ignore this url and not to look for its .JSP file.
#RequestMapping(value = "/clearSession.html")
public void unloadDAOSession(HttpServletRequest request) {...}
the InternalViewResolver is looking for clearSession.jsp which throws a 404 Resource Not found. I dont want to create a JSP which is of no use.
Are there any application Context settings in the view resolver to ignore this ".html" file and not to look for its ".jsp"?
Any help is appreciated.
Even though the return type is void it only means that the view name will be resolved based on the URL as you have seen.
One way to avoid view resoluion is to annotate the response with #ResponseBody or
bypass the view resolver by tweaking your return type to something like
#RequestMapping(value = "/clearSession.html")
public ResponseEntity<String> unloadDAOSession(HttpServletRequest request) {
...
return new ResponseEntity<String>("OK",HttpStatus.NO_CONTENT);
}
This way instead of forwarding to a view, your just adding a header and an empty body to the response stream
In case of use of ajax and traditional controller, the best approach is write the your controller for answare to the page rendering as you had done adn then write a rest end-point layer for answare to ajax request.
I just give you some piece of code for clearing what I want say:
Controller layer:
#RequestMapping(value = "/yourPage")
public void yourPage(Model mode) {...}
Rest layer:
#RequestMapping(value = "/yourAjax")
public ResponseEntity<String> yourAjax(#RequstBody YoutDTOClass postBody) {
...
return ResponseEntity.created(...).build();
}
class YoutDTOClass{
// your properties
....
}
with this schema you separate the service layer for your ajax request and the classic web layer for serving the your page.
Just an hint don't use a pattern like /yourPage.html but you should prefare a pattern like /youtPage.This balically for banefit of the view resolver abstraction of Spring, you should let to springMVC to resolve the actual view.
Even for the ajax you should use the accept header for ask the correct rappresentation of your resource and the ResponseEntity should be used for return a 201 Http status for say to your browser that the your resource was created. remember that a better approach should prefere the use of http method in REST world and then for delete a session you should be prefare delte method for delete a session and put http method for update the sate of the session.
I hope that this can help you

Spring rest use of pathVariable and RequestParam

With spring rest is there any reason to use request param?
For a search i don't know if i shoud use
#RequestMapping(value = "/lodgers/{searchParam}", method = RequestMethod.GET)
public Lodger getAllLogders(#PathVariable("searchParam") String searchParam)
or
#RequestMapping(value = "/lodgers/", method = RequestMethod.GET)
public Lodger getAllLogders(String searchParam)
As I use it, a path (pathVariables) points to a resource.
A queryParam (requestParam) results in a subset of a resource.
If you want certain users from /Users (e.g. beginning with "A", or lodgers named "Curt") this would be a subset, of all /Users and I see not a very good reason for having a special resource with that criteria, so I would use a queryParam here.

Spring MVC REST - Block access to Web Methods

I have this method in my Controller that returns a json string to the view
#RequestMapping(value = "/getDevs", method=RequestMethod.GET)
public#ResponseBody String getDevs() throws JsonProcessingException,RemoteException,ServiceException{
ObjectMapper om = new ObjectMapper();
return om.writeValueAsString(WSCall.getDevelopers());
}
I call the method URL using ajax. Everything works fine except I can obtain the json if I put the URL directly in the browser. Is there a way to block this?
I agree with the comments above, that it is not relevant from a security standpoint, but you could probably make use of the X-Requested-With: XMLHttpRequest header that is most likely set for your AJAX requests. I can at least confirm it for jQuery, which might be on your tool stack.
So you could add the headers parameter to your #RequestMapping annotation:
#RequestMapping(value = "/getDevs", method=RequestMethod.GET, headers = { "X-Requested-With=XMLHttpRequest" })
public#ResponseBody String getDevs() throws JsonProcessingException,RemoteException,ServiceException{
[...]
}

Mapping same URL to different controllers in spring based on query parameter

I'm using spring annotation based controller. I want my URL /user/messages to map to some controller a if query parameter tag is present otherwise to some different controller b. This is required because when parameter tag is present then some more parameters can be present along with that which i want to handle in different controller to keep the implementation clean.Is there any way to do this in spring. Also is there any other elegant solution to this problem ?
You can use the params attribute of the #RequestMapping annotation to select an controller method depending on Http parameters.
See this example:
#RequestMapping(params = "form", method = RequestMethod.GET)
public ModelAndView createForm() {
...
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView list() {
...
}
It is a REST style like Spring ROO uses: if the request contains the parameter forms then the createForm handler is used, if not the list method is used.
If you want to go the Spring route, you can checkout the HandlerInterceptor mentioned here. The Interceptor can take a look at your query param and redirect the link to something else that can be caught by another SimpleUrlMapper.
The other way is to send it to a single controller and let the controller forward to another action if the query parameter is "b".

Resources