How to GET and POST requests separately with HttpRequestHandler - java

I'm using HttpRequestHandler to inject Spring beans into Servlets:
#Component("myServlet")
public class MyServlet implements HttpRequestHandler {
#Autowired
private MyService myService;
HttpServlet has separate methods doGet, doPost etc for different request methods.
But HttpRequestHandler has only one:
public void handleRequest (HttpServletRequest req, HttpServletResponse resp)
So how to handle GET and POST requests in this method separately? I need to have different logic for different request methods.
UPDATE:
Also I have a question: is there possibility to restrict handleRequest method to support only POST requests by configuration and to sendHTTP Error 405 automatically for other requests?

The HttpServletRequest provides the method getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Same as the value of the CGI variable REQUEST_METHOD.

public void handleRequest (HttpServletRequest req, HttpServletResponse resp)
{
if(req.getMethod().equalsIgnoreCase("GET")){
//GET BODY
}
else if(req.getMethod().equalsIgnoreCase("POST")){
//POST BODY
}
}

Related

Java Servlet doPost() returning null from Postman

I am doing a simple Java Servlet POST request without using any HTML and only using Postman. And the response from getParameter() is always null.
Here is the servlet:
#WebServlet("/api/form")
public class FormServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String orderNumber = req.getParameter("testString");
System.out.println(orderNumber);
resp.getWriter().print(orderNumber);
}
}
And a picture with responses and how I am doing it:
EDIT
As was commented by Mukesh Verma.
All I had to do was add #MultipartConfig Annotation and I got the data.
This is not how method getParameter works. As stated in this question, you should call the servlet with the following URL:
http://localhost:8080/api/form?testString=test
Try using #MultipartConfig Annotation. It handles form-data mime type.
Changing Postman's radiobutton from form-data to x-www-form-urlencoded also does the trick and I am able to get the data.

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);
}
}

Extract URL from HttpServletRequest

I am maintaining a Java servlet application and now have to extract the URL from the web service request to determine what action to take depending on what URL called the web service. I have found that it is something to do with HttpServletRequest which I have imported to the class. I have tried setting up the following inside the web service end point but it keeps telling me that the urlrequest is not initialised. What am I doing wrong?
HttpServletRequest urlrequest;
StringBuffer url = urlrequest.getRequestURL();
The HttpServletRequest you are using should be the input parameter HttpServletRequest of either doGet,doPut,doPost or doDelete.
Then Surely HttpServletRequest.getRequestURL will reconstruct the URL used by the client,excluding the query string parameters.
Your code is correct but it has to be accessed within the doPost(request, response), doGet(request, response) etc. methods of a class extending HttpServlet.
The reason for this is the when the service() method of HttpServlet is called, it populates the request and response objects for you given the client who prompted the request to your servlet.
You cannot define a variable in java and call a method on it without initializing it beforehand.
In the first line: HttpServletRequest urlrequest; you are just defining a variable. Since it is not initialized it is null and you cannot use it.
Remove this line and use the argument passed to the doGet (or doPost) method in your Servlet.
For example if your servlet is like this:
public class MyServlet extends HttpServlet {
...
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws Exception {
...
}
Instead of your code just add below line in the body of the doGet method:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws Exception {
...
StringBuffer url = request.getRequestURL();
...
}
After this line you should be able to use the url variable.

How can I extract request attributes from Jersey's ContainerRequest?

HttpServletRequest has a method setAttribute(String, Object).
How can I extract this attribute from ContainterRequest?
I didn't find: getAttribute method!
Code
public class AuthenticationFilter implements Filter {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) servletRequest;
// .... ....
httpReq.setAttribute("businessId", businessId);
}
}
In Jersey Filter:
private class Filter implements ResourceFilter, ContainerRequestFilter {
public ContainerRequest filter(ContainerRequest request) {
// ..extract the attribute from the httpReq
}
}
You can't. They're not exposed through the Jersey API in any way. If you search the Jersey codebase, you'll find that there are no uses of HttpServletRequest.getAttributeNames(), which you'd expect to be used if they were being copied en masse. You'll also find that there are only a handful of uses of HttpServletRequest.getAttribute(), and it's strictly for internal bookkeeping.
Note, however, that when deployed in a Servlet Context, JAX-RS allows you to inject the original HttpServletRequest using the #Context annotation. I'm not certain whether you can do this in a Jersey filter, but it works in MessageBodyReaders/Writers and in resource classes.
Update: I've checked, and you can, in fact, inject the HttpServletRequest into a Jersey ContainerRequestFilter by simply including:
#Context private HttpServletRequest httpRequest;
If you're using Jersey 2, which implements JAX-RS 2.0, you can implement a ContainerRequestFilter which defines a filter method as follows:
public void filter(ContainerRequestContext requestContext) throws IOException;
ContainerRequestContext has getProperty(String) and setProperty(String, Object) methods, which in a Servlet environment (ServletPropertiesDelegate), map to the servlet request's getAttribute(String) and setAttribute(String, Object) methods.
See: Jersey on GitHub
I got the #Context working, but have the problem is that my ContainerRequestFilter is singleton.
I had to implement a custom javax.servlet.Filter and use a ThreadLocal to store the HttpServletRequest.
I wanted to add to previous answers my solution, in addition to adding context:
#Context
private HttpServletRequest httpRequest;
You should set and get attributes from the session.
Set:
httpRequest.getSession().setAttribute("businessId", "yourId");
Get:
Object attribute = httpRequest.getSession().getAttribute("businessId");

Can't find service method in Netbeans J2EE project

In NetBeans 6.7.1, I have made a j2ee project,
In this project I have Servlet that extends HttpServlet,
Of whatever little I know about servlets, they should have a service method however in the class in NetBeans I find only thefollowing methods.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
public String getServletInfo() {}
doGet and doPost in call the processRequest method.
Where is the service method?
A servlet does not need to (re)implement the service() method of the javax.servlet.Servlet or javax.servlet.http.HttpServlet class. Regurgitating from the API doc, the service() method is used to dispatch requests to the doXXX() methods of the servlet. It is already implemented in the HttpServlet class, for the HTTP protocol, and hence there is no need to override it in another servlet relying on the HTTP protocol.
By the way, NetBeans automatically creates the doGet(), doPost(), getServletInfo() and processRequest() methods for convenience, when you create a servlet. It does not mean that the service() method is not available - most servlet programmers do not have to implement the service() method.

Categories