Is there any way to modify or set-header of request inside action class? I want to modify it or you can say i want to put flag inside request Header just like we put values in 'attribute' and parameters.
You can do this using HttpServletRequestWrapper. But it's quite dirty solution. Are there really no other ways to solve your problem?
You cannot. Request parameters returned from the servlet are unmodifiable Map. You cannot add/delete content returned from request (via servlet).
In order to set a flag, my suggestion is to store it in a session, and on another action, retrieve the flag & delete it from session.
I think you'd need to wrap the original request into a request class containing the change you wish to have.
It might be better design to have the request parameters parsed earlier in processing to such objects that make more sense to your application logic, and then set the state of those objects in the place where you now would like to modify the original header.
The answer to this depends on what problem you're trying to solve.
One of your comments suggests you're trying to test; if this is the case you have two basic options:
Use a mock request (unit-style testing).
Change the header from the client (integration-style testing).
For testing from real clients, set headers on the client side.
For mocking client interactions, you should be using some form of mock. StrutsTestCase, for example, provides MockStrutsTestCase (outside container) and CactusStrutsTestCase (inside container) classes allowing easy manipulation of request properties and characteristics.
If you are trying to open a URL connection using Java,
you can something like this What is the proper way of setting headers in a URLConnection?
If you can make requests with a browser,
You can use this Firefox plugin to add/modify any number of request headers.
https://addons.mozilla.org/en-US/firefox/addon/modify-headers/
Good Luck
You need to give more details. It sounds like you want to manipulate the request header once the server has received the request. I'm not sure I understand why you would want to do that. Modifying the response headers make sense. But not the request.
I think they only clean way you can do this is via an HttpServletRequestWrapper
Just override getHeader, getHeaders, getHeaderNames and you are good to go.
Related
I have a use case where some context needs to be transferred from the UI to the backend and backend needs to decide and send the response based on that context.
This can be achieved by sending the context through request body and at the server side, by parsing the request body, the representation can be sent in the response body.
My doubt is which http method is suitable for this?
GET: If we use GET, we can send the request body but it is advised that the body should not have any semantics related to the request.
See this: http-get-with-request-body
So I am left with POST or PUT but these corresponds to updating or creating a resource and using them might be little misleading.
So my question is what is the appropriate HTTP method that could be used in this scenario which is acceptable in the RESTful design standpoint.
Appreciate the response.
I am thinking to use POST or PUT as there are no restrictions on consuming the request body on the server side.
EDIT:
I think POST would serve my purpose.
The rfc HTTP RFC 7231 says that POST can be used for:
Providing a block of data, such as the fields entered into an HTML form, to a data-handling process
So the data handling process for me is the backend server and HTML Form is equivalent to any UI element.
So I can make use POST method to send the data to backend and send the existing resource representation as response body with http-status code being 200
Please bear in mind that GET must be used for data retrieval only, without side effects. That is, GET is both safe and idempotent (see more details here).
If the operation is meant to be idempotent, go for PUT:
4.3.4. PUT
The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response. [...]
Otherwise, go for POST, which is a catch all verb:
4.3.3. POST
The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics. [...]
I would go for POST because in REST, PUT is used to create a new resource like user.
There is a PATCH post method, that is for changing things maybe thats what you are looking for
So my question is what is the appropriate HTTP method that could be used in this scenario which is acceptable in the RESTful design standpoint.
The world wide web is about as RESTful an example as you are going to find, and HTML forms only support GET (which should not have a request body) and POST. So POST must be fine (and it is).
More generally, POST can be used for anything; the other methods should be used when they are a better semantic fit. For example, you can use POST to make a resource unavailable, but DELETE is more explicit, and generic components can do sensible things because they recognize the semantics. PUT is a better choice than POST when what you are intending is to provide the server with a new representation of a resource, and so on.
I am not able to understand why the payload of the HTTP GET is forbidden
Payload of the HTTP GET is forbidden because the standard says "don't do that".
I believe it is written that way to simplify the rules for caching the response. As written, cache implementations only have to worry about header data (including information on the start-line).
But it could be as simple as the fact that the older versions of the standard didn't require that generic components do anything specific with the message-body of a GET request, and therefore modern specifications say "don't do that" in order to maintain backward compatibility. (One of the important constraints in designing long-lived systems is that you don't break older implementations.)
Using jQuery AJAX, can we call a specific JAVA method (e.g. From an Action class)
The returned data from that Java method would be used to fill in some HTML code.
Please let me know if this can be done easily using jQuery (like it does in DWR)..Also for multiple data points in HTML, do we need to make multple AJAX requests?
The simple answer is you map your ajax calls to urls, which are in turned map to methods in your java code. The Ajax -> URI mapping happens on the client side (which ever js framework you are using, and the URI -> specific handler mapping happens within the java application)
What java framework are you using? There should be very clear and simple documentation on how to do this. For standard Java EE mappings (meaning you are not using any frameworks like Spring or Roo) I found this on google: http://javapapers.com/servlet/what-is-servlet-mapping/
"For multiple data points in HTML" I assume you are talking about having multiple parts of the html update. You can do this with multiple requests, or you can do it with one request. If you do the latter, the server needs to return all the data you need to update the dom appropriately.
It's not as transparent as with DWR--DWR handles making JavaScript look like Java. With jQuery you'll get JSON (or just HTML if/when it's easier that way). It's still pretty straight-forward, though. You'd send the Ajax request to a URL, rather than having it look like a local method call.
I'm not sure what you mean by "multiple data points in HTML" -- you get back whatever data you get back, and you can do with it whatever you want. If the response has all the data you need, then you wouldn't need to make multiple requests.
I have read this GREAT answer regarding REST. I have few questions regarding it:
According to the answer and what i read, new resource creation needs happen using the PUT verb but in most cases when you create a resource you need to provide parameters and sometimes binary data.
what is the way to do it with PUT? isn't it more natural to do it with multipart POST?
Can someone direct me to an example for use of PUT to send both binaries and String, preferably using the httpClient library.
What verb to use if i want something that is beyond the basic CRUD actions? like generate a report regarding one of the resources.
Thanks
You are confusing the HTTP Verb with the actual payload.
Nothing prevents you from using a multipart payload for PUT.
POST can be used to create new resources, but you are usually POSTing to a different URL.
As a side-effect, a new resource might get created and returned in the Location header.
PUT is used if you already have the URL to a resource.
REST != CRUD.
A restful architecture forces you to think in resources.
So 'report' might be a good candidate for a resource.
You could POST your report parameters to a resource like /..../reports (for example) and create a new report resource that way. Put the URL for the report in said Location header and use a GET to actually get the report data (or return the report data right away)
The Same Origin Policy is preventing me from fetching the JSON data I need from another web site (with permission). I saw one person who was working around this with JsonpRequestBuilder, but I'm not sure if that's going to be the best solution for me. The only other option that comes to my mind would be to have an intermediary servlet on my server.
What's my best bet here? I have concerns with both methods. With an intermediary servlet, I worry about the delay that would introduce. With the JsonpRequestBuilder, it looks like I have to create a complete JavascriptObject for each method I'll call from the other site, even though I only need to pull out a single value from some of those methods.
I don't use Java, but JSONP is what I usually implement when I need cross-domain chatter, and I'm sure someone will have made a Java library that unwraps it. It requires a change on the third-part's site, but it is a very simple change.
EDIT: Sounds like that is what that library does, sorry... but still... it's the way to go :)
Check out the CORS Specification. We are using this to successfully circumvent the SOP using our own server with GWT's devmode Jetty.
You don't have to "create a complete JavaScriptObject", a JavaScriptObject is actually just a mean to call to JavaScript from the Java world, so you only need the one getter for the value you need, and it can even return a "nested" value:
public native String getFoo() /*-{
return this.nested[0].obj.foo;
}-*/;
Whether you'll use JSONP (and JsonpRequestBuilder) or a "proxy servlet" actually only depends by the capabilities of the "service" you need to call: JSONP is JavaScript, not JSON, so the server has to return a "JSONP response script" or you won't be able to use JsonpRequestBuilder (and similarly, you won't be able to (safely) use CORS or a proxy-servlet if the server returns a "JSONP script" rather than application/json).
I need to get hold of the request object in Java code. I can't pass this object down to my code for certain reasons. Is there any way I can say something like: getCurrentHTTPServletRequest?
It is safe for me to assume that I am in a Servlet Context.
Well you should pass it down if you need it. Anything else you do is going to be ugly, basically.
You could use a ThreadLocal variable - basically set the context for that particular thread when you get the request, and then fetch it later on. That will work so long as you only need to get at the request within the thread that's processing it - and so long as you don't do any funky asynchronous request handling. It's brittle though, for precisely those reasons.
However, I would strongly advise you to be explicit about your dependencies instead. Either pass the servlet request down, or just the bits that you need.
Assuming you're not able to pass the request object down the call stack, then some kind of sharing mechanism becomes necessary, which is not ideal, but sometimes necessary.
Spring provides the RequestContextFilter for just this purpose. It uses ThreadLocal, and allows the code to fetch the current request via RequestContextHolder. Note that this filter does not require you to use any other part of Spring:
Servlet 2.3 Filter that exposes the
request to the current thread, through
both LocaleContextHolder and
RequestContextHolder. To be registered
as filter in web.xml.
This filter is mainly for use with
third-party servlets, e.g. the JSF
FacesServlet. Within Spring's own web
support, DispatcherServlet's
processing is perfectly sufficient.
If you're going to use ThreadLocal, then better to use an existing, working solution, rather than risk bugs creeping in, which ThreadLocal code is prone to.
Jon Skeet said practically everything, but one clarification to his advice "just the bits that you need" - if you need your request parameters passed down, but you don't need a dependency on HttpServletRequest, pass request.getParameterMap().
And extending a bit on the ThreadLocal option - you can have a Filter which handles all incoming requests, and sets the request in a
public final static ThreadLocal<HttpServletRequest> httpServletRequestTL =
new ThreadLocal<HttpServletRequest>();
Because you are setting it on each request (careful with the filter mapping), you won't have to worry about the servlet-container thread pool - you will always have the current request.
P.S. this is the logic behind the spring utility proposed by skaffman - I join him recommending the stable component, rather than making your own.
There is no servlet API to do this. However, Tomcat does provide an API call to do this,
HttpServletRequest request = (HttpServletRequest)org.apache.catalina.core.ApplicationFilterChain.getLastServicedRequest();
This will get the last request passed to a servlet for servicing from the current thread.
For this to work, the Tomcat must be in "Strict Servlet Compliance" mode. If not, you need to enable it by adding this JVM parameter:
org.apache.catalina.STRICT_SERVLET_COMPLIANCE=true
Assuming the top-level servlet really is taboo for some crazy business-related reason, there is still the option of defining a ServletFilter to pre-view the request and stuff it into a ThreadLocal. Assuming that the web.xml is not also sacrosanct.
But I agree with Jon Skeet in that this would be very ugly. I'd code this up and then try to find a different job. :)
Actually, given the fact that a filter can totally wrest away control from the receiving servlet, you could use this technique to divert the code to a servlet of your own, do whatever you want, and THEN run the other, "official" servlet... or anything else along those lines. Some of those solutions would even allow you to deal correctly and robustly with your request data.