Question

I have some questions about dispatching a request in a servlet.

To sum it up, I deployed a website on a public server which forces me to have a url-pattern like /servlet/* for all my servlets (I heard that it was a default configuration anyway). The problem is that while developping the application I didn't have such restrictions and therefore didn't built it to support such patterns....now, my application just doesn't work because of the urls. Let's say me servlet is declared and mapped like this :

 <servlet>
  <servlet-name>MainController</servlet-name>
  <servlet-class>controller.controllers.MainController</servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>MainController</servlet-name>
  <url-pattern>/servlet/MainController</url-pattern>
 </servlet-mapping>

The problem is that I use this code in my Servlet :

this.getServletContext()
           .getRequestDispatcher(destination).forward(request, response);

The destination parameter is always a *.jsp at the root of my webapp juste like "/index.jsp", "home.jsp", etc.

When I was using my application on localhost my servlet had this url pattern :

<url-pattern>/MainController</url-pattern>

and everything was working fine because the request dispatcher was always searching the .jsp at the root of the webapp. But now with my new url-pattern, it tries to serch all my .jsp at servlet/* just like servlet/index.jsp and, of corse throw me a HTTP Status 404 - /servlet/index.jsp

I perfectly understand why it's acting like that as, if I recall well, Servlets cannot extend outside their current context.

But my question is, am I doomed ? Isn't there a way to tell to the request dispatcher to go to the .jsp I'm asking without taking care of the "/servlet/*" pattern ? I absolutely need the request's object because I work with it before forwarding it.

I do really don't know how to get through this, so I'm seeking some help here hoping that someone had already faced this situation or at least have a clearer vision of the situation than me.

Thank's for taking the time to read this and for helping me.

Best regards,

Sampawende.

Was it helpful?

Solution

So, destination doesn't start with / which makes its location to be dependent on the path of the calling servlet?

Fix it accordingly:

request.getRequestDispatcher("/" + destination).forward(request, response);

By the way, if you'd like to prevent direct access to JSP as well (enduser could change the URL to point to the JSP without calling the controller first), then consider placing the JSPs in /WEB-INF folder. Don't forget to change the RequestDispatcher path accordingly: "/WEB-INF/" + destination.

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