How can I get RequestMethod of ServletRequest? - java

I have ServletRequest, which client machine sent. How to know which one it is: GET POST UPDATE or DELETE?

HttpServletRequest contains getMethod() which returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT

If you are using Spring MVC and your comunication protocol is HTTP, you don't need use ServletRequest, you can use directly HttpServletRequest in your method like this:
public ModelAndView index(HttpServletResponse response, HttpServletRequest request)
But if you need use ServletRequest and you are sure your comunication protocol is HTTP you can cast your ServletRequest to HttlServletRequest and use getMethod() like Shriram said.

Related

get the http post request body before jackson invocation in spring

i want to know is there a way to get the HttpServletRequest body before any Jackson involvement in spring. I tried it with #JsonDeserializer and spring HandlerInterceptorAdapter and also with a HttpRequestWrapper but no luck for now. if anyone knows please suggest me a way to do this thanks.
You can add a custom Filter in the application (explained here) and override doFilter method. E.g.:
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain){
....
}
This would give you the request object from which, you can get the payload.

Change ServletRequest server name programmatically

I need to change the serverName of the ServletRequest object in my Grails controller. I'm having trouble figuring out how to do this since the serverName is a read-only property.
The most correct thing to do is probably to set up a clever filter or redirect which "fixes" your request URL before your servlet even gets involved. I know nothing about how to do that; you should ask on serverfault.com if you want to do that.
In java, you can fake it by creating your own subclass of HttpServletRequestWrapper which provides setServerName() and overrides getServerName() while delegating all other methods to the superclass. You can then provide a filter which creates an instance of your request and sends that one down the chain.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
YourHttpServletRequest yourRequest =
new YourHttpServletRequest(request, newServerName);
chain.doFilter(yourRequest, response);
}
If I understand this correctly, CORS filter might help
I've used http://software.dzhuvinov.com/cors-filter.html in my previous project.
But you can also lookup on github for example https://github.com/eBay/cors-filter

Java HttpServletRequest getquerystring

In my servlet, req.getQueryString() returns null when an ajax request is sent to it.
Is this because req.getQueryString() only works for GET and not POST?
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getQueryString();
}
The easiest way to get hold of request parameters is to use request.getParameter(). This works for both GET and POST requests.
POST requests typically carry their parameters within the request body, which is why the request.getQueryString() method returns null.
From docs:
This method returns null if the URL does not have a query string.
Since you are in a doPost() handler, we can assume that indeed the request has no query string since it is a POST.
POST request may have a query string, but this is uncommon. POST data is included directly after the HTTP headers that browser sends to the server.

Get Cookies from ServletRequest

I'm using ServletRequestListener to attach to new requests, get a ServletRequest object and extract cookies from it.
I've noticed that only HTTPServletRequest has cookies but I haven't found a connection between those two objects.
Is it okay to use
HttpServletRequest request = ((HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest());
to retrieve the request while in a RequestInitialized method? (I do want to run on every request)
FYI - This is all done in a JSF 1.2 Application
This is not correct. The FacesContext isn't available in a ServletRequestListener per se. The getCurrentInstance() might return null, leading to NPE's.
If you're running the webapp on a HTTP webserver (and thus not some Portlet webserver for example), you could just cast the ServletRequest to HttpServletRequest.
public void requestInitialized(ServletRequestEvent event) {
HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
// ...
}
Note that a more common practice is to use a Filter for this since you can map this on a fixed URL pattern like *.jsf or even on specific servlets so that it runs only when the FacesServlet runs. You might for example want to skip cookie checks on static resources like CSS/JS/images.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
// ...
chain.doFilter(req, res);
}
When you happens to be already inside the JSF context (in a managed bean, phaselistener or whatever), you could just use ExternalContext#getRequestCookieMap() to get the cookies.
Map<String, Object> cookies = externalContext.getRequestCookieMap();
// ...
When running JSF on top of Servlet API, the map value is of type javax.servlet.http.Cookie.
Cookie cookie = (Cookie) cookies.get("name");
Yes, you can do that. In Web scenarios, this will always be ok. If you want to be sure, you could do a check for the type first. (Good practice anyway):
if (FacesContext.getCurrentInstance().getExternalContext().getRequest() instanceof HttpServletRequest) {
...
By the way: Why do you have to use FacesContext? From where are you calling this code?

how to pass a request of a servlet as a parameter to another helper

I wonder how cn i pass a request parameter of a servlet as a parameter to another java file of my web app that doesm't have POST and GET methods?
Thanks in advance
Antonis
Simply by getting the request parameter from the HttpServletRequest object, and using it as a parameter.
void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException {
String param = req.getParameter("name_of_your_param");
new YourOtherClass().yourOtherMethod(param);
//implement the rest to return a response
}
I'm excluding obvious things like input validation on the parameter (e.g. if the http client didn't send the parameter in the request, the result of getParameter is null) and sending the response.
Please takes some time to become familiar with the Servlet API and refer to it whenever you are curious how to do something with your Servlets and Request/Response objects: http://download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.5/docs/servlet-2_5-mr2/index.html
What's the problem with someObject.someMethod(request, response) ?
Your request always passes through a Servlet, so:
extract the needed parameters there
pass them as arguments to the helper
There is another option - to store what you need in a ThreadLocal variable, because each request is handled in a separate thread, but that's to be avoided.

Categories

Resources