访问路径整理

来源:互联网 发布:老虎 知乎 编辑:程序博客网 时间:2024/06/11 10:12

访问路径(实际开发中用处较大)

Servlet配置:

<serlvet>

<servlet-name>hello</servlet-name>

<servlet-class>cn.itcast.servlet.HelloServlet</servlet-class>

</servlet>

<servlet-mapping>

<serlvet-name>hello</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>


配置如上,访问时<a href="${pageContext.request.contextPath}/hello">hello</a>

${pageContext.request.contextPath}即为工程名


一、现象

1.<form name="form1" method=post action="${ pageContext.request.contextPath }/xServlet" onsubmit="return y();">

2.<a href="${ pageContext.request.contextPath }/zServlet?username=${user.username}">修改</a>

二、分类

1.相对路径:不以"/"开头

WebRoot下新建了一个jsp:

(1)jsp的访问路径:http://localhost/day1/1.jsp

Servlet的访问路径:http://localhost/day1/hello

使用相对路径<a href=hello>  <a href=./hello>,即可以在1.jsp中写,去访问servlet

WebRoot下的jsp文件夹下新建了一个jsp:

(2)jsp的访问路径:http://localhost/day1/jsp/2.jsp

Servlet的访问路径:http://localhost/day1/hello

使用相对路径<a href=../hello> ,即先到父文件夹(../),然后再去访问servlet,由于要判断是否在一个目录下,故容易搞晕,所以一般用绝对路径


2.绝对路径:以"/"开头的路径.

(1)jsp的访问路径:http://localhost/day1/1.jsp

Servlet的访问路径:http://localhost/day1/hello

使用绝对路径:<a href=/day1/hello>,即可在1.jsp中访问到servlet,"/"相当于到了”localhost“那层路径

(2)jsp的访问路径:http://localhost/day1/jsp/2.jsp

Servlet的访问路径:http://localhost/day1/hello

使用绝对路径:<a href=/day1/hello>

绝对路径分为两类:

1.客户端路径:需要加 项目名

如:重定向

response.sendRedirect("/day1/successs1.jsp");

2.服务器端路径:不需要加 项目名

如:转发

request.getRequestDispatcher("/successs2.jsp").forward(request, response);


相关练习

在应用名称为app的web应用中WEB-INF目录下有一个1.jpg文件,现在需要在Servlet中获取指向这个文件的字节输入流。如下哪些选项可以实现:(BD)

A. FileInputStream fin = new FileInputStream(“/WEB-INF/1.jpg”); 
B. FileInputStream fin= new FileInputStream(this.getServletContext( ).getRealPath( “/WEB-INF/1.jpg”) ) ;
C. InputStream fin =this.getClass().getClassLoader().getResourceAsStream("1.jpg"); 
D. InputStream fin =this.getClass().getClassLoader().getResourceAsStream(" ../1.jpg" ) ;

解析:由于this.getServletContext( ).getRealPath()获得web项目全路径,故找到1.jpg文件的话,需要"/WEB-INF/1.jpg"

this.getClass().getClassLoader()是类加载器,即路径从classes文件夹开始,需向上(../)到文件夹WEB-INF,才能找到1.jpg


0 0