Use ServletContext.getContext(String uripath)
Using it, we can access servlet context of another web application deployed on the same application server.
A configuration (in server configuration) need to be added to enable this feature.
Example
- Forward the request from the current application to the /otherapp/hello.jsp page.
- Put string in the request object attribute of the current application and show it in the hello.jsp
public class GetAnotherContextServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
/** Get ServletContext of another application
* on the same Servlet container.
* This allow us to forward request to another application * on the same application server.
**/
ServletContext ctx =
request.getServletContext().getContext("/otherapp");
/** Set a request attribute and forward to hello.jsp page
* on another context.
**/
request.setAttribute("MESSAGE", "Hello There!");
RequestDispatcher dispatcher =
ctx.getRequestDispatcher("/hello.jsp");
dispatcher.forward(request, response);
}
}
Server configuration
To enable this feature in Tomcat we need to enable the crossContext attribute by setting the value to true, the default value is false.
Update the server.xml file to add the following configuration.
...
<Context path="/webapp" debug="0" reloadable="true" crossContext="true" />
...
No comments:
Post a Comment
Note: only a member of this blog may post a comment.