在企业产品的开发中,为了对资源进行保护,可把文件放在WEB-INF下,然而这样的话,访问资源需要一些策略,个人总结可采用:
一:使用jsp:forward
在页面上直接使用jsp:forward,如<jsp:forward page = "/WEB-INF/view/thinking/result.jsp" />
二:配置web.xml
- <!--设置访问资源 -->
- <servlet>
- <servlet-name>test</servlet-name>
- <jsp-file>/WEB-INF/view/thinking/test.jsp</jsp-file>
- </servlet>
- <servlet-mapping>
- <servlet-name>test</servlet-name>
- <url-pattern>/test.jsp</url-pattern>
- </servlet-mapping>
这样就可以在浏览器中输入:如:(注:D为工程名)
http://localhost:8888/D/test.jsp
这样配置只能针对单个文件,如果有多个文件需要进行保护,则配置文件显得臃肿.
三:利用拦截器
自己制作个类充当拦截器,拦截器类
- package net.cokeframework.Dispather;
-
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- public class Dispather extends HttpServlet {
-
-
-
-
- private static final long serialVersionUID = 1L;
-
- static String pubInit = "";
- static String selInit = "";
-
- @Override
- public void init() throws ServletException {
-
- if (pubInit == "") {
- pubInit = this.getServletContext().getInitParameter("root");
- }
- if (selInit == "") {
- selInit = this.getInitParameter("child");
- }
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- doGet(req, resp);
- }
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- String spath=req.getServletPath();
- String cpath=req.getContextPath();
- String url=req.getRequestURI();
- String path=pubInit+selInit+url.substring((cpath+spath).length());
-
- req.getRequestDispatcher(path).forward(req, resp);
- }
- }
由此可见,这个拦截器也没有什么特别的,只是拼接请求的资源真正的路径,利用服务器的转发请求.
当然顺便提一下,不能使用sendRedirect,为简单的重定向,只能用于客户端上资源进行转发,不能用sendRedirect,而getRequestDispatcher,为服务器上资源之间进行转发.关于他们之间的其他区别,不是本文讨论的范围.
同时配置web.xml
- <!-- 拦截器 -->
- <context-param>
- <param-name>root</param-name>
- <param-value>/WEB-INF</param-value>
- </context-param>
- <servlet>
- <servlet-name>dis</servlet-name>
- <servlet-class>net.cokeframework.Dispather.Dispather</servlet-class>
- <init-param>
- <param-name>child</param-name>
- <param-value>/view</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>dis</servlet-name>
- <url-pattern>/dis/*</url-pattern>
- </servlet-mapping>
这样,就可以对view文件夹下的进行访问了,如
http://localhost:8888/D/dis/study/test.jsp
就可以访问web-inf/view/study/test.jsp.