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.
Related
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.
I am using jersey rest service in java to accept request.
Here is my snippet
#Path("main")
public class xxxx{
#GET
#Path("test/{path}")
public void test(#Context HttpServletRequest req ) {
System.out.println(req.getRequestURI());
}
}
I am invoking this using REST Api as test/abcd , it is working. I want #path to accept test/abcd or test/abcd/ab and so. I tried with "test/{path}/*" nothing works.
Please someone help me as I am new to this.
You should use regex in the #Path for example :
#Path("{parameter: .*}")
Response getData(#PathParam("parameter") List<String> parameter){
//do processing
}
For more details you can see the examples given here.
This question already has an answer here:
Spring #RestController Get Request Content-Type to response json or html
(1 answer)
Closed 4 years ago.
I need to make a single api, by which I can return data format of json or xml, as it has been requested from the customer.
guys, any idea how I achieve this because when I use #Produces annotation it makes it fix for specific format, but I need to return as it has been requested.
If you can use Spring, configure ContentNegotiationManager in DispatcherServlet.xml and then you can use response type as parameters to url.
For example:
http://localhost:8080/employee-management-system/viewEmployee/4?type=xml
http://localhost:8080/employee-management-system/viewEmployee/4?type=json
More detailed instructions you can find here:
https://www.javainuse.com/spring/rest4
You could specify the response content type using the ResponseEntity object as follows:
return ResponseEntity
.ok()
.contentType(MediaType.IMAGE_GIF);
What I would normally expect to see here are two methods, one that #Produces ("application/json"), and the other that #Produces("application/xml").
#Path("/foobar")
public final class FooBar {
#Produces("application/xml")
public String xml () { ... }
#Produces("application/json")
public String json() { ... }
}
The example in Oracle's description of the #Produces annotation includes an example for text/plain and text/html which is similar.
this is one way to do it, but I don't want to write 2 methods. I want to do it in one method.
Another reasonable approach would be to get closer to the metal
#Path("/foobar")
public final class FooBar {
public Response foobar() (#Context HttpHeaders headers) { ... }
}
And then inspect the headers yourself to decide what to do. See Get HTTP header in JAX-RS
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) {
...
Say I have this endpoint:
#GET
#Path("/{product}")
#Produces(MediaType.APPLICATION_JSON)
public String getProduct(
#PathParam("product") final String product) {
return createSignature(<<PLACE COMPLETE URL HERE>>);
}
How can I know the complete URL that is being called from inside the endpoint in order to maybe create a signature based on that? Thanks
There are several ways.
Generally you can add special parameter to method or a field to your resource class. Special parameter is recognized by type (HttpServletRequest or UriInfo) and should be marked using annotaiton #Context.
#StormBringerX already mentioned that the information may be passed using method parameter (+1). I personally prefer to add this as a field of your class because I think this is clearer and allows creating methods that accept only application level parameters.
You can access the original request by adding #Context HttpServletRequest request as a parameter to your method. You can then access anything you want to do with the request.