JSP與Servlet的跳轉及得到路徑方法整理

今天整理項目的流程,在JSP和Servlet之間跳來跳去,曾經一段時間,我都是把Servlet路徑定義爲“/SomeServlet”,也即定義爲根目錄,因爲兼容性比較好,但是用了MyEclipse之後,新建的Servlet默認路徑是“/servlet/SomeServlet”,這樣寫便於管理,另外就是更適合單獨爲Servlet設置Filter(關於Filter的設置可以參考這篇文章)。而我的JSP文件目前是放在項目的根目錄,也即形成下圖這樣的路徑結構:

/ProjectRoot/
  |--servlet/
  |  |--Servlet1
  |  |--Servlet2
  |
  |--myJsp1.jsp
  |--myJsp2.jsp

其中Servlet跳轉有兩種方式:
1、sendRedirect()方式

response.sendRedirect(String targetUrl);

2、RequestDispather方式

RequestDispatcher requestDispatcher = request.getRequestDispatcher(String targetUrl);
requestDispatcher.forward(request, response);


第一種方式是給用戶瀏覽器發送通知,然後由瀏覽器再給服務器發送跳轉請求,所以比較類似用戶自己去點URL的跳轉,這種方式如果需要傳參給跳轉頁面,需要使用Session或者使用GET方式將參數顯式的寫在targetUrl裏(如:ooxx.jsp?id=1),而且大部分情況下由於GET方法的侷限性,這種跳轉方式只能帶較爲簡單的參數。

而第二種方式有點類似C#中的Server.Transfer()方法,即服務器端跳轉,從現象上看就是用戶的瀏覽器內容發生了變化,但是瀏覽器的地址欄不變還是老地址。這種方式由服務器直接控制request及response的走向及參數,從命令行的參數上就可以看出這一點。這樣方便程序員控制參數的傳遞,幾乎可以傳遞任何類型的參數,只要簡單的使用setAttribute()方法即可:

request.setAttribute(String attriName, Object attriValue);


但是也就是因爲它是服務器端跳轉,所以用戶瀏覽器的地址欄是不發生變化的。那麼,如果項目路徑結構如上圖所示的情況,那麼:
1、從JSP跳轉向Servlet時
只要簡單的使用相對路徑“serlvet/SomeServlet”即可。

2、從Servlet跳轉向另一個Servlet時
因爲Servlet都在相同路徑下,所以可以直接寫相對路徑,如“./SomeServlet”或直接“SomeServlet”。

3、從Servlet跳轉向JSP時
因爲Servlet路徑爲“servlet/SomeServlet”,所以如果要使用RequestDispather方式跳轉,JSP頁面在接參數時,會將地址欄的地址作爲當前目錄尋找自己需要的方法、JavaScript、CSS等。所以經常有朋友遇到JavaScript報錯“Ext未定義”就是因爲JSP頁面找不到Ext的js文件。所以這種情況,需要使用絕對路徑來告訴JSP去哪裏得到這些資源。JAVA有關獲得路徑的方法較多,測試如下:

項目根目錄:http://localhost:8080/TestProject/
JSP測試:http://localhost:8080/TestProject/TestPath.jsp

 1<%@ page language="java" contentType="text/html; charset=UTF-8"
 2    pageEncoding="UTF-8"
%>
 3<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4<html>
 5<head>
 6<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7<title>Insert title here</title>
 8</head>
 9<body>
10<%="request.getContextPath() = " + request.getContextPath() + "<BR />"%>
11<%="request.getServletPath() = " + request.getServletPath() + "<BR />"%>
12<%="request.getRequestURI() = " + request.getRequestURI() + "<BR />"%>
13<%="request.getRequestURL() = " + request.getRequestURL() + "<BR />"%>
14<%
15    String realPath = session.getServletContext().getRealPath("/");
16
%>
17<%="request.getRealPath(/"//") = " + realPath + ""%>
18</body>
19</html>

返回結果:

request.getContextPath() = /TestProject
request.getServletPath() = /TestPath.jsp
request.getRequestURI() = /TestProject/TestPath.jsp
request.getRequestURL() = http://localhost:8080/TestProject/TestPath.jsp
request.getRealPath("/") = C:/Tomcat/webapps/TestProject/


Servlet測試

 1package servlet;
 2
 3import java.io.IOException;
 4import java.io.PrintWriter;
 5
 6import javax.servlet.ServletException;
 7import javax.servlet.http.HttpServlet;
 8import javax.servlet.http.HttpServletRequest;
 9import javax.servlet.http.HttpServletResponse;
10import javax.servlet.http.HttpSession;
11
12public class TestPath extends HttpServlet {
13
14    private static final long serialVersionUID = 3093731648408094325L;
15
16    public void doGet(HttpServletRequest request, HttpServletResponse response)
17            throws ServletException, IOException {
18
19        response.setContentType("text/html");
20        PrintWriter out = response.getWriter();
21        out.println("request.getContextPath() = " + request.getContextPath() + "<BR />");
22        out.println("request.getServletPath() = " + request.getServletPath() + "<BR />");
23        out.println("request.getRequestURI() = " + request.getRequestURI() + "<BR />");
24        out.println("request.getRequestURL() = " + request.getRequestURL() + "<BR />");
25        HttpSession session = request.getSession();
26        String realPath = session.getServletContext().getRealPath("/");
27        out.println("request.getRealPath(/"//") = " + realPath + "");
28        out.flush();
29        out.close();
30    }

31
32    public void doPost(HttpServletRequest request, HttpServletResponse response)
33            throws ServletException, IOException {
34        doGet(request, response);
35    }

36
37}

返回結果:

request.getContextPath() = /TestProject
request.getServletPath() = /servlet/TestPath
request.getRequestURI() = /TestProject/servlet/TestPath
request.getRequestURL() = http://localhost:8080/TestProject/servlet/TestPath
request.getRealPath("/") = C:/Tomcat/webapps/TestProject/


這樣就一目瞭然了,另外要特別說下getRealPath()這個方法,用於得到URL的物理磁盤路徑,以前的寫法很簡單request.getRealPath(String path)即可。但是此方法已被廢棄。現在要用ServletContext.getRealPath(String path)。也就是說要先得到ServletContext對象,而這個對象獲得方式有好幾種,比較簡單的無非是從Session中獲得:

HttpSession session = request.getSession();
String realPath = session.getServletContext().getRealPath("/");

還有幾種方法同樣可以獲得ServletContext:

Javax.servlet.http.HttpSession.getServletContext()
Javax.servlet.jsp.PageContext.getServletContext()
Javax.servlet.ServletConfig.getServletContext()


以上。

參考資料:
http://hi.baidu.com/fytcm/blog/item/298975d7e796aedaa044df0a.html
http://hi.baidu.com/javagt/blog/item/6b7a68f4ebc3b3d8f2d385e3.html
http://www.blogjava.net/flysky19/articles/98006.html
http://bbs.chinaunix.net/viewthread.php?tid=383861

發佈了37 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章