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.
Related
I have searched and seen a couple of answers about this problem, but still don't know how it's possible...
I'm asked to Implement a filter that returns response-time of an HTTP Request in the response header, eg. response-header: XX
in order to get collected by a web analytics client side library.
here's my code :
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse)response;
long startTime = System.nanoTime();
chain.doFilter(request, response);
long endTime = System.nanoTime();
httpResp.addHeader("response-time",endTime-startTime);
}
as well I tried to user HttpServletResponseWrapper
I managed to modify the response using OutputStream but didn't succeed with setting the response headers.
Thanks,Jay
Extend wrapper utility class like HttpServletResponseWrapper (using custom output streams) and pass it to the chain doFilter() method. If you dont do that, after chain doFilter() returns, the original (not wrapped) response will be gone and you will not have a chance to modify it.
Here you can find an example: Looking for an example for inserting content into the response using a servlet filter
I am trying to print the browser URL using Java. I have come across codes where they have used "request.getRequestURI();" to retrieve the URL. What is this "request" in "request.getRequestURI();" ? How do we define it? Can i get an example of a code with "request" defined?
It is an HttpServletRequest object.
See: http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html.
Normally it is passed in to a method on your controller.
The request object retrieves the values that the client browser passed to the server during an HTTP request such as headers, cookies or parameters associated with the request. Among the most common use of the request object is to obtain parameter or query string values. The following demo illustrates how to use the request object for parsing form data. - See more at: http://www.gulland.com/courses/jsp/objects#sthash.zigrGeiE.dpuf
The request object is an instance of HttpServletRequest. The request object is implicitly defined in jsp pages. It is also a parameter in the doGet and doPost method of an HttpServlet
So in a servlet, you'll have something like:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
and in a jsp page, you can access an object, lets say the firstName string, attached to the request with expression language:
<p>${request.firstName}</p>
I have two Java web applications that have a single servlet that gets mapped to a specific URL:
red.war/
WEB-INF/classes
com.me.myorg.red.RedServlet (maps to http://red.example.com/doStuff)
blue.war/
WEB-INF/classes
com.me.myorg.blue.BlueServlet (maps to http://blue.example.com/doStuff)
I want to put these application (I'm calling them my "backend apps") behind a "proxy app" (servlet) that will decide which of these two apps will ultimately service a client-side request.
This proxy web app would take an incoming HTTP request, and determines which of the 2 "backend apps" (red or blue) to forward the request onto. The request would then be forwarded on to either http://red.example.com/doStuff (and then processed by RedServlet#doGet(...)) or http://blue.example.com/doStuff (and then processed by BlueServlet#doGet(...)). The returned response from the backend app (again, either RedServlet#doGet(...) or BlueServlet#doGet(...)) would then be returned to the proxy servlet, and ultimately returned to the client.
In other words, in pseudo-code:
public class ProxyServlet extends HttpServlet {
#Override
public doGet(HttpServletRequest request, HttpServletResponse response) {
String forwardingAddress;
if(shouldBeRed(request))
forwardingAddress = "http://red.example.com/doStuff";
else
forwardingAddress = "http://blue.example.com/doStuff";
PrintWriter writer = response.getWriter();
writer.write(getResponseFromBackend(forwardingAddress, request));
}
private String getResponseFromBackend(String addr, HttpServletRequest req) {
// Somehow forward req to addr and get HTML response...
}
}
Is this possible? If so, how and what code would I need to write to make it work?
You could use a RequestDispatcher to forward your request in the following way:
RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(forwardingAddress);
// here you have the choice whether to use include(..) or forward(..) see below
if(useInclude)
dispatcher.include(httpRequest, httpResponse);
else
dispatcher.forward(httpRequest, httpResponse);
... where useInlcude is set to your choice with the following options:
includeThis is probably what you want to do: Load the content from the forwardingAdress into your response.
This means you could even include multiple targets into a single response.
The client will not even realize this procedure nor does he need to be able to see the target document.
forwardSend a forward to the forwardingAddress. This will tell the client to submit a new request to the specified URL.
If you do it in a browser with developer tools, you will see a second request.
The client must be able to see and load the target URL.
You can only forward to a single target.
See, the following links, too:
RequestDispatcher javadoc, especially for the notes:
forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.
include: The request and response parameters must be either the same objects as were passed to the calling servlet's service method or be subclasses of the ServletRequestWrapper or ServletResponseWrapper classes that wrap them.
URLRewriteFilter examplealthough this example is implemented using a Filter instead of a Servlet the behavior is the same (Note: this example is part of a framework of mine and hence contains some overhead in the parent classes. Just have a look at the relevant section...)
Since there is not yet an approved answer I try to write how I see the solution to this request use apache-http-commons library. In addition I suggest to add a flush on writer.
public class ProxyServlet extends HttpServlet {
#Override
public doGet(HttpServletRequest request, HttpServletResponse response) {
String forwardingAddress;
if(shouldBeRed(request))
forwardingAddress = "http://red.example.com/doStuff";
else
forwardingAddress = "http://blue.example.com/doStuff";
PrintWriter writer = response.getWriter();
writer.write(getResponseFromBackend(forwardingAddress, request));
**writer.flush();**
}
private String getResponseFromBackend(String addr, HttpServletRequest req) {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
client.executeMethod(method);
String body=method.getResponseBodyAsString();
return body;
}
}
I have a HashMap of custom objects being passed to a JSP using RequestDispatcher and I am able to access the object and its properties using JSTL.
However the code fails in case the parameter is sent using response.sendRedirect() .
I am not sure what the reason is and how to make it work?
The response.sendRedirect() basically instructs the client (the webbrowser) to send a new request on the given URL. You'll also see this being reflected by a change in the browser address bar.
A new request does of course not contain the attribtues of the previous (or any other) request. That would otherwise have broken the whole concept of "request scope".
To preprocess a GET request, you need to do the job in doGet() method of a servlet and then redirect to the URL of that servlet instead.
E.g.
response.sendRedirect(request.getContextPath() + "/foo");
and
#WebServlet("/foo")
public class FooServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, Foo> foos = fooService.map();
request.setAttribute("foos", foos);
request.getRequestDispatcher("/WEB-INF/foo.jsp").forward(request, response);
}
}
Note that this problem is in no way related to having a hashmap of custom objects in the request scope.
See also:
Our servlets wiki page
You can not share a request attribute in response.sendRedirect as it creates a new request.
But, if you want that HashMap, in response.sendRedirect, you can put that in session like
request.getSession().setAttribute("myMap", [HashMap object]);
and can share between the servlet and JSP. This works in both RequestDispatcher and sendRedirect.
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.