Can HttpServletRequest be null after arriving in Java REST API? - java

I am using REST API with spring.is it possible that request arrives from UI/CURL to following API with request parameter null?
#GET
#Path(/abc)
#Produces({ "application/xml", "application/json" })
Public Users getUsers(#Context HttpServletRequest request)
{
someOtherClassMethod(request);
}
should I put null check for request here or request would always be not null if its arrived here.

#Context can be used to inject 12 object instances related to the context of HTTP requests.
It behaves just like the #Inject and #Autowired annotations in Java EE and Spring respectively.
#Context HttpServletRequest request
Here bean is created , and so can never be null
No need of null check
Hope this answers

Related

How to set value to #RequestAttribute in Spring boot using postman or feign client

I have method like this:
#PostMapping(path = "/workflow-services/{service_id}/tickets",
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TicketIdResponse> createTicket(#PathVariable("service_id") String serviceId,
#RequestBody #Validated CreateTicketRequest request, #RequestAttribute Payload payload) {
log.info("Start create ticket [{}]", request);
TicketIdResponse response = ticketService.createTicket(serviceId, request, payload);
log.info("Create ticket response: {}", response);
return ResponseFactory.success(response);
}
so how to set value to #RequestAttribute Payload in postman or feign client
Thank you very much!
The #RequestAttribute annotation is usually used to retrieve data that is populated on the server-side but during the same HTTP request. For example, if you have used an interceptor, filter or possibly an aspect to populate the "payload" attribute then you should be able to access this using the #RequestAttribute annotation.
If you are looking to pass something from an external client (i.e via postman, curl or any other simple client) - #RequestAttribute is not the way forward.
Good references;
https://www.baeldung.com/whats-new-in-spring-4-3
https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/request-attribute.html
This SO post may also help.

Setting response header using interceptor?

I'm writing jax-rs end points. For some set of end points (existing code), I want to set an extra response header which was actually generated in #AroundInvoke interceptor and set to HttpServletRequest attribute. In #AroundInvoke I'm able to access HttpServletRequest using #Inject. But it seems I cannot access HttpServletResponse in the same interceptor itself.
It seems I can do with PostProcessorInterceptor but again I'm confused with the following doc.
The org.jboss.resteasy.spi.interception.PostProcessInterceptor runs after the JAX-RS method was invoked but before MessageBodyWriters are invoked. They can only be used on the server side. Use them if you need to set a response header when there might not be any MessageBodyWriter invoked.
I'm using resteasy, jackson. If I use PostProcessorInterceptor can I inject HttpServletResponse? Or Can I set new http header there some how?
Any code example/direction would be appreciated.
With JaxRS 2 (which comes with javaEE 7) you can use a ContainerResponseFilter see also
public class PoweredByResponseFilter implements ContainerResponseFilter {
#Inject
HttpServletRequest request;
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
String name = "X-My-Header";
String value = "";// some data from request
responseContext.getHeaders().add(name, value);
}
}

Configure Spring to return 404 HTTP code on every null returning webmethod

I want to configure my web methods to set the http status code to 404 or an other code indicating that something went wrong (e.g. 444 No Response).
Currently the response is http 200 with null in its body.
#RequestMapping(value = "folder", method = RequestMethod.GET)
#ResponseBody
public Folder findFolder(String folderId, WebRequest request) throws PermissionDeniedException, ServiceException {
return projectService.findFolder(folderId); // should set HttpCode.NO_RESPONSE if the method returns null
}
Is there a central way to configure the web services rather than handling null values one by one in each method?
Alternatively, is there a way to bind an #ExceptionHandler (or rather #SomeGenereicHandler) to null return values?

Getting HttpServletRequestWrapper in Jersey

I wrote an HttpServletRequestWrapper named HTTPRequest that reads the full HTTP POST body for further use. This one is based in the code at http://natch3z.blogspot.com/2009/01/read-request-body-in-filter.html
My Jersey server application needs to get this wrapper to read the body. Unfortunately, I don't know how to do that.
I've tried putting
#Context HTTPRequest request;
but it does not work (Missing dependency for field).
I've tried too doing:
#Context HttpServletRequest request;
then casting to HTTPRequest, it didn't work neither ($ProxyXXX cannot be cast to HTTPRequest).
I've searched for information in the Internet but I cannot find anything regarding this. Any idea? :)
Thanks!
I don't quite understand: HTTPRequest is your objects extending the HttpServletRequestWrapper, right?
So if you want Jersey to inject it via the #Context annotation, you need to implement the ContextResolver. Actually in your case it should be easy:
#Provider
HTTPRequestContextResolver implements ContextResolver<HTTPRequest> {
#Context HttpServletRequest request;
HTTPRequest getContext(Class<?> type) {
return new HTTPRequest(request);
}
}
Updated: If you already wrapped the original request in a filter, you may have a problem to get it, since Jersey wraps the original request using the dynamic proxy.

Question about Request and Session with CXF, JAX-RS webservice

I have a webservice set up using CXF, JAX-RS and Spring. I have the following method:
#GET
#Path("/getPayload")
#Produces("application/XML")
public Response makePayload(){
Payload payload = new Payload();
payload.setUsersOnline(new Long(200));
return Response.ok().entity(payload).build();
}
How can I get access to the HttpRequest object in my makePayload()?
Will a call to this method generate a Session, and if so, can I get a handle to it and will that session be persistent for all subsequent requests from the same client?
#Context can be used to obtain contextual Java types related to the request or response:
#GET
#Path("/getPayload")
#Produces("application/XML")
public Response makePayload(#Context Request request) {
//...
}

Categories