map 2 different URI to same Controller method [duplicate] - java

This question already has answers here:
How to do Multiple URL Mapping (aliases) in Spring Boot
(2 answers)
Closed 2 years ago.
I have 2 URIs
/books
/getallbooks
I want to call the same Controller method upon these URIs
Is it possible through Spring ? (Mapping same controller method with multiple URIs)
Or,
I create 2 different methods and map these URIs with them, and then call a common method

You can use more than one URI as follows :
#Controller
public class IndexController {
#RequestMapping({"","/","index","index.html"})
public String index() {
return "index";
}
Here I have passed a list of URIs to RequestMapping annotation.

Related

PathVariable and pathvariable with requestparam endpoints in rest controller [duplicate]

This question already has answers here:
create two method for same url pattern with different arguments
(2 answers)
Closed 11 months ago.
I want to create 2 endpoints in my #RestController annotated spring boot project.
Endpoint 1: api/account/balance/{accountnum}
Endpoint 2: api/account/balance/{accountnum}?datetime={datetime}
Both end points are having same URI until the path variable but second one has an additional query param in it. But when i send request it always go to first endpoint(without query param) eventhoug i send datetime query param in the request.
Is it possible to create these 2 endpoints with same URL but one with additional query param?
No, You can't, what you can do is get the datetime param value, if it has value, then do the operation based on it else do the other operation.
You can create a single endpoint with Queryparameter as optional by default.
If you want to specify you can use like below
#RequestParam(value = "myProp", required = false) String myProp

Spring MVC controller testing [duplicate]

This question already has answers here:
How to test a spring mvc controller
(3 answers)
Closed 2 years ago.
New at testing and after doing much research not sure where to start based on examples I've seen.
The below controller is used in a spring boot client app that makes only GET requests to the REST API that returns a response as a list. Here the response is set as an attribute on the model and then returned as a String to be rendered in the view... if I got that 100% correct.
Question : can someone share an example on how I need to write a test for this controller? Do I need to just assert that the controller attribute is not null?
#Controller
#RequestMapping
public class WebController {
#GetMapping("/ListA")
public String viewListAController(Model model) {
return "ListA";
}
}
Well, the Model method parameter is never used and should most likely be removed since it isn't doing anything.
Then your unit test would most likely just be making sure that the viewListAController method returns the string 'ListA'.
And...
That's it...

more servlets vs more objects [duplicate]

This question already has answers here:
Design Patterns web based applications [closed]
(5 answers)
Closed 6 years ago.
I want to understand, If request has to be processed through multiple functions-
is it good to forward through multiple Servlets OR
implement as object methods
Example
req.getRequestDispatcher("LoadSession").forward(req, resp);
req.getRequestDispatcher("AuthoriseRoles").forward(req, resp);
req.getRequestDispatcher("Boot").forward(req, resp);
OR
sessionLoader.loadSession(req,res);
authoriseService.authoriseRoles(req,res);
bootService.boot(req, res);
I assume you are at the phase of designing an API. According to REST design principles, the url should reflect the resource that is handled or requested and the HTTP method should reflect what action is required to be taken on the resource.
So, instead of /LoadSession and having the session id as query param in the Http request, it should be GET /session/{id} for example GET /session/e841092fa2194340bc40 (I am assuming LoadSession is a request to return an existing session)
You might ask yourself what is the advantage of following this design. It is that there are several libraries and frameworks that are able to parse incoming HTTP requests and take care of the routing for you (for example, Jersey is the reference JAX-RS implementation, JAX-RS being JavaEE's REST standard) . So instead of writing a servlet as you mentioned, you write the class that represents the resource and methods that are fired according to the HTTP method. you tie it all together with annotations:
#Path("/session")
import javax.ws.rs.*;
import javax.ws.rs.core.*;
#Produces({MediaType.APPLICATION_JSON})
public class SessionHandler
{
#Context
private HttpServletRequest httpRequest;
#Context
private HttpServletResponse httpResponse;
#GET
#Path("{id}")
public Session load(#PathParam("id") String id) {
...

Using same path for #GET and #POST [duplicate]

This question already has answers here:
Is it okay to use same resource name for both get and post rest api
(2 answers)
Closed 7 years ago.
In java RESTfull service can I define two methods in same path differentiate by http calling method.
EG : first method using GET and Second one using POST
#GET
#Produces("application/pdf")
public Response getFile(#Context HttpServletRequest req,#PathParam("search") final String search,Map<Object, Object> input) {
....}
#Post
#Produces("application/pdf")
public Response getFile(#Context HttpServletRequest req,#PathParam("search") final String search) {
....}
Annotation is just a decorator for the given method. The core principle is , it should not stop original structure of java classes. So it is perfectly legal to have multiple handler in single file.
Yes, it is perfectly valid to have separate handlers for different methods at the same path.

Want my spring controller to return a string without a view [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Return only string message from Spring MVC 3 Controller
My spring controller has a endpoint where I want to only:
1. set the http response code
2. return a string back, don't need to render a .jsp view page or anything.
So will want to set the http status code to 200 OK or 500 etc.
And simply return a string like "OK".
How can I do this, or am I forced to render a .jsp view page?
Use the #ResponseBody annotation:
#RequestMapping(value="/sayHello", method=GET)
#ResponseBody
public String whatever() {
return "Hello";
}
See the #ResponseBody ref docs for further details.
You may be able to use the #ResponseStatus annotation to set the code rather than using the HttpServletResponse directly.
No, you are not forced to use view. If you use more recent version of Spring, you may use #ResponseBody annotation. See documentation for reference.
Example:
#Controller
#RequestMapping(value = "/someUrl", method = RequestMethod.GET, produces="text/plain")
#ResponseBody
public String returnSimpleMessage() {
return "OK";
}
You could also use HttpServletResponse as a parameter to set desired HTTP status.

Categories