Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect the URL in a Java Servlet when forwarding to JSP?

Tags:

java

jsp

servlets

I have a servlet that looks something like this:

public class ExampleServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println(request.getPathInfo());
    }
}

with a web.xml mapping like:

<servlet>
    <servlet-name>example</servlet-name>
    <servlet-class>com.example.ExampleServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>example</servlet-name>
    <url-pattern>/example/*</url-pattern>
</servlet-mapping>

and it gives me exactly what I expect... If I go to http://localhost:8080/example/foo it prints "/foo". However, if I change the servlet to forward to a JSP file:

public class ExampleServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // do something here to check the value of request.getPathInfo()
        request.getRequestDispatcher("whatever.jsp").forward(request, response);
    }
}

then when I check the value of getPathInfo() it now reports "whatever.jsp" instead of "foo".

  1. Why has this changed before it's been forwarded to the JSP?
  2. How can I detect what URL the user's looking for?

EDIT: Just in case it matters this is on Google App Engine. Don't think it should though.

like image 473
Jeremy Logan Avatar asked Dec 03 '22 07:12

Jeremy Logan


1 Answers

The question is vague and ambiguous (is the servlet calling itself on every forward again?), but it much sounds like that you need request.getAttribute("javax.servlet.forward.request_uri").

like image 100
BalusC Avatar answered Feb 16 '23 01:02

BalusC