1
votes

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?

2
FYI: Web request cannot directly access JSPs (or any other resource) inside WEB-INF. Resources inside WEB-INF can only be access by code.Andreas
And if you have the option, you should go with a modern system like Spring MVC/Boot instead of hand-writing servlets and using JSP.chrylis -cautiouslyoptimistic-
@chrylis Is JSP outdated?Jae Bin
Yes; it's tied to specific servlet models and isn't suitable for many testing scenarios or for use for e-mail, etc. Thymeleaf is generally a better choice for new projects.chrylis -cautiouslyoptimistic-

2 Answers

3
votes

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.

0
votes

'/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.