天天看點

通路路徑整理

通路路徑(實際開發中用處較大)

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" οnsubmit="return y();">

2.<a href="${ pageContext.request.contextPath }/zServlet?username=${user.username}" target="_blank" rel="external nofollow" >修改</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

繼續閱讀