作者:jspfuns
By Scott Ferguson
引論
樣板的架構: Hello, World
Servlet 評論
展示留言板
留言板的模式
作為應用屬性的留言板
留言板的邏輯
結論
引論
JSP的強大優勢在於把一種應用的商務邏輯和它的介紹分離開來。用 Smalltalk的物件導向的術語來說, JSP鼓勵MVC(model-view-controller)的web應用。JSP的classes 或 beans 是模型, JSP 是這個視圖, 而Servlet是控制器。
這個例子是一個簡單的留言板。使用者登入和留言。
It is also available in the Resin demos
Role Implementation
Model A GuestBook of Guests.
View login.jsp for new users
add.jsp for logged-in users.
Controller GuestJsp, a servlet to manage the state.
樣板的架構: Hello, World
GuestJsp的架構把 "Hello, World" 這個字串傳給login.jsp頁面。這個架構為留言板設立結構。具體細節將在下面補充。
這個例子被編譯後可以瀏覽到:
http://localhost:8080/servlet/jsp.GuestJsp
你可以看到這樣的頁面:
Hello, world
JSP模板是以Servlet的處理開始然後把處理結果傳給JSP頁進行格式化。
Forwarding uses a Servlet 2.1 feature of the ServletContext, getRequestDispatcher(). The request dispatcher lets servlets forward and include any subrequests on the server. It´s a more flexible replacements for SSI includes. The RequestDispatcher can include the results of any page, servlet, or JSP page in a servlet´s page. GuestJsp will use dispatcher.forward() to pass control to the JSP page for formatting.
GuestJsp.java: Skeleton package jsp.GuestJsp;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* GuestJsp is a servlet controlling user
* interaction with the guest book.
*/
public class GuestJsp extends HttpServlet {
/**
* doGet handles GET requests
*/
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
// Save the message in the request for login.jsp