1

I just started working with JSPs and came across one problem.

As I understand, JSP pages under WEB-INF can be accessed via a browser with the URL in localhost:

localhost:8080/MyProject/MyJSP.jsp

However, if I create another sub-folder within the WEB-INF folder (i.e. 'MyFolder') and try to access the same JSP page through the URL:

localhost:8080/MyProject/MyFolder/MyJSP.jsp

it gives an Error 404 instead. Are JSP file navigation systems treated differently to, say, HTML file navigation system?

EDIT: I am using servlets to display my JSP page as such:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.sendRedirect("MyJSP.jsp");
}

EDIT2: I've changed my redirect to a requestDispatcher as I've been advised to do:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/MyFolder/MyJSP.jsp");
dispatcher.forward(request, response);
}

If my @WebServlet is ("/myjsp"), can anyone still access my MyJSP.jsp page if they type localhost:8080/MyProject/myjsp?

Jae Bin
  • 49
  • 1
  • 9

2 Answers2

3

As I understand, JSP pages under WEB-INF can be accessed via a browser with the URL in localhost

No. It's exactly the reverse. Everything under WEB-INF is not accessible by the browser.

It's a good practice to put them there precisely because you never want anyone to access a JSP from the browser directly. JSPs are views, and requests should go through a controller first, which then dispatches (i.e. forwards, not redirects, see RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()) to the right view.

JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174
  • Ah, ok. If my @WebServlet is "/myjsp" and someone types "/MyProject/myjsp" as the URL, will they still be able to access the MyJSP.jsp page? – Jae Bin Oct 01 '18 at 22:08
0

'/WEB-INF/' is considered to be a protected/secured folder and it is not advisable to make it accessible unless really required. If you still want to make these files available, try adding the below servlet mapping in your web.xml. Hope it helps

<servlet>
<servlet-name>MyJSP</servlet-name>
<jsp-file>/WEB-INF/MyFolder/*</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>MyJSP</servlet-name>
<url-pattern>/ViewMyJsp.jsp</url-pattern>
</servlet-mapping>

You can specify the mapping explicitly by declaring it with a element in the deployment descriptor. Instead of a <servlet-class> element, you specify a <jsp-file> element with the path to the JSP file from the WAR root.

Sumesh TG
  • 2,367
  • 1
  • 12
  • 29