Question

I am learning JSP and Servlets. Consider the following code inside the doPost method of a Servlet which forwards a HTTP request to a JSP -

RequestDispatcher view = request.getRequestDispatcher("/MyWebApp/MvcView.jsp");  

I wonder what will happen if someone wants this servlet to forward the request to another jsp instead of the one above ? Does one have to change this code manually every time in their application ? How can one free oneself of all this manual work ?

Was it helpful?

Solution

One simple solution is to set the url as a parameter for your servlet:

<servlet>
    <servlet-name>YourServlet</servlet-name>
    <servlet-class>com.you.YourServlet</servlet-class>

    <init-param>
        <param-name>url</param-name>
        <param-value>/MyWebApp/MvcView.jsp</param-value>
    </init-param>
</servlet>

and the in the servlet:

public class YourServlet {

  protected String url = null;

  public void init(ServletConfig servletConfig) throws ServletException {
    this.url = servletConfig.getInitParameter("url");
  }

  public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException {

    RequestDispatcher view = request.getRequestDispatcher(url);  

  }
}

then there is no need to recompile servlet code to chage the url.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top