Search code examples
javajspweb.xmlcustom-url

How to remove JSP's native request URL?


I have a webpage page called page.jsp, and I only want it to have 2 URLs:

  • /page-url-1
  • /page-url-2

In the web.xml I wrote:

<servlet>
    <servlet-name>Page</servlet-name>
    <jsp-file>page.jsp</jsp-file>
</servlet>

<servlet-mapping>
    <servlet-name>Page</servlet-name>
    <url-pattern>/page-url-1</url-pattern>
    <url-pattern>/page-url-2</url-pattern>
</servlet-mapping>

But now, it has 3 URLs:

  • /page.jsp <== Not wanted
  • /page-url-1
  • /page-url-2

Question: How do I remove the JSP's native URL, and assign it custom one(s)?


Solution

  • URL 'page.jsp' works because 'page.jsp' is placed in document root of your web application. Any file stored in your container except 'WEB-INF' folder can be served directly to the client.

    viz. file '/js/myJavascirpt.js' will be accessed if you type it in your url. Same applies for images, lets say '/images/picture.png'.

    According to Servlet specification for WEB-INF:

    A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.

    From the specification, it is clear that if you don't want to give client direct access of your files, those files should be stored under 'WEB-INF' folder. That's the reason why all classes and libraries in java web application are stored under 'WEB-INF' folder.

    When it comes to your problem, you could simply place your jsp file under 'WEB-INF' folder.

    eg: Place your jsp file under 'WEB-INF' folder:

    WEB-INF/views/jsp/page.jsp

    and change your entry in web.xml like this:

    <servlet>
        <servlet-name>Page</servlet-name>
        <jsp-file>/WEB-INF/views/jsp/page.jsp</jsp-file>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>Page</servlet-name>
        <url-pattern>/page-url-1</url-pattern>
        <url-pattern>/page-url-2</url-pattern>
    </servlet-mapping>
    

    Source: Visit JSR-000315 JavaTM Servlet 3.0 for Java Servlet Specification(Ch 10.5).