Forward parameters to jsp from servlet - java

Is there a way to send parameters from servlet to jsp without redirecting the browser to that page?
RequestDispatcher disp = request.getRequestDispatcher("shoppingCart.jsp");
disp.forward(request, response);

There can be one way as below:
RequestDispatcher disp = request.getRequestDispatcher("shoppingCart.jsp"+"?myParam=myValue");
disp.forward(request, response);
If you are fine with "GET" method then you can solve this problem with appended parameters.

Well you can either set the attributes(used in case of internal communication with servlets or servlet to jsp or vice-versa) to the response object and forward the request you can achieve this as :
request.setAttribute("someKey","someValue");
You can also use the session scope to share the attributes between servlet and jsp like this:
Http session = request.getSession();
session.setAttribute("someKey","someValue");

Related

Refreshing session of other servlet

I have a problem with handling sessions between Java servlet, jsp page and Struts Action. Java servlet adds some param to session when get request and sendRedirect to some page1.jsp. On page1 I have an url to Struts Action like strutsAction.do. When StrutsAction recevies request, the session doesn't contain attributes I added in Java servlet. Clicking on page returned by this action doesnt refresh session of Java Servlet, but they have the same SessionId. So, after session.getMaxInactiveInterval() of servlet session pass I'm getting sessionDestroyed() event, even when i taking actions on page returned by StrutsAction. How to fix this issue?
In case of SendRedirect call old request and response object is lost because it’s treated as new request,
You should try the following code
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);
becuase when forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request.

how to get response from one servlet to another?

I have one Servlet A in which I put my result (e.g. URL ) in JSONObject (org.codehaus.jettison.json.JSONObject).I am trying to get url from Servlet A to Servlet B with passing some parameters (like ID).How to do this?
Is it possible?
Thanks.
You can use request dispatcher and in request object you can set the attribute using request.setAttribute() in Servlet A and in Servlet B you can access it using request.getAttribute()
RequestDispatcher dispatcher = request.getRequestDispatcher(URL_PATTERN_OF_ANOTHERSERVLET);
dispatcher.forward(request,response);
Try using sessions.
Servlet A:
HttpSession session = request.getSession();
session.setAttribute("id", yourValue);
Servlet B:
String str = (String)session.getAttribute("id");
You can get the url by the following code:
request.getAttribute("javax.servlet.forward.request_uri")
And then you can navigate to another servlet using
response.sendRedirect("/ServletB")
EDIT
In Servlet B:
request.setAttribute("attributeName",StringParameter);
RequestDispatcher rd = request.getRequestDispatcher("/ServletA");
rd.forward(request,response);
In Servlet A:
String r = (String)request.getAttribute("attributeName");

Communication between servlets and/or jsp

How can you sent a request from one servlet to another or one servlet to any jsp file?
Actually i want to send a request form one servlet named Demo to another jsp file abc.jsp
Using RequestDispatcher
programatically...
public class Demo extends HttpServlet{
public void doGet(HttpServletRequest req , HttpServletRespaonse res)
throws ServletException, IOException {
res.setContentType(text/html);
PrintWritter pr = res.getWriter();
pr.println("i am in servlet");
RequestDispatcher rd = req.getRequestDispatcher("abc.jsp");
rd.forward();
}
}
abc.jsp
<body>
<i am abc in abc.jsp>
</body>
You can either forward it or redirect it.
To forward, you can use RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("abc.jsp");
rd.forward(request, response);
To redirect,
response.sendRedirect("abc.jsp");
FYI, Difference between the two,
In Forwarding, the same request object is forwarded to the next resource (Servlet or JSP) and in Redirecting client (browser) is asked to send a new request to the server for the next resource (servlet or JSP).

Using sendRedirect inside a servlet forwarded with request dispatcher

I have a filter that implements a custom convention for loading servlets and JSPs. In that convention I am using the following code to include the servlet:
servletContext
.getRequestDispatcher( uriDispatcherLocator.getServletLocation( uri ) )
.include( request, response );
and the following code to include the JSP (in the same filter):
servletContext
.getRequestDispatcher( "/index.jsp" )
.include( request, response );
Everything works fine, the servlet executes, then it includes the JSP and some irrelevant custom rules take place.
As you can see, at the very moment I include a servlet with request dispatcher I cannot send an http header response to the client.
The problem is that I want the servlet to have full control of the response as if it was called from inside the filter (because the filter will do nothing else than dinamically mapping the servlets according to their respective Class/JSP location in the project file system).
I can use .forward() instead of .include(), but if I do I will not be able to include a JSP after the servlet has been executed.
So, how would I allow the servlet to execute the code below when being included through a filter via RequestDispatcher interface?
response.sendRedirect( "/somePath" );
No Javascript hacks, I am willing to send the proper HTTP response from the server to make the browser behave correctly.
--
EDIT:
In other words:
I want to change the headers sent to the client from INSIDE an included servlet by using RequestDispatcher, but the docs states:
The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
Your Filter includes your servlet
servletContext
.getRequestDispatcher( uriDispatcherLocator.getServletLocation( uri ) )
.include( request, response );
Your Servlet indicates it wants to redirect
request.setAttribute ("sendRedirect", "/some/path");
or, wishes to add one or more response headers
Map<String, String> respHeaders = new HashMap<String, String>();
respHeaders.put("Expires", "0");
respHeaders.put("Cache-Control", "no-cache");
request.setAttribute("respHeaders", respHeaders);
Your Filter checks for these special requests
Map<String, String> respHeaders =
(Map<String, String>) request.getAttribute("respHeaders");
for (String key : respHeaders.keySet()) {
response.setHeader(key, respHeaders.get(key)); // set response headers
}
String sendRedirect;
if ((sendRedirect = (String) request.getAttribute("sendRedirect")) != null) {
response.sendRedirect(sendRedirect); // redirect the client
}
EDIT: Perhaps some of your servlets are already driving the flow and setting response headers when called from outside an include. But, there's no way to reuse them as is. You can't simply include them and expect the same behaviour because the goal of a RequestDispatcher#include() is to provide for server-side includes (SSI) only.
Hence, we do not find any overloaded methods (or any setters that could modify this behaviour) in the API. If you want to include such servlets and retain their behaviour (like redirects) you would have to pass them a hint that they're running under an include context and so should submit their response requests.
request.setAttribute ("includeContext", true);

Setting parameters in jsp and in servlets

In my web application , I get a request from the client. I process the request in my jsp page or the servlet(which ever is called) and want to forward to other jsp's or servlets accordingly. But before forwarding I want to set a few parameters and then forward it with these new parameters. The old parameters should not be present when forwarding. Only the new parameters should be present. How can this be done?
Can I forward from a servlet to jsp and vice-versa?
Please tell how the above can be accomplished?
If you have no use for the request parameters and your jsp/servlet has not written anything to the response, then I suppose it would be fine to use redirect instead of forward, since redirecting will discard the request along with the parameters.
When you do redirect, you can create dynamically and set the querystring like so:
response.sendRedirect("url?a=" + var1 +"&b=" + var2);
Take note that this will be a GET method to the url. If url will be resolved to a servlet, you can implement the doGet method to just call the doPost.
Please note that a redirect will be ignored if the jsp/servlet has written something already on the response...
You can use request dispatcher and redirect as per your need and requirement.
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("url");
rd.forward(request,response);
or
response.sendRedirect("url");
sendRedirect() sends the header back to the browser , which contains the name of the resource to be redirected to. So this will be a new request to the resource from the browser .
forward() action takes place within the server without the knowledge of the browser .
yes you can forward the parameter servlet to jsp and jsp to servlet.
when you can set the attribute in request then it will lost on destination.means you can not access that on third resource.
request.setAttribute(attribute name,attribute value)
you can do same thing in session also.
You have to forward to JSP/Servlet using RequestDisptcher. Set the request attribute on the request to set parameters using
request.setAttribute(name, value)
The Forwarded JSP can read the parameter using
request.getAttribute(name)
But, You cannot hide the attribute existing before forward by default. You can achieve this using Request Wrapper. Wrap the request before forwarding override the set and get attribute methods.
Below code explains
RequestDisptcher dispatcher = req.getRequestDispatcher("url");
HideExistingRequestWrapper requestWrapper =
new HideExistingRequestWrapper(request);
requestWrapper.setAtribute("forwarded", "forwarded value");
dispatcher.forward(requestWrapper, response);
Here is the code of wrapper implementation:
class HideExistingRequestWrapper extends HttpServletRequestWrapper {
private Map localattributes = new HashMap();
public HideExistingRequestWrapper (HttpServletRequest orignialRequest) {
super(orignialRequest);
}
public Object getAttribute(java.lang.String name) {
return localattributes.get(name);
}
public Object setAttribute(java.lang.String name, java.lang.String value) {
return localattributes.put(name, value);
}
}
use
ServletRequest.removeAttribute(name of your old attribute)
ServletRequest.setAttribute(name , value)
After setting the attributes, get the RequestDispatcher using
getRequestDispatcher(url)
and then use forward() method

Categories

Resources