Servlet--慕課網筆記

第1章 Servlet基礎
1-1 Servlet概述

Servlet基礎

  • 什麼是Servlet
  • Tomcat容器等級
  • 手工編寫第一個Servlet
  • 使用MyEclipse編寫Servlet
  • Servlet聲明週期
  • Servlet獲取九大內置對象
  • Servlet與表單
  • Servlet路徑跳轉
  • 階段項目

什麼是Servlet 先有JSP還是先有Servlet?

我可以負責任的告訴大家先有Servlet。沒錯,Jsp的前身就是Servlet。

Servlet是在服務端運行的小程序。一個Servlet就是一個Java類,並且
可以通過“請求-響應”編程模型來訪問的這個駐留在服務器內裏的Servlet
程序。

1-2 Tomcat容器等級

Tomcat容器等級
Tomcat的容器分爲四個等級,Servlet的容器管理Context容器,一個
Context對應一個Web工程。

Tomcat->Container容器->Engine->HOST->Servlet容器->Context

1-3 手工編寫第一個Servlet

手工編寫第一個Servlet

  1. 繼承HttpServlet
  2. 重寫doGet()或者doPost()方法
  3. 在web.xml中註冊Servlet

Servlet ->三個方法Init() service() destory()
|
GenericServlet(Abstract Class) ->與協議無關的Servlet
|
HttpServlet(Abstract Class) ->實現了http協議的servlet
|
自定義Servlet ->一般重寫(覆蓋)doGet(),doPost()方法

public class HelloServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest requset, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("處理Get()請求...");
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        out.println("<Strong>Hello Servlet!</Strong><br>");
    }

    @Override
    protected void doPost(HttpServletRequest requset, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("處理Post()請求...");
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        out.println("<Strong>Hello Servlet!</Strong><br>");
    }


}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>servlet.HelloServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/servlet/HelloServlet</url-pattern>
  </servlet-mapping>


</web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
     <h1>第一個Servlet小例子</h1>
    <hr>
    <a href="servlet/HelloServlet">Get方式請求HelloServlet</a><br>
    <form action="servlet/HelloServlet" method="post">
      <input type="submit" value="Post方式請求HelloServlet"/> 
    </form>
  </body>
</html>
1-4 使用MyEclipse編寫Servlet

使用M有Eclipse編寫第一個Servlet

  1. src->new->Servlet
  2. 重寫doGet()或者doPost()
  3. 部署運行
public class HelloServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public HelloServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("處理get請求...");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("<strong>Hello Servlet!</strong>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("處理post請求...");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("<strong>Hello Servlet!</strong>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>servlet.HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/servlet/HelloServlet</url-pattern>
  </servlet-mapping>

</web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
     <h1>第一個Servlet小例子</h1>
    <hr>
    <a href="servlet/HelloServlet">Get方式請求HelloServlet</a><br>
    <form action="servlet/HelloServlet" method="post">
      <input type="submit" value="Post方式請求HelloServlet"/> 
    </form>
  </body>
</html>
1-5 練習題

假設在helloapp應用中有一個HelloServlet類,它在 web.xml文件中的配置如下:

 <servlet>   
  <servlet-name>HelloServlet</servlet-name>    
  <servlet-class>org.javathinker.HelloServlet</servlet-class>
 </servlet>  
<servlet-mapping>   
  <servlet-name>HelloServlet</servlet-name>  
  <url-pattern>/hello</url-pattern>
</servlet-mapping>  

那麼在瀏覽器端訪問HelloServlet的URL是什麼?

http://localhost:8080/helloapp/hello

localhost是服務器主機名,也可以是IP地址127.0.0.1;8080是tomcat服務器的端口號;helloapp是web工程的上下文地址ContexRoot(一般情況下與web工程名一致);最後是標籤中的內容。

1-6 Servlet執行流程和生命週期
  • servlet執行流程
  • 使用MyEclipse編寫第一個Servlet

Get方式請求HelloServlet -> Get方式請求HelloServlet

/servlet/HelloServlet

servlet.HelloServlet

public class HelloServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest requset, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("處理Get()請求...");

Servlet生命週期

  1. 舒適化階段,調用init()方法
  2. 響應客戶端請求階段,調用service()方法。由service()方法根據提交
    方式選擇執行doGet()或者doPost()方法。
  3. 終止階段,調用destroy()方法。
Created with Raphaël 2.1.0開始Servlet實例是否存在?調用service(Servlet Request Servlet Response)方法服務器關閉?調用destroy()方法裝載Servlet類並創建實例調用init(ServletConfig)方法yesnoyes
1-7 練習題

在Java EE中Servlet是在服務器端運行以處理客戶端請求而做出的響應的程序。下列選項中屬於Servlet生命週期階段的是
加載和實例化、初始化、服務和銷燬

1-8 練習題

編寫Servlet的doPost方法時,需要拋出異常爲
ServletException, IOException

1-9 Tomcat裝載Servlet的三種情況

在下列時刻Servlet容器裝載Servlet

  1. Servlet容器啓動時刻自動裝載某些Servlet,實現它只需在web.xml文件中的
    之間添加如下代碼:1
    數字越小表示優先級別越高。
  2. 在Servlet容器啓動後,客戶端首次向Servlet發送請求。
  3. Servlet類文件被更新後,重新裝載Servlet。
public class TestServlet1 extends HttpServlet {



    /**
     * Constructor of the object.
     */
    public TestServlet1() {
        System.out.println("TestServlet1構造方法被執行....");
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        System.out.println("TestServlet1銷燬方法被執行....");
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("TestServlet1的doGet()方法被執行...");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("<h1>大家好,我是TestServlet1!</h1>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("TestServlet1的doPost()方法被執行...");
        doGet(request,response); //讓doPost()執行與doGet()相同的操作。
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
        System.out.println("TestServlet1的初始化方法被執行....");
    }

}
public class TestServlet2 extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public TestServlet2() {
        System.out.println("TestServlet2構造方法被執行....");
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        System.out.println("TestServlet2銷燬方法被執行....");
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("TestServlet2的doGet()方法被執行...");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("<h1>您好,我是TestServlet2</h1>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("TestServlet2的doPost()方法被執行...");
        doGet(request,response); //讓doPost()執行與doGet()相同的操作
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        System.out.println("TestServlet2的初始化方法被執行....");
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>TestServlet1</servlet-name>
    <servlet-class>servlet.TestServlet1</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>TestServlet2</servlet-name>
    <servlet-class>servlet.TestServlet2</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>


  <servlet-mapping>
    <servlet-name>TestServlet1</servlet-name>
    <url-pattern>/servlet/TestServlet1</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>TestServlet2</servlet-name>
    <url-pattern>/servlet/TestServlet2</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    <h1>Servlet生命週期</h1>
    <hr>
    <a href="servlet/TestServlet1">以Get方式請求TestServlet1</a>
  </body>
</html>
1-10 Servlet與JSP內置對象的對應關係
JSP對象 怎麼獲得
out resp.getWriter
request service方法中req參數
response service方法中resp參數
session req.getSession()函數
application getServletContext()函數
exception Throwable
page this
pageContext PageContext
Config getServletConfig函數
1-11 Servlet獲取表單數據
//用戶實體類
public class Users {

    private String username; //用戶名
    private String mypassword; //密碼
    private String email; //電子郵箱
    private String gender; //性別
    private Date birthday; //出生日期
    private String[] favorites; //愛好
    private String introduce; //自我介紹
    private boolean flag; //是否接受協議

    public Users()
    {

    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getMypassword() {
        return mypassword;
    }
    public void setMypassword(String mypassword) {
        this.mypassword = mypassword;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String[] getFavorites() {
        return favorites;
    }
    public void setFavorites(String[] favorites) {
        this.favorites = favorites;
    }
    public String getIntroduce() {
        return introduce;
    }
    public void setIntroduce(String introduce) {
        this.introduce = introduce;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }


}
public class RegServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public RegServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        Users u = new Users();
        String username,mypassword,gender,email,introduce,isAccept;
        Date birthday;
        String[] favorites;


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            username = request.getParameter("username");
            mypassword = request.getParameter("mypassword");
            gender = request.getParameter("gender");
            email = request.getParameter("email");
            introduce = request.getParameter("introduce");
            birthday = sdf.parse(request.getParameter("birthday"));
            if(request.getParameterValues("isAccpet")!=null)
            {
              isAccept = request.getParameter("isAccept");
            }
            else
            {
              isAccept = "false";
            }
            //用來獲取多個複選按鈕的值
            favorites = request.getParameterValues("favorite");
            u.setUsername(username);
            u.setMypassword(mypassword);
            u.setGender(gender);
            u.setEmail(email);
            u.setFavorites(favorites);
            u.setIntroduce(introduce);
            if(isAccept.equals("true"))
            {
                u.setFlag(true);
            }
            else
            {
                u.setFlag(false);
            }
            u.setBirthday(birthday);

            //把註冊成功的用戶對象保存在session中
            request.getSession().setAttribute("regUser", u);
            //跳轉到註冊成功頁面
            request.getRequestDispatcher("../userinfo.jsp").forward(request,response);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }


    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>RegServlet</servlet-name>
    <servlet-class>servlet.RegServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>RegServlet</servlet-name>
    <url-pattern>/servlet/RegServlet</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'reg.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
     .label{
          width: 20%    
     }
     .controler{
          width: 80%    
     }
   </style>  
   <script type="text/javascript" src="js/Calendar3.js"></script>
  </head>

  <body>
    <h1>用戶註冊</h1>
    <hr>
    <form name="regForm" action="servlet/RegServlet" method="post" >
              <table border="0" width="800" cellspacing="0" cellpadding="0">
                <tr>
                    <td class="lalel">用戶名:</td>
                    <td class="controler"><input type="text" name="username" /></td>
                </tr>
                <tr>
                    <td class="label">密碼:</td>
                    <td class="controler"><input type="password" name="mypassword" ></td>

                </tr>
                <tr>
                    <td class="label">確認密碼:</td>
                    <td class="controler"><input type="password" name="confirmpass" ></td>

                </tr>
                <tr>
                    <td class="label">電子郵箱:</td>
                    <td class="controler"><input type="text" name="email" ></td>

                </tr>
                <tr>
                    <td class="label">性別:</td>
                    <td class="controler"><input type="radio" name="gender" checked="checked" value="Male"><input type="radio" name="gender" value="Female"></td>

                </tr>

                <tr>
                    <td class="label">出生日期:</td>
                    <td class="controler">
                      <input name="birthday" type="text" id="control_date" size="10"
                      maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" />
                    </td>
                </tr>
                <tr>
                    <td class="label">愛好:</td>
                    <td class="controler">
                    <input type="checkbox" name="favorite" value="nba"> NBA &nbsp;
                      <input type="checkbox" name="favorite" value="music"> 音樂 &nbsp;
                      <input type="checkbox" name="favorite" value="movie"> 電影 &nbsp;
                      <input type="checkbox" name="favorite" value="internet"> 上網 &nbsp;
                    </td>
                </tr>
                <tr>
                    <td class="label">自我介紹:</td>
                    <td class="controler">
                        <textarea name="introduce" rows="10" cols="40"></textarea>
                    </td>
                </tr>
                <tr>
                    <td class="label">接受協議:</td>
                    <td class="controler">
                        <input type="checkbox" name="isAccept" value="true">是否接受霸王條款
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" value="註冊"/>&nbsp;&nbsp;
                        <input type="reset" value="取消"/>&nbsp;&nbsp;
                    </td>
                </tr>
              </table>
            </form>
  </body>
</html>
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'userinfo.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
     .title{
         width: 30%;    
         background-color: #CCC;
         font-weight: bold;
     }
     .content{
         width:70%;
         background-color: #CBCFE5;
     }

   </style>  
  </head>

  <body>
    <h1>用戶信息</h1>
    <hr>
    <center>
     <jsp:useBean  id="regUser" class="entity.Users" scope="session"/>   
     <table width="600" cellpadding="0" cellspacing="0" border="1">
        <tr>
          <td class="title">用戶名:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="username"/></td>
        </tr>
        <tr>
          <td class="title">密碼:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="mypassword"/></td>
        </tr>
        <tr>
          <td class="title">性別:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="gender"/></td>
        </tr>
        <tr>
          <td class="title">E-mail:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="email"/></td>
        </tr>
        <tr>
          <td class="title">出生日期:</td>
          <td class="content">&nbsp;
            <% 
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
               String date = sdf.format(regUser.getBirthday());

            %>
             <%=date%>
          </td>
        </tr>
        <tr>
          <td class="title">愛好:</td>
          <td class="content">&nbsp;
            <% 
               String[] favorites = regUser.getFavorites();
               for(String f:favorites)
               {
            %>
                <%=f%> &nbsp;&nbsp;
            <% 
               }
            %>
          </td>
        </tr>
        <tr>
          <td class="title">自我介紹:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="introduce"/></td>
        </tr>
        <tr>
          <td class="title">是否介紹協議:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="flag"/></td>
        </tr>
     </table>
    </center>
  </body>
</html>
1-12 練習題

在J2EE中,對於HttpServlet類的描述,不正確的是
我們自己編寫的Servlet繼承了HttpServlet類,一般只需覆蓋doPost或者doGet方法,不必覆蓋service( )方法,因爲一個sevrvice( )方法是空的。

HttpServlet類擴展了GenericServlet類,實現了GenericServlet類的抽象方法
sevrvice( )
HttpServlet類有兩個sevrvice( )方法
我們自己編寫的Servlet繼承了HttpServlet類,一般只需覆蓋doPost或者doGet方法,不必覆蓋sevrvice( )方法.因爲一個sevrvice( )方法會調用doPost或者doGet方法

該選項描述錯誤,不覆蓋service()方法,不是因爲該方法是空,而是因爲sevrvice( )方法會調用doPost或者doGet方法。

1-13 Servlet路徑跳轉

Servlet路徑跳轉

  • 絕對路徑:放之四海而皆準的路徑
  • 相對路徑:相對於當前資源的路徑
public class HelloServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public HelloServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("<h1>您好,我是HelloServlet!</h1>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
public class TestServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public TestServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         //請求重定向方式跳轉到test.jsp,當前路徑是ServletPathDirection/servlet/
         //response.sendRedirect("test.jsp");
         //使用request.getContextPath獲得上下文對象
         //response.sendRedirect(request.getContextPath()+"/test.jsp");

        //服務器內部跳轉,這裏的斜線表示項目的根目錄
        //request.getRequestDispatcher("/test.jsp").forward(request, response);
        request.getRequestDispatcher("../test.jsp").forward(request, response);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>servlet.HelloServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>servlet.TestServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <!--url-pattern處必須以/開頭,這裏的/表示項目的根目錄  -->
    <url-pattern>/servlet/HelloServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/servlet/TestServlet</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    <h1>Servlet路徑跳轉</h1>
    <hr>
    <!--使用相對路徑訪問HelloServlet -->
    <!-- /servlet/HelloServlet 第一個/表示服務器的根目錄 -->
    <a href="servlet/HelloServlet">訪問HelloServlet!</a><br>
    <!-- 使用絕對路徑 訪問HelloServlet,可以使用path變量:path變量表示項目的根目錄-->
    <a href="<%=path%>/servlet/HelloServlet">訪問HelloServlet!</a><br>
    <!--表單中action的URL地址寫法,與超鏈接方式完全相同。 -->
    <a href="servlet/TestServlet">訪問TestServlet,跳轉到Test.jsp</a>

  </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    <h1>Test.jsp</h1>
    <hr>
  </body>
</html>
1-14 階段案例
//用戶類
public class Users {

    private String username;
    private String password;

    public Users()
    {

    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


}
public class LoginServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public LoginServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Users u = new Users();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        u.setUsername(username);
        u.setPassword(password);
        //判斷用戶名和密碼是否合法
        if(u.getUsername().equals("admin")&&u.getPassword().equals("admin"))
        {
            request.getSession().setAttribute("loginUser", username);
            response.sendRedirect(request.getContextPath()+"/login_success.jsp");
        }
        else
        {
            response.sendRedirect(request.getContextPath()+"/login_failure.jsp");
        }
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>servlet.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/servlet/LoginServlet</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
    <head>
        <!-- Page title -->
        <title>imooc - Login</title>
        <!-- End of Page title -->
        <!-- Libraries -->
        <link type="text/css" href="css/login.css" rel="stylesheet" />  
        <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /> 
        <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
        <script type="text/javascript" src="js/easyTooltip.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
        <!-- End of Libraries -->   
    </head>
    <body>
    <div id="container">
        <div class="logo">
            <a href="#"><img src="assets/logo.png" alt="" /></a>
        </div>
        <div id="box">
             登錄失敗!請檢查用戶或者密碼!<br>
          <a href="login.jsp">返回登錄</a>   
        </div>
    </div>
    </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
    <head>
        <!-- Page title -->
        <title>imooc - Login</title>
        <!-- End of Page title -->
        <!-- Libraries -->
        <link type="text/css" href="css/login.css" rel="stylesheet" />  
        <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /> 
        <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
        <script type="text/javascript" src="js/easyTooltip.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
        <!-- End of Libraries -->   
    </head>
    <body>
    <div id="container">
        <div class="logo">
            <a href="#"><img src="assets/logo.png" alt="" /></a>
        </div>
        <div id="box">
          <% 
             String loginUser = "";
             if(session.getAttribute("loginUser")!=null)
             {
                loginUser = session.getAttribute("loginUser").toString();
             }
          %>
             歡迎您<font color="red"><%=loginUser%></font>,登錄成功!
        </div>
    </div>
    </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
    <head>
        <!-- Page title -->
        <title>imooc - Login</title>
        <!-- End of Page title -->
        <!-- Libraries -->
        <link type="text/css" href="css/login.css" rel="stylesheet" />  
        <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /> 
        <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
        <script type="text/javascript" src="js/easyTooltip.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
        <!-- End of Libraries -->   
    </head>
    <body>
    <div id="container">
        <div class="logo">
            <a href="#"><img src="assets/logo.png" alt="" /></a>
        </div>
        <div id="box">
            <form action="servlet/LoginServlet" method="post">
            <p class="main">
                <label>用戶名: </label>
                <input name="username" value="" /> 
                <label>密碼: </label>
                <input type="password" name="password" value="">    
            </p>
            <p class="space">
                <input type="submit" value="登錄" class="login" style="cursor: pointer;"/>
            </p>
            </form>
        </div>
    </div>
    </body>
</html>
第2章 應用MVC架構實現項目
2-1 獲取初始化參數

Servlet高級

  1. 獲取初始化參數
  2. MVC設計模式
  3. Model2簡介
  4. 階段項目

獲取初始化參數
在web.xml中配置Servlet時,可以配置一些初始化參數。而在Servlet中可以
通過ServletConfig接口提供的方法來獲取這些參數。

public class GetInitParameterServlet extends HttpServlet {

    private String username;//用戶名
    private String password; //密碼



    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Constructor of the object.
     */
    public GetInitParameterServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("<h2>"+"用戶名:"+this.getUsername()+"</h2>");
        out.println("<h2>"+"密碼:"+this.getPassword()+"</h2>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
      this.setUsername(this.getInitParameter("username"));
      this.setPassword(this.getInitParameter("password"));
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>GetInitParameterServlet</servlet-name>
    <servlet-class>servlet.GetInitParameterServlet</servlet-class>
    <init-param>
      <param-name>username</param-name>
      <param-value>admin</param-value>
    </init-param>
    <init-param>
      <param-name>password</param-name>
      <param-value>123456</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>GetInitParameterServlet</servlet-name>
    <url-pattern>/servlet/GetInitParameterServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    <h1>獲取初始化參數演示案例</h1>
    <hr>
    <a href="servlet/GetInitParameterServlet">獲取初始化參數Servlet</a>
  </body>
</html>
2-2 練習題

從以下哪一個選項中可以獲得Servlet的初始化參數
ServletConfig

2-3 MVC模型介紹

MVC
MVC模式:MVC(Model、View、Controller),是軟件開發過程中比較流行的
設計思想。旨在分離模型、控制、視圖。是一種分層思想的體現。

2-4 Model2模型介紹

Model1簡介
瀏覽器 - JSP JavaBean - 企業數據庫

Model2簡介
JSP(V)-Servlet(C)-JavaBean(M)-DB

2-5 項目概述

使用servlet技術實現購物車效果

2-6 界面原型效果及界面開發步驟

MVC模型實現(Jsp+Servlet+dao)

創建購物車類
編寫Servlet
創建頁面層

2-7 購物車類的設計

購物車類(Cart)的設計

  • 添加
  • 刪除
  • 計算總金額
//購物車類
public class Cart {

    //購買商品的集合
    private HashMap<Items,Integer> goods;

    //購物車的總金額
    private double totalPrice;

    //構造方法
    public Cart(){
        goods = new HashMap<Items,Integer>();
        totalPrice = 0.0;
    }



    public HashMap<Items, Integer> getGoods() {
        return goods;
    }

    public void setGoods(HashMap<Items, Integer> goods) {
        this.goods = goods;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }


    //添加商品進購物車
    public boolean addGoodsInCart(Items item,int number){
        goods.put(item, number);
        calTotalPrice();//重新計算購物車的總金額
        return true;
    }

    //刪除商品的方法
    public boolean removeGoodsFromCart(Items item){
        goods.remove(item);
        calTotalPrice();//重新計算購物車的總金額
        return true;
    }

    //統計購物車的總金額
    public double calTotalPrice(){
        double sum = 0.0;
        Set<Items> keys = goods.keySet();
        Iterator<Items> it = keys.iterator();
        while(it.hasNext()){
            Items i = it.next();
            sum += i.getPrice()*goods.get(i);

        }
        this.setTotalPrice(sum);//設置購物車的總金額
        return sum;
    }

}
2-8 測試購物車類
//購物車類
public class Cart {

    // 購買商品的集合
    private HashMap<Items, Integer> goods;

    // 購物車的總金額
    private double totalPrice;

    // 構造方法
    public Cart() {
        goods = new HashMap<Items, Integer>();
        totalPrice = 0.0;
    }

    public HashMap<Items, Integer> getGoods() {
        return goods;
    }

    public void setGoods(HashMap<Items, Integer> goods) {
        this.goods = goods;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    // 添加商品進購物車
    public boolean addGoodsInCart(Items item, int number) {
        goods.put(item, number);
        calTotalPrice();// 重新計算購物車的總金額
        return true;
    }

    // 刪除商品的方法
    public boolean removeGoodsFromCart(Items item) {
        goods.remove(item);
        calTotalPrice();// 重新計算購物車的總金額
        return true;
    }

    // 統計購物車的總金額
    public double calTotalPrice() {
        double sum = 0.0;
        Set<Items> keys = goods.keySet();
        Iterator<Items> it = keys.iterator();
        while (it.hasNext()) {
            Items i = it.next();
            sum += i.getPrice() * goods.get(i);

        }
        this.setTotalPrice(sum);// 設置購物車的總金額
        return sum;
    }

    public static void main(String[] args) {

        // 先創建兩個商品對象
        Items i1 = new Items(1, "沃特籃球鞋", "溫州", 200, 500, "001.jpg");
        Items i2 = new Items(2, "李寧運動鞋", "廣州", 300, 500, "002.jpg");
        Items i3 = new Items(1, "沃特籃球鞋", "溫州", 200, 500, "001.jpg");

        Cart c = new Cart();
        c.addGoodsInCart(i1, 1);
        c.addGoodsInCart(i2, 2);
        // 再次購買沃特籃球鞋,購買3雙
        c.addGoodsInCart(i3, 3);

        // 變量購物商品的集合
        Set<Map.Entry<Items, Integer>> items = c.getGoods().entrySet();
        for (Map.Entry<Items, Integer> obj : items) {
            System.out.println(obj);
        }

        System.out.println("購物車的總金額:" + c.getTotalPrice());

    }

}
2-9 如何保證不添加重複商品進購物車
//購物車類
public class Cart {

    //購買商品的集合
    private HashMap<Items,Integer> goods;

    //購物車的總金額
    private double totalPrice;

    //構造方法
    public Cart()
    {
        goods = new HashMap<Items,Integer>();
        totalPrice = 0.0;
    }


    public HashMap<Items, Integer> getGoods() {
        return goods;
    }

    public void setGoods(HashMap<Items, Integer> goods) {
        this.goods = goods;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    //添加商品進購物車的方法
    public boolean addGoodsInCart(Items item ,int number)
    {
        if(goods.containsKey(item))
        {
            goods.put(item, goods.get(item)+number);
        }
        else
        {
            goods.put(item, number);    
        }
        calTotalPrice(); //重新計算購物車的總金額
        return true;
    }

    //刪除商品的方法
    public boolean removeGoodsFromCart(Items item)
    {
        goods.remove(item);
        calTotalPrice(); //重新計算購物車的總金額
        return true;
    }

    //統計購物車的總金額
    public double calTotalPrice()
    {
        double sum = 0.0;
        Set<Items> keys = goods.keySet(); //獲得鍵的集合
        Iterator<Items> it = keys.iterator(); //獲得迭代器對象
        while(it.hasNext())
        {
            Items i = it.next();
            sum += i.getPrice()* goods.get(i);
        }
        this.setTotalPrice(sum); //設置購物車的總金額
        return this.getTotalPrice();
    }

    public static void main(String[] args) {

        //先創建兩個商品對象
        Items i1 = new Items(1,"沃特籃球鞋","溫州",200,500,"001.jpg");
        Items i2 = new Items(2,"李寧運動鞋","廣州",300,500,"002.jpg");
        Items i3 = new Items(1,"沃特籃球鞋","溫州",200,500,"001.jpg");

        Cart c = new Cart();
        c.addGoodsInCart(i1, 1);
        c.addGoodsInCart(i2, 2);
        //再次購買沃特籃球鞋,購買3雙
        c.addGoodsInCart(i3, 3);


        //變量購物商品的集合
        Set<Map.Entry<Items, Integer>> items= c.getGoods().entrySet();
        for(Map.Entry<Items, Integer> obj:items)
        {
            System.out.println(obj);
        }


        System.out.println("購物車的總金額:"+c.getTotalPrice());

    }

}
//商品類
public class Items {

    private int id; // 商品編號
    private String name; // 商品名稱
    private String city; // 產地
    private int price; // 價格
    private int number; // 庫存
    private String picture; // 商品圖片

    //保留此不帶參數的構造方法
    public Items()
    {

    }

    public Items(int id,String name,String city,int price,int number,String picture)
    {
        this.id = id;
        this.name = name;
        this.city = city;
        this.picture = picture;
        this.price = price;
        this.number = number;

    }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }



    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return this.getId()+this.getName().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        if(this==obj)
        {
            return true;
        }
        if(obj instanceof Items)
        {
            Items i = (Items)obj;
            if(this.getId()==i.getId()&&this.getName().equals(i.getName()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    public String toString()
    {
        return "商品編號:"+this.getId()+",商品名稱:"+this.getName();
    }

}
2-10 添加商品進購物車
2-11 顯示購物車
2-12 商品刪除
//商品的業務邏輯類
public class ItemsDAO {

    // 獲得所有的商品信息
    public ArrayList<Items> getAllItems() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
        try {
            conn = DBHelper.getConnection();
            String sql = "select * from items;"; // SQL語句
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next()) {
                Items item = new Items();
                item.setId(rs.getInt("id"));
                item.setName(rs.getString("name"));
                item.setCity(rs.getString("city"));
                item.setNumber(rs.getInt("number"));
                item.setPrice(rs.getInt("price"));
                item.setPicture(rs.getString("picture"));
                list.add(item);// 把一個商品加入集合
            }
            return list; // 返回集合。
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            // 釋放數據集對象
            if (rs != null) {
                try {
                    rs.close();
                    rs = null;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            // 釋放語句對象
            if (stmt != null) {
                try {
                    stmt.close();
                    stmt = null;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

    }

    // 根據商品編號獲得商品資料
    public Items getItemsById(int id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = DBHelper.getConnection();
            String sql = "select * from items where id=?;"; // SQL語句
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, id);
            rs = stmt.executeQuery();
            if (rs.next()) {
                Items item = new Items();
                item.setId(rs.getInt("id"));
                item.setName(rs.getString("name"));
                item.setCity(rs.getString("city"));
                item.setNumber(rs.getInt("number"));
                item.setPrice(rs.getInt("price"));
                item.setPicture(rs.getString("picture"));
                return item;
            } else {
                return null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            // 釋放數據集對象
            if (rs != null) {
                try {
                    rs.close();
                    rs = null;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            // 釋放語句對象
            if (stmt != null) {
                try {
                    stmt.close();
                    stmt = null;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        }
    }
    //獲取最近瀏覽的前五條商品信息
    public ArrayList<Items> getViewList(String list)
    {
        System.out.println("list:"+list);
        ArrayList<Items> itemlist = new ArrayList<Items>();
        int iCount=5; //每次返回前五條記錄
        if(list!=null&&list.length()>0)
        {
            String[] arr = list.split(",");
            System.out.println("arr.length="+arr.length);
            //如果商品記錄大於等於5條
            if(arr.length>=5)
            {
               for(int i=arr.length-1;i>=arr.length-iCount;i--)
               {
                  itemlist.add(getItemsById(Integer.parseInt(arr[i])));  
               }
            }
            else
            {
                for(int i=arr.length-1;i>=0;i--)
                {
                    itemlist.add(getItemsById(Integer.parseInt(arr[i])));
                }
            }
            return itemlist;
        }
        else
        {
            return null;
        }

    }

}
//購物車類
public class Cart {

    //購買商品的集合
    private HashMap<Items,Integer> goods;

    //購物車的總金額
    private double totalPrice;

    //構造方法
    public Cart()
    {
        goods = new HashMap<Items,Integer>();
        totalPrice = 0.0;
    }


    public HashMap<Items, Integer> getGoods() {
        return goods;
    }

    public void setGoods(HashMap<Items, Integer> goods) {
        this.goods = goods;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    //添加商品進購物車的方法
    public boolean addGoodsInCart(Items item ,int number)
    {
        if(goods.containsKey(item))
        {
            goods.put(item, goods.get(item)+number);
        }
        else
        {
            goods.put(item, number);    
        }
        calTotalPrice(); //重新計算購物車的總金額
        return true;
    }

    //刪除商品的方法
    public boolean removeGoodsFromCart(Items item)
    {
        goods.remove(item);
        calTotalPrice(); //重新計算購物車的總金額
        return true;
    }

    //統計購物車的總金額
    public double calTotalPrice()
    {
        double sum = 0.0;
        Set<Items> keys = goods.keySet(); //獲得鍵的集合
        Iterator<Items> it = keys.iterator(); //獲得迭代器對象
        while(it.hasNext())
        {
            Items i = it.next();
            sum += i.getPrice()* goods.get(i);
        }
        this.setTotalPrice(sum); //設置購物車的總金額
        return this.getTotalPrice();
    }

    public static void main(String[] args) {

        //先創建兩個商品對象
        Items i1 = new Items(1,"沃特籃球鞋","溫州",200,500,"001.jpg");
        Items i2 = new Items(2,"李寧運動鞋","廣州",300,500,"002.jpg");
        Items i3 = new Items(1,"沃特籃球鞋","溫州",200,500,"001.jpg");

        Cart c = new Cart();
        c.addGoodsInCart(i1, 1);
        c.addGoodsInCart(i2, 2);
        //再次購買沃特籃球鞋,購買3雙
        c.addGoodsInCart(i3, 3);


        //變量購物商品的集合
        Set<Map.Entry<Items, Integer>> items= c.getGoods().entrySet();
        for(Map.Entry<Items, Integer> obj:items)
        {
            System.out.println(obj);
        }


        System.out.println("購物車的總金額:"+c.getTotalPrice());

    }

}
//商品類
public class Items {

    private int id; // 商品編號
    private String name; // 商品名稱
    private String city; // 產地
    private int price; // 價格
    private int number; // 庫存
    private String picture; // 商品圖片

    //保留此不帶參數的構造方法
    public Items()
    {

    }

    public Items(int id,String name,String city,int price,int number,String picture)
    {
        this.id = id;
        this.name = name;
        this.city = city;
        this.picture = picture;
        this.price = price;
        this.number = number;

    }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }



    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return this.getId()+this.getName().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        if(this==obj)
        {
            return true;
        }
        if(obj instanceof Items)
        {
            Items i = (Items)obj;
            if(this.getId()==i.getId()&&this.getName().equals(i.getName()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    public String toString()
    {
        return "商品編號:"+this.getId()+",商品名稱:"+this.getName();
    }

}
public class CartServlet extends HttpServlet {

    private String action ; //表示購物車的動作 ,add,show,delete
    //商品業務邏輯類的對象
    private ItemsDAO idao = new ItemsDAO();


    /**
     * Constructor of the object.
     */
    public CartServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(request.getParameter("action")!=null)
        {
            this.action = request.getParameter("action");
            if(action.equals("add")) //如果是添加商品進購物車
            {
                if(addToCart(request,response))
                {
                    request.getRequestDispatcher("/success.jsp").forward(request, response);
                }
                else
                {
                    request.getRequestDispatcher("/failure.jsp").forward(request, response);
                }
            }
            if(action.equals("show"))//如果是顯示購物車
            {
                request.getRequestDispatcher("/cart.jsp").forward(request, response);
            }
            if(action.equals("delete")) //如果是執行刪除購物車中的商品
            {
                if(deleteFromCart(request,response))
                {
                    request.getRequestDispatcher("/cart.jsp").forward(request, response);
                }
                else
                {
                    request.getRequestDispatcher("/cart.jsp").forward(request, response);
                }
            }
        }

    }

    //添加商品進購物車的方法
    private boolean addToCart(HttpServletRequest request, HttpServletResponse response)
    {
        String id = request.getParameter("id");
        String number = request.getParameter("num");
        Items item = idao.getItemsById(Integer.parseInt(id));

        //是否是第一次給購物車添加商品,需要給session中創建一個新的購物車對象
        if(request.getSession().getAttribute("cart")==null)
        {
            Cart cart = new Cart();
            request.getSession().setAttribute("cart",cart);
        }
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        if(cart.addGoodsInCart(item, Integer.parseInt(number)))
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    //從購物車中刪除商品
    private boolean deleteFromCart(HttpServletRequest request, HttpServletResponse response)
    {
        String id = request.getParameter("id");
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        Items item = idao.getItemsById(Integer.parseInt(id));
        if(cart.removeGoodsFromCart(item))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
public class DBHelper {

    private static final String driver = "com.mysql.jdbc.Driver"; //數據庫驅動
    //連接數據庫的URL地址
    private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8"; 
    private static final String username="root";//數據庫的用戶名
    private static final String password="root";//數據庫的密碼

    private static Connection conn=null;

    //靜態代碼塊負責加載驅動
    static 
    {
        try
        {
            Class.forName(driver);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    //單例模式返回數據庫連接對象
    public static Connection getConnection() throws Exception
    {
        if(conn==null)
        {
            conn = DriverManager.getConnection(url, username, password);
            return conn;
        }
        return conn;
    }

    public static void main(String[] args) {

        try
        {
           Connection conn = DBHelper.getConnection();
           if(conn!=null)
           {
               System.out.println("數據庫連接正常!");
           }
           else
           {
               System.out.println("數據庫連接異常!");
           }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>CartServlet</servlet-name>
    <servlet-class>servlet.CartServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>CartServlet</servlet-name>
    <url-pattern>/servlet/CartServlet</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="entity.Cart" %>
<%@ page import="entity.Items" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'cart.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <link type="text/css" rel="stylesheet" href="css/style1.css" />
    <script language="javascript">
        function delcfm() {
            if (!confirm("確認要刪除?")) {
                window.event.returnValue = false;
            }
        }
   </script>
  </head>

  <body>
   <h1>我的購物車</h1>
   <a href="index.jsp">首頁</a> >> <a href="index.jsp">商品列表</a>
   <hr> 
   <div id="shopping">
   <form action="" method="">       
            <table>
                <tr>
                    <th>商品名稱</th>
                    <th>商品單價</th>
                    <th>商品價格</th>
                    <th>購買數量</th>
                    <th>操作</th>
                </tr>
                <% 
                   //首先判斷session中是否有購物車對象
                   if(request.getSession().getAttribute("cart")!=null)
                   {
                %>
                <!-- 循環的開始 -->
                     <% 
                         Cart cart = (Cart)request.getSession().getAttribute("cart");
                         HashMap<Items,Integer> goods = cart.getGoods();
                         Set<Items> items = goods.keySet();
                         Iterator<Items> it = items.iterator();

                         while(it.hasNext())
                         {
                            Items i = it.next();
                     %> 
                <tr name="products" id="product_id_1">
                    <td class="thumb"><img src="images/<%=i.getPicture()%>" /><a href=""><%=i.getName()%></a></td>
                    <td class="number"><%=i.getPrice() %></td>
                    <td class="price" id="price_id_1">
                        <span><%=i.getPrice()*goods.get(i) %></span>
                        <input type="hidden" value="" />
                    </td>
                    <td class="number">
                        <%=goods.get(i)%>                   
                    </td>                        
                    <td class="delete">
                      <a href="servlet/CartServlet?action=delete&id=<%=i.getId()%>" onclick="delcfm();">刪除</a>                                    
                    </td>
                </tr>
                     <% 
                         }
                     %>
                <!--循環的結束-->

            </table>
             <div class="total"><span id="total">總計:<%=cart.getTotalPrice() %></span></div>
              <% 
                }
             %>
            <div class="button"><input type="submit" value="" /></div>
        </form>
    </div>
  </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'details.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <link href="css/main.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="js/lhgcore.js"></script>
    <script type="text/javascript" src="js/lhgdialog.js"></script>
    <script type="text/javascript">
      function selflog_show(id)
      { 
         var num =  document.getElementById("number").value; 
         J.dialog.get({id: 'haoyue_creat',title: '購物成功',width: 600,height:400, link: '<%=path%>/servlet/CartServlet?id='+id+'&num='+num+'&action=add', cover:true});
      }
      function add()
      {
         var num = parseInt(document.getElementById("number").value);
         if(num<100)
         {
            document.getElementById("number").value = ++num;
         }
      }
      function sub()
      {
         var num = parseInt(document.getElementById("number").value);
         if(num>1)
         {
            document.getElementById("number").value = --num;
         }
      }

    </script>

    <style type="text/css">
       hr{

         border-color:FF7F00; 
       }

       div{
          float:left;
          margin-left: 30px;
          margin-right:30px;
          margin-top: 5px;
          margin-bottom: 5px;

       }
       div dd{
          margin:0px;
          font-size:10pt;
       }
       div dd.dd_name
       {
          color:blue;
       }
       div dd.dd_city
       {
          color:#000;
       }
       div #cart
       {
         margin:0px auto;
         text-align:right; 
       }
       span{
         padding:0 2px;border:1px #c0c0c0 solid;cursor:pointer;
       }
       a{
          text-decoration: none; 
       }
    </style>
  </head>

  <body>
    <h1>商品詳情</h1>
    <a href="index.jsp">首頁</a> >> <a href="index.jsp">商品列表</a>
    <hr>
    <center>
      <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <!-- 商品詳情 -->
          <% 
             ItemsDAO itemDao = new ItemsDAO();
             Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
             if(item!=null)
             {
          %>
          <td width="70%" valign="top">
             <table>
               <tr>
                 <td rowspan="5"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
               </tr>
               <tr>
                 <td><B><%=item.getName() %></B></td> 
               </tr>
               <tr>
                 <td>產地:<%=item.getCity()%></td>
               </tr>
               <tr>
                 <td>價格:<%=item.getPrice() %></td>
               </tr>
               <tr>
                 <td>購買數量:<span id="sub" onclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2"/><span id="add" onclick="add();">+</span></td>
               </tr> 
             </table>
             <div id="cart">
               <img src="images/buy_now.png"><a href="javascript:selflog_show(<%=item.getId()%>)"><img src="images/in_cart.png"></a><a href="servlet/CartServlet?action=show"><img src="images/view_cart.jpg"/></a>
             </div>
          </td>
          <% 
            }
          %>
          <% 
              String list ="";
              //從客戶端獲得Cookies集合
              Cookie[] cookies = request.getCookies();
              //遍歷這個Cookies集合
              if(cookies!=null&&cookies.length>0)
              {
                  for(Cookie c:cookies)
                  {
                      if(c.getName().equals("ListViewCookie"))
                      {
                         list = c.getValue();
                      }
                  }
              }

              list+=request.getParameter("id")+",";
              //如果瀏覽記錄超過1000條,清零.
              String[] arr = list.split(",");
              if(arr!=null&&arr.length>0)
              {
                  if(arr.length>=1000)
                  {
                      list="";
                  }
              }
              Cookie cookie = new Cookie("ListViewCookie",list);
              response.addCookie(cookie);

          %>
          <!-- 瀏覽過的商品 -->
          <td width="30%" bgcolor="#EEE" align="center">
             <br>
             <b><font color="#FF7F00">您瀏覽過的商品</font></b><br>
             <!-- 循環開始 -->
             <% 
                ArrayList<Items> itemlist = itemDao.getViewList(list);
                if(itemlist!=null&&itemlist.size()>0 )
                {
                   System.out.println("itemlist.size="+itemlist.size());
                   for(Items i:itemlist)
                   {

             %>
             <div>
             <dl>
               <dt>
                 <a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
               </dt>
               <dd class="dd_name"><%=i.getName() %></dd> 
               <dd class="dd_city">產地:<%=i.getCity() %>&nbsp;&nbsp;價格:<%=i.getPrice() %></dd> 
             </dl>
             </div>
             <% 
                   }
                }
             %>
             <!-- 循環結束 -->
          </td>
        </tr>
      </table>
    </center>
  </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'success.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    <center>
      <img src="images/add_cart_failure.jpg"/>
      <hr>

      <br>
      <br>
      <br>

    </center>
  </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
       hr{
        border-color:FF7F00; 
       }
       div{
          float:left;
          margin: 10px;
       }
       div dd{
          margin:0px;
          font-size:10pt;
       }
       div dd.dd_name
       {
          color:blue;
       }
       div dd.dd_city
       {
          color:#000;
       }
    </style>
  </head>

  <body>
    <h1>商品展示</h1>
    <hr>

    <center>
    <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td>

          <!-- 商品循環開始 -->
           <% 
               ItemsDAO itemsDao = new ItemsDAO(); 
               ArrayList<Items> list = itemsDao.getAllItems();
               if(list!=null&&list.size()>0)
               {
                   for(int i=0;i<list.size();i++)
                   {
                      Items item = list.get(i);
           %>   
          <div>
             <dl>
               <dt>
                 <a href="details.jsp?id=<%=item.getId()%>"><img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/></a>
               </dt>
               <dd class="dd_name"><%=item.getName() %></dd> 
               <dd class="dd_city">產地:<%=item.getCity() %>&nbsp;&nbsp;價格:¥ <%=item.getPrice() %></dd> 
             </dl>
          </div>
          <!-- 商品循環結束 -->

          <%
                   }
              } 
          %>
        </td>
      </tr>
    </table>
    </center>
  </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'success.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    <center>
      <img src="images/add_cart_success.jpg"/>
      <hr>
      <% 
         String id = request.getParameter("id");
         String num = request.getParameter("num");
      %>
             您成功購買了<%=num%>件商品編號爲<%=id%>的商品&nbsp;&nbsp;&nbsp;&nbsp;
      <br>
      <br>
      <br>

    </center>
  </body>
</html>
2-13 練習題

MVC模型包含模型層、視圖層和控制器層,在下列組件中扮演控制器角色的是
Servlet

使用MVC模型搭建某網上書店系統設計用戶登陸界面,如果你是設計人員你將在MVC模型結構的( )中實現
視圖層

視圖層關注界面設計。


《JAVA遇見HTML——Servlet篇》視頻地址

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