How can I set the URL for a JSP page?

java, jsp, servlets

Solution

Just like any servlet, you can map a particular URL-pattern to a JSP.

Simply add this snippet in your deployment descriptor

<servlet>
    <servlet-name>fooBar</servlet-name>
    <jsp-file>/foo.jsp</jsp-file> <!-- Your JSP. Must begin with '/' -->
</servlet>

<servlet-mapping>
    <servlet-name>fooBar</servlet-name>
    <url-pattern>/bar</url-pattern> <!-- Any URL you want here -->
</servlet-mapping>

There is no facility to have annotations inside the JSP so if you don't want to make an entry inside the web.xml and work purely with annotations, you have a work around to make a sevlet that simply forwards the `RequestDispatcher` to the JSP and you can annotate this servlet with the URL that you want.

@WebServlet("/bar") //your URL pattern
public class DummyServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/path/to/foo.jsp").forward(request, response);
}

}

Problem

In a servlet I would just do ``` @WebServlet("/myURL") ``` But how would I do that with a JSP page?

Original source