How can I hide the JSP file in WEB-INF folder? [du

2019-02-17 18:17发布

问题:

This question already has an answer here:

  • Include a private JSP from a Servlet 2 answers

In a simple Java web application, for example imagine you have a servlet TestServlet.java. In deployment description ( web.xml ) you can for example map the request coming to say /testpage to TestServlet so that when /testapplication/testpage is requested TestServlet handles the request. And you can for example write "Hello World" and send the response.

In directory structure ( the application that is deployed to the web server ), TestServlet.java will reside in:

webapps\testapplication\WEB-INF\classes\com\packagename\TestClass.java

which means there is no way to get to this file using the browser. ( Like entering a URL )

You can also get the request dispatcher and forward the request and response object to a JSP file like .getRequestDispatcher("/test.jsp"). But then the file will be in

webapps\testapplication\test.jsp

so connecting to http:\\server.com\test.jsp will also get this file.

I want to hide the file in WEB-INF folder so it can not be reached by the client except the mapping I have provided.

What is the appropriate way for doing this?

回答1:

I want to hide the file in WEB-INF folder so it can not be reached by the client.

Keep your jsp files under WEB-INF for example - (WEB-INF/jsp), so that by default Web Containers does not allow resources under WEB-INF folder to be accessed directly by clients, but the RequestDispatcher can access it.

request.getRequestDispatcher("/WEB-INF/test.jsp").forward(request, response);



回答2:

If you are using jsf, you can put this file in WEB-INF folder and use a navigation rule to mapping the request to the page. But if you are not, you can create a filter and map it to url "/test.jsp" using the <url-pattern> attribute and redirect to anywhere you want (like a page in WEB-INF).