Servlet使用jsp

 

Servlet要呼叫(公派jsp頁面)jsp跟在jsp中使用javaBeans比走來要簡單的多了,主要只是網頁傳送的技巧而已,在圖2雖使用到;

撰寫Servlet

Seervlet程序如下:

import java.io.*;

import javax.Servlet.*;

import javax.servlet.http.*;

 

public class HelloWorldServlet extendsHttpServlet{

public void Service (HttpServletRequestrequest, HttpSeervletResponse reponse) throws ServletException, IOException{

 response.setContentType("text/html; charset=big5");

       request.setCharacterEncoding("big5");

        StringtheMessage = "Hello, World!";

        StringtargetURL = "/HelloFromServlet.jsp";

        request.setAttribute("message", theMessage);

        RequestDispatcher rd;

        rd = getServletContext().getRequestDispatcher(targetURL);

        rd.forward(request,response);

}

}.

注意:

1、 之前Servlet程序都是用doGet來處理用戶端的Httprequest,這裏則改用service.

2、 Request.setAttribute().

3、 RequestDisatcher類別。

4、 getServletContext().

5、 ServletContext類別的getRequestDisatcher()方法。

6、 RequestDisatcher類別的Forward()方法。

撰寫jsp:

helloFromServlet.jsp

<%@ page language="java" contentType="text/html;charset=big5" %>
<% String msg = (String)request.getAttribute("message"); %>
<html>
<body>
 servlet 傳來的信息: <%= msg %>
</body>
</html>
 

之前的servlet程序使用到了request.setAttribute()這裏則用到了request.getAttribute() ,從這裏就可以看出來,sevletjsp通過request來儲存和傳遞給對方參數。

程序的運行過程如下:

1.      用戶端送出HTTPrequest請求,請求的網址是:http://localhost:8080/myapp/helloWordServlet.

2.      helloworldServlet收到請求後通過request.setAttribute()把要傳送給jsp的參數字串“helloWorld”儲存在request容器裏;

3.      helloWorldSservlet通過servletContext建立requestDispatcher容器,並指定轉發的網址。

4.      helloWorldServlet使用RequestDispatcherforwaard()方法,把這次的Http request轉發至另一網頁,出就是HelloFromServlet.jsp.

5.      jsp先通過request.getAttribute()取得request容器中的屬性值,該屬性值是在步驟2中由Servlet指定的,最後搭配Html標籤顯示出來。

我把整個過程書寫成了一個循序圖,你可以搭配上面的文字說明來了解程序的運行過程;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章