How to forward request from web1/servlet to web2/servlet? - java

I've two web applications say web1 and web2. I want to forward a request from web1/servlet1 to web2/servlet2. Is it possible? Please help!

This is a two-step process:
Get hold of the ServletContext representing web2
Get the RequestDispatcher from that ServletContext corresponding to servlet2
So, something like this, from inside servlet1:
ServletContext web1 = getServletContext();
ServletContext web2 = web1.getContext("/web2");
RequestDispatcher dispatcher = web2.getRequestDispatcher("/servlet2");
dispatcher.forward(request, response);
There's a big caveat to all of this - the container may not be configured to permit cross-context forwarding, since it's a potential security risk. If this is the case, getContext("web2") will return null.

Related

Understanding JSP line of code with getRequestDispatcher

req.getRequestDispatcher("jsp/viewArticles.jsp").forward(req, resp);
So we get the Dispatcher of the Request, and provide the path. Ok so far. Now we forward to it the req and resp.
Now I am lost: We get RequestDispatcher from this req so RequestDispatcher is member method of req. Then why do we need to forward req itself to this RequestDispatcher anyway? Can't this method just use this to access req?
I found a question identical to mine but it do not understand the explanation, this is why I am asking again as an absolute servlet beginner.
How do the getRequestDispatcher() and forward() methods work?
Just for clarification, req and resp are of type HttpServletRequest and HttpServletResponse respectively.
From th API deginition, the RequestDispatcher an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container (aka Tomcatt) creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name
The getRequestDispatcher() method is available from the current Request Object or from the current Servlet Context Object . Use req.getRequestDispatcher(path) for a relative path in the same context, and prefer ServletContext.getRequestDispatcher(path) for an absolute path.
Before forwarding you can add parameters Object as attribute with req.setAttribute("key", valueObject ) method to foward parameters server-side . The Request handle the data from the client, you can complete it, and the Response will handle the page, the headers , cookies and so on to the client.
Hope this can help
There's a hint in the JavaDoc of RequestDispatcher:
The difference between this method and ServletContext.getRequestDispatcher(java.lang.String) is that this method can take a relative path.
So essentially, you can ask for the RequestDispatcher via the ServletContext, in which case you can only use absolute paths, or you can request it via the ServletRequest, in which case you can use paths relative to that request path.

The url works in localhost but not in server

I use getServletContext().getRequestDispatcher("/message.jsp").forward(request, response); to forward from servlet to jsp, but this does not work in server. I used response.sendRedirect(request.getContextPath() + "/message.jsp"); but then jsp does not show the message which I send from servlet. How to solve it?
If you do a sendRedirect instead of a forward, you will create a new request, which will cause your request attributes to be gone. Some frameworks use a 'flash' scope (essentially 2 times a request) instead of the request or session scope to handle this. In your case, however, there is no flash scope since you are using plain Servlets/JSP.
Instead, you can do something like:
ServletContext context = getServletContext().getContext(request.getContextPath());
RequestDispatcher dispatcher = context.getRequestDispatcher("/message.jsp");
dispatcher.forward(request, response);
Which should forward the current request to the message.jsp.
you can do by this way
request.setAttribute("PARAM1", "VALUE1");
RequestDispatcher dispatcher = request.getRequestDispatcher("message.jsp");
dispatcher.forward(request, response);
and in your Message.jsp retrieve your set value.
request.getAttribute("PARAM1");

How to send object throgh request between diffent application

I want to send Java (POJO class) Object to other applcation which is installed on diffent or same tomcat.
I have tried with request.setAttribute("abc",javaObj) but getting null value while using request.getAttribue("abc") and scope="application" and My both application on same tomcat.
I am Using redirect jsp.
If you want to share a variable between two applications under the same tomcat then you need to set it in the servletcontext using setAttribute method of that.
For sending the POJO to a different tomcat or JVM, you either use RMI or HTTP.
Use RequestDispatcher and setAttribute
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("your url");
MyPojoObject m=new MyPojoObject();
request.setAttribute("abc", m);
dispatcher.forward(request, response);
to retreive
MyPojoObject mo=(MyPojoObject)request.getAttribute("abc");

Reusing RequestDispatcher object

Inside doGet()/doPost() in a servlet I have:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/pages/view.jsp");
dispatcher.forward(request, response);
As the path to the jsp is not relative to current request and the RequestDispatcher is obtained from servlet context, can I reuse the same dispatcher object in multiple requests
such that
RequestDispatcher dispatcher becomes instance variable
init() has
dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/pages/view.jsp");
and doGet()/doPost() just have
dispatcher.forward(request, response);
The reason behind doing so is to save the cost of construction(/lookup) of RequestDispatcher for every request. This may really not be significant if the server implementation already caches the objects and looks up dispatcher by the url for every getRequestDispatcher() call, but by obtaining the reference to dispatcher in the code in init, we can save the cost of lookup as well.
Also want to know if will this be thread safe as same dispatcher object will be used every time?
It's supposed to be threadsafe, but there are certain servletcontainer makes/versions where this is not threadsafe. In Apache Tomcat for example, it was not been threadsafe until they fixed it in version 6.0.8.
I'd place this approach in the category "premature optimization". I wouldn't do it that way.

RequestDispatcher.forward loop

I am using
<url-pattern>/*</url-pattern>
to map all the requests to one sevlet,where i do all the authentication work.
but I want to skip some static content (like css files).so I tried fowrding them from
that sevlet to where the resource file is
if(isResourceFile){
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("static/" + fileName);
dispatcher.forward(request, response);
}
but this will start a infinite loop because this will again call the same sevlet
is there any way to work around this without mapping all the resource(css) files in web.xml?
The url-pattern of /* is better to be used exclusively by Filters, not Servlets. Put all your static files in a certain folder (maybe covered by the url-pattern of a more effective FileServlet?) and let the Filter check it.
E.g. (pseudo)
public void doFilter(request, response, chain) {
if (requestURI.startsWith("/static")) {
chain.doFilter(request, response); // Just continue. Do nothing.
} else {
request.getRequestDispatcher("/pages").forward(request, response); // Forward to page controller.
}
}
Hope this helps.
Assuming that you're looking to authenticate just JSP files, you could change the URL:
/*.jsp
I think it's a better idea to handle your authentication using a filter rather than a servlet. And in a production environment, you should use a front-end webserver for static content.
In case you cannot use a filter and you have to use a wildcard '*' in the mapping without a extension like '.jsp' then then this could work for you:
if(isResourceFile){
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/static/" + fileName);
dispatcher.forward(request, response);
return;
}
Adding the '/' in the beginning of the static directory will give it root context.

Categories