JSP--慕課網筆記

第1章 JAVA WEB簡介
1-1 什麼是WEB應用程序

JavaWeb簡介

  1. 什麼是Web應用程序
  2. 靜態頁面與動態頁面
  3. 搭建Java Web開發環境
  4. 手工編寫第一個Web應用程序
  5. MyEclipse配置
  6. 使用MyEclipse編寫第一個Web應用程序
  7. 修改Tomcat默認端口

什麼是Web應用程序
Web應用程序是一種可以通過Web訪問的應用程序。Web應用程序的一個最大好處是用戶
很容易訪問應用程序。用戶只需要有瀏覽器即可,不需要在安裝其他軟件。

爲什麼要學習Web應用程序
我們說Web應用程序開發,是目前軟件開發領域的三大方向之一。
JAVAEE方向需求一直是很大的,也是就業比較容易和穩定的。

軟件領域三大方向

  • 桌面應用程序
  • Web應用程序
  • 嵌入式應用程序
1-2 靜態網頁與動態網頁

靜態網頁與動態網頁

  • 靜態網頁
    表現形式:網頁中的內容是固定,不會更新
    所需技術:HTML、CSS
  • 動態網頁
    表現形式:網頁中的內容通過程序動態顯示,自動更新。學習製作動態網頁。
    所需技術:HTML、CSS,數據庫技術,至少一門高級語言(Java、C#、Php),
    Javascript,XML等。主流的動態網頁腳本技術(Jsp/Asp.net/Php)
1-3 練習題

關於靜態網頁與動態網頁下說法錯誤的是( )。
動態網頁上可以顯示動態元素比如:動畫,視頻等,而靜態網頁無法顯示動態元素

動態網頁的內容一般是從數據庫裏面讀取出來的
動態網頁的內容的顯示是通過程序來實現的
學習動態網頁開發至少要掌握一門高級語言

動態網頁的動態指的是能與用戶進行交互,比如登錄時輸入正確的用戶名和密碼,系統會提示登錄成功。

1-4 搭建JAVA WEB開發環境

工慾善其事必先利其器。學會搭建Java Web學習JSP動態網站開發的最基本技能之一。

  • JDK
  • Tomcat
  • MyEclipse

Tomcat服務器簡介

  • Apache Jakarta的開源項目
  • JSP/Servlet容器

Tomcat安裝與配置
安裝Tomcat–>配置環境變量–>測試首頁

CATALINA_HOME:Tomcat根目錄

1-5 Tomcat目錄結構

Tomcat服務器的目錄結構

目錄 說明
/bin 存放各種平臺下用於啓動和停止Tomcat的命令文件
/conf 存放Tomcat服務器的各種配置文件
/lib 存放Tomcat服務器所需的各種JAR文件
/logs 存放Tomcat的日誌文件
/temp Tomcat運行時用於存放臨時文件
webapps 當發佈web應用時,默認會將web應用的文件發佈到此目錄
/work Tomcat把有JSP生成的Servlet放於此目錄下
1-6 手工編寫第一個Java Web程序

手工編寫第一個Web程序

  1. 在WebApps創建項目目錄
  2. 編寫index.jsp
  3. 創建WEB-INF目錄
  4. 測試運行
<html>
<head>
    <title>第一個web應用</title>
</head>
<body>
    第一個web應用
</body>
</html>
1-7 WEB-INF目錄詳解

WEB-INF目錄結構

  1. WEB-INF是Java的WEB應用的安全目錄。所謂安全就是客戶端無法訪問,只有服務端可以訪問的目錄。
  2. web.xml,項目部署文件。
  3. classess文件夾,用於存放*.classess文件。
  4. lib文件夾,用於存放需要的jar包。
1-8 MyEclipse開發Java Web程序

MyEclipse
MyEclipse,是在eclipse基礎上加上自己的插件開發而成的功能
強大的企業級集成開發環境,主要用於Java、Java EE以及移動應用
的開發。MyEclipse的功能非常強大,支持也十分廣泛,尤其是對各種
開源產品的支持相當不錯。

MyEclipse與Eclipse的區別

  • MyEclipse:收費,集成了很多收費的插件。比如:SSH,安卓等。
  • Eclipse:免費開源,不包含任何附加功能的插件。

MyEclipse配置JRE
windows->Preference->Java->Installed JREs

MyEclipse集成Tomcat服務器
windows->Preference->MyEclipse->Server->Tomcat

MyEclipse Web項目目錄結構
項目名稱
java源程序
類庫
項目根目錄
資源文件

1-9 理解Web項目虛擬路徑

理解項目的虛擬路徑
選擇項目->屬性->MyEclipse->Web->查看項目虛擬路徑

1-10 Eclipse開發Java Web程序

Dynamic Web Project

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
hello world !
</body>
</html>
1-11 修改Tomcat服務器默認端口號

修改conf/server.xml

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
1-12 練習題

修改Tomcat服務器默認端口號需要修改的配置文件是( )
server.xml

第2章 JSP基礎語法
2-1 JSP簡介
  1. Jsp簡介
  2. 常用動態網站開發技術
  3. Jsp頁面構成元素
  4. Jsp的生命週期
  5. 階段項目

JSP全名爲Java Server Pages,其根本是一個簡化的Servlet設計,
他實現了在Java當中使用HTML標籤。Jsp是一種動態網頁技術標準也是
JAVAEE的標準。JSP與Servlet一樣,是在服務器端執行的。

2-2 常見動態網站開發技術對比

常見動態網站開發技術對比

  • Jsp:Java平臺,安全性高,適合開發大型的,企業級的Web應用程序
  • Asp.net:.Net平臺,簡單易學。但是安全性及跨平臺性差。
  • Php:簡單,高效,成本低開發週期短,特別適合中小型企業的Web應用開發。
    (LAMP:Linux+Apache+MySql+PHP)
2-3 JSP頁面元素簡介及page指令

JSP頁面組成部分

  • 指令
  • 表達式
  • 小腳本
  • 聲明
  • 註釋
  • 靜態內容

Jsp指令

  • page指令:通常位於jsp頁面的頂端,同一個頁面可以有多個page指令。
  • include指令:將一個外部文件嵌入到JSP文件中,同時解析這個頁面中的JSP語句。
  • taglib指令:使用標籤庫定義新的自定義標籤,在JSP頁面中啓用定製行爲。

page指令語法
<%@ page 屬性1=”屬性值” 屬性2=”屬性值1,屬性值2”…
屬性n=”屬性值n”%>

屬性 描述 默認值
language 指定JSP頁面使用的腳本語言 java
import 通過該屬性來引用腳本語言中使用到的類文件
contentType 用來指定JSP頁面所採用的編碼方式 text/html,ISO-8859-1
2-4 練習題

以下哪個不屬於JSP的三大指令元素( )
import

include
page
taglib

2-5 JSP註釋

在JSP頁面的註釋

  • HTML的註釋: 客戶端可見
  • JSP的註釋:<%– html註釋 –> 客戶端不可見
  • JSP腳本註釋://當行註釋 /**/多行註釋 客戶端不可見
2-6 練習題

以下哪個註釋是客戶端無法查看到的註釋( )
<%– 這裏是註釋–%>

2-7 JSP腳本

在JSP頁面中執行的java代碼
語法:
<% Java代碼 %>

<%

    out.println("大家好!");

%>
2-8 JSP聲明

在JSP頁面中定義變量或者方法。
語法:
<%! Java代碼 %>

<%! 
    String s = "張三";
    int add(int a,int b){
        return a+b;
    }
%>
2-9 JSP表達式

在JSP頁面中執行的表達式。
語法:
<%= 表達式 %> //注意:表達式不以分號結尾

<p>你好,<%= s %></p>
<p>1+1= <%= add(1,1) %></p>
2-10 JSP頁面生命週期
Created with Raphaël 2.1.0用戶發出請求index.jsp是否是第一次請求?JSP引擎把該JSP文件轉換成爲一個Servlet,生成字節碼文件,並執行jspInit()生成的字節碼文件解析執行,jspService()yesno

jspservice()方法被調用來處理客戶端的請求。對每一個請求,JSP引擎創建
一個新的線程來處理該請求。如果有多個客戶端同時請求該JSP文件,則JSP
引擎會創建多個線程。每個客戶端請求對應一個線程。以多線程方式執行可以
大大降低對系統資源的需求,提高系統的併發量及響應時間。但是也要注意多線
程的編程帶來的同步問題,由於該Servlet始終駐留在內存,所以相應是非常快的。

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="java.text.*" %>
<%
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>JSP生命週期</h1>
    <hr>
    <%
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String s = sdf.format(new Date());
    %>
    今天是:<%= s %>
  </body>
</html>
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=utf-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("\r\n");

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

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("    \r\n");
      out.write("    <title>My JSP 'index.jsp' starting page</title>\r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("\t<!--\r\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");
      out.write("\t-->\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("   \t<h1>JSP生命週期</h1>\r\n");
      out.write("   \t<hr>\r\n");
      out.write("   \t");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String s = sdf.format(new Date());

      out.write("\r\n");
      out.write("   \t今天是:");
      out.print( s );
      out.write("\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
2-11 練習題

當用戶第一次請求一個jsp頁面時,首先被執行的方法是( )
構造方法

jspInit()
jspService()
jspDestroy()

第一次請求一個jsp頁面時,首先被執行的方法是構造方法

2-12 階段項目
<%@ 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>
   <%!
        String printMultiTable1()
        {
            String s = "";
            for(int i=1;i<=9;i++){
                for(int j=1;j<=i;j++){
                    s += i + "*" + j + "=" +(i*j)+"&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                s += "<br>";
            }
            return s;
        }

        void printMultiTable2(JspWriter out) throws Exception
        {
            for(int i=1;i<=9;i++){
                for(int j=1;j<=i;j++){
                    out.println( i + "*" + j + "=" +(i*j)+"&nbsp;&nbsp;&nbsp;&nbsp;");
                }
                out.println("<br>");
            }
        }
   %>



    <h1>九九乘法表</h1>
    <hr>
    <%= printMultiTable1() %>
    <br>
    <% printMultiTable2(out); %>
  </body>
</html>
第3章 JSP內置對象(上)
3-1 JSP內置對象簡介
  1. 內置對象簡介
  2. 四種作用域範圍
  3. out
  4. request/response
  5. session
  6. application
  7. 其他內置對象
  8. 項目案例

JSP內置對象是Web容器創建的一組對象,不使用new關鍵字就可以使用的內置對象。

int[] value = {60,70,80};
  for(int i:value){
      out.println(i);
  }

九大內置對象

  • out
  • request
  • response
  • session
  • application
  • Page
  • pageContext
  • exception
  • config
3-2 練習題

以下哪個不屬於jsp九大內置對象( )
pageConfig

exception
page
pageContext

3-3 web程序的請求與響應模式

Web程序的請求響應模式
用戶發送請求(request)
服務器給用戶相應(response)

3-4 out對象

什麼是緩衝區
緩衝區:Buffer,所謂緩衝區就是內存中的一塊區域用來保存臨時數據。

IO輸出最原始的就是一個字節一個字節輸出,就像一粒一粒吃一樣,但效率太差。

剛煮好的米飯一粒一粒吃不知道要猴年馬月。。。把米飯放到碗裏,一碗一碗吃豈不痛快!

out對象是JspWriter類的實例,是向客戶端輸出內容的常用對象。
常用方法如下:

  • void println() 向客戶端打印字符串
  • void clear() 清除緩衝區的內容,如果在flush之後調用會拋出異常
  • void clearBuffer() 清除緩衝區的內容,如果在flush之後調不用會拋出異常
  • void flush() 將緩衝區內容輸出到客戶端
  • int getBufferSize() 返回緩存區以字節數的大小,如不設緩衝區則爲0
  • int getRemaining() 返回緩衝區還剩餘多少可用
  • boolean isAutoFlush() 返回緩衝區滿時,是自動清空還是拋出異常
<%@ 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>out內置對象</h1>
    <% 
       out.println("<h2>靜夜思</h2>");
       out.println("牀前明月光<br>");
       out.println("疑是地上霜<br>");
       out.flush();
       //out.clear();//這裏會拋出異常。
       out.clearBuffer();//這裏不會拋出異常。
       out.println("舉頭望明月<br>");
       out.println("低頭思故鄉<br>");

    %>
        緩衝區大小:<%=out.getBufferSize() %>byte<br>
        緩衝區剩餘大小:<%=out.getRemaining() %>byte<br>
       是否自動清空緩衝區:<%=out.isAutoFlush() %><BR>    
  </body>
</html>
3-5 練習題

執行以下jsp腳本輸出效果是( )

<%
 out.println("牀前明月光");
 out.flush();
 out.clear();
 out.println("疑是地上霜");
%>

在瀏覽器中只輸出牀前明月光

在瀏覽器中輸出“牀前明月光”,控制檯會輸出異常信息。

3-6 get與post提交方式的區別

get與post區別

表單有兩種提交方式:get與post

  • get:以明文的方式通過URL提交數據,數據在URL中可以看到。提交數據
    量最多不超過2KB。安全性較低但效率比post方式高。適合提交數據量不大,
    安全性不高的數據。比如:搜索、查詢等功能。
  • post:將用戶提交的信息封裝在HTML HEADER內。適合提交數據量大,安全
    性高的用戶信息。比如:註冊、修改、上傳等功能。
<%@ 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 'login.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>
    <form action="dologin.jsp" name="loginForm" method="post">
     <table>
       <tr>
         <td>用戶名:</td>
         <td><input type="text" name="username"/></td>
       </tr>
       <tr>
         <td>密碼:</td>
         <td><input type="password" name="password"/></td>
       </tr>
       <tr>
         <td colspan="2"><input  type="submit" value="登錄"></td>
       </tr>
     </table>
    </form>
  </body>
</html>
3-7 request對象(上)

request對象
客戶端的請求信息被封裝在request對象中,通過它才能瞭解到客戶的請求,然後
響應。它是HttpServletRequest類的實例。request對象具有請求域,即完成客戶端
請求之前,該對象一直有效。常用方法如下:

  • String getParameter(String name) 返回name指定參數的參數值
  • String[] getParameterValues(String name) 返回包含參數name的所有值的數組
  • void setAttribute(String,Object) 存儲此請求中的屬性
  • object getAttribute(String name) 返回指定屬性的屬性值
  • String getContentType() 得到請求體的MIME類型
  • String getProtocol() 返回請求用的協議類型及版本號
  • String getServerName() 返回接受請求的服務器主機名
3-8 request對象(下)
<%@ 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>
    <% 
       int number=-1;
       //說明用戶第一次訪問頁面,計數器對象還未創建
       if(application.getAttribute("counter")==null)
       {
           application.setAttribute("counter", 0);
       }
       number = Integer.parseInt(application.getAttribute("counter").toString());
       number++;
       application.setAttribute("counter", number);
    %>
    <!-- <form name="regForm" action="request.jsp" method="post"> -->
    <form name="regForm" action="response.jsp" method="post">
    <table>
      <tr>
        <td>用戶名:</td>
        <td><input type="text" name="username"/></td>
      </tr>
      <tr>
        <td>愛好:</td>
        <td>
           <input type="checkbox" name="favorite" value="read">讀書
           <input type="checkbox" name="favorite" value="music">音樂
           <input type="checkbox" name="favorite" value="movie">電影
           <input type="checkbox" name="favorite" value="internet">上網
        </td>
      </tr>
      <tr>
         <td colspan="2"><input type="submit" value="提交"/></td>
      </tr>
    </table>
    </form>
    <br>
    <br>
    <a href="request.jsp?username=李四">測試URL傳參數</a>

    <br>
    <br>
    <center>
             您是第<%=number %>位訪問本頁面的用戶。
    </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 '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>request內置對象</h1>
    <% 
       request.setCharacterEncoding("utf-8"); //解決中文亂碼問題,無法解決URL傳遞中文出現的亂碼問題。
       request.setAttribute("password", "123456");

    %>
        用戶名:<%=request.getParameter("username") %><br>   
        愛好 :<% 
           if(request.getParameterValues("favorite")!=null)
           {
               String[] favorites = request.getParameterValues("favorite");
               for(int i=0;i<favorites.length;i++)
               {
                  out.println(favorites[i]+"&nbsp;&nbsp;");
               }
            }
        %> <br>
         密碼:<%=request.getAttribute("password") %><br> 
         請求體的MIME類型:<%=request.getContentType() %><br>
         協議類型及版本號:  <%=request.getProtocol() %><br>
         服務器主機名 :<%=request.getServerName() %><br>
         服務器端口號:<%=request.getServerPort() %><BR>
         請求文件的長度 :<%=request.getContentLength() %><BR>
         請求客戶端的IP地址:<%=request.getRemoteAddr() %><BR>
         請求的真實路徑:<%=request.getRealPath("request.jsp") %><br>
         請求的上下文路徑:<%=request.getContextPath() %><BR>         



  </body>
</html>
3-9 練習題

在用戶註冊表單中,用戶的愛好信息用複選框表示,包括讀書、音樂、電影和上網四項。如果已經選中讀書和電影兩項,此時要獲取用戶的愛好信息,使用request對象的哪個方法實現( )
request.getParameterValues(“favorite”);

3-10 response對象

response對象
response對象包含了響應客戶請求的有關信息,但在JSP中很少直接用到它。它是
HttpServetResponse類的實例。response對象具有頁面作用域,即訪問一個頁面時
該頁面內的response對象只能對這次訪問有效,其它頁面的response對象對當前頁面無效。
常用方法如下:

  • String getCharacterEncoding() 返回響應是用的何種字符編碼
  • void setContentType(String type) 設置響應的MIME類型
  • PrintWriter getWriter() 返回可以向客戶端輸出字符的一個對象(注意比較:
    PrintWriter與內置對象out對象的區別)
  • sendRedirect(String location) 重新定向客戶端的請求
<%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%>
<%
    response.setContentType("text/html;charset=utf-8"); //設置響應的MIMI類型

    out.println("<h1>response內置對象</h1>");
    out.println("<hr>");
    //out.flush();

    PrintWriter outer = response.getWriter(); //獲得輸出流對象
    outer.println("大家好,我是response對象生成的輸出流outer對象");
    //response.sendRedirect("reg.jsp");//請求重定向
%>
3-11 請求重定向與請求轉發的區別

請求轉發與請求重定向

  • 請求重定向:客戶端行爲,response.sendRedirect(),從本質上講等同於兩次請求,
    前一次的請求對象不會保存,地址欄的URL地址會改變。
  • 請求轉發:服務器行爲,request.getRequestDispatcher().forward(req,resp)是
    一次請求,轉發後請求對象會保存,地址欄的URL地址不會改變。

假設你去辦理某個護照
重定向:你先去了A局,A局的人說:“這個事不歸我管,去B局”,然後,你就從A局
退了出來,自己乘車去了B局。
轉發:你去了A局,A局看了以後,知道這個事情其實應該B局來管,但是他沒有把
你退回來,而是讓你坐一會兒,自己到後面辦公室聯繫了B的人,讓他們辦好後,送了
過來。

<%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%>
<%
    response.setContentType("text/html;charset=utf-8"); //設置響應的MIMI類型

    out.println("<h1>response內置對象</h1>");
    out.println("<hr>");
    //out.flush();

    PrintWriter outer = response.getWriter(); //獲得輸出流對象
    outer.println("大家好,我是response對象生成的輸出流outer對象");
    //response.sendRedirect("reg.jsp");//請求重定向
    //請求重定向
    //response.sendRedirect("request.jsp");
    //請求轉發
    request.getRequestDispatcher("request.jsp").forward(request, response);
%>
3-12 練習題

關於請求重定向與請求轉發的區別以下說法不正確的是( )
請求重定向是服務器端行爲而請求轉發是客戶端行爲

請求重定向相當於兩次請求,地址欄地址會發生變化
重定向是response對象的方法而請求轉發是request對象的方法
請求重定向不會保存原有request對象而請求轉發會保存原有request對象

第4章 JSP內置對象(下)
4-1 什麼是session

什麼是session

  • session表示客戶端與服務器的一次會話
  • Web中的session指的是用戶在瀏覽某個網站時,從進入網站到瀏覽器關閉所經過的這段
    時間,也就是用戶瀏覽這個網站所花的時間
  • 從上述定義中可以看到,session實際上是一個特定的時間概念

購物流程說明
用戶登錄-》放入購物車-》訂單填寫-》提交訂單-》確認訂單-》立即付款

整個購物過程屬於一次會話

在服務器的內存中保存着不同用戶的session。

4-2 session對象

session對象

  • session對象是一個JSP內置對象。
  • session對象在第一個JSP頁面被加載時自動創建,完成會話期管理。
  • 從一個客戶打開瀏覽器並連接到服務器開始,到客戶關閉瀏覽器離開這個服務器結束被
    稱爲一個會話。
  • 當一個客戶訪問一個服務器時,可能會在服務器之間的幾個頁面切換,服務器應該通過
    某種辦法知道這是一個客戶,就需要session對象。
  • session對象是HttpSession類的實例。

session對象常用方法如下:

long getCreationTime():返回SESSION創建時間
public String getId():返回SESSION創建時JSP引擎爲它設置的唯一ID號
public Object setAttribute(String name,Object value):使用指定名稱將對象綁定到此會話
public Object getAttribute(String name):返回與此會話中的指定名稱綁定在一起的對象,如果沒有對象綁定在該名稱下,則返回null
String[] getValueNames():返回一個包含SESSION中所有可用屬性的數組
int getMaxInactiveInterval():返回兩次請求間隔多長時間此SESSION被取消(單位秒)

<%@ 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 '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>session內置對象</h1>
    <hr>
    <% 
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
      Date d = new Date(session.getCreationTime());
      session.setAttribute("username", "admin"); 
      session.setAttribute("password", "123456");
      session.setAttribute("age", 20);

      //設置當前session最大生成期限單位是秒
      //session.setMaxInactiveInterval(10);//10秒鐘

    %>
    Session創建時間:<%=sdf.format(d)%><br>    
    Session的ID編號:<%=session.getId()%><BR>
         從Session中獲取用戶名:<%=session.getAttribute("username") %><br>

    <a href="session_page2.jsp" target="_blank">跳轉到Session_page2.jsp</a>     

  </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 '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>session內置對象</h1>
    <hr>
    <% 
      //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
      //Date d = new Date(session.getCreationTime());
      //session.setAttribute("username", "admin"); 
    %>

    Session的ID編號:<%=session.getId()%><BR>
         從Session中獲取用戶名:<%=session.getAttribute("username") %><br>
    Session中保存的屬性有:<% 
                     String[] names =session.getValueNames();
                     for(int i=0;i<names.length;i++)
                     {
                        out.println(names[i]+"&nbsp;&nbsp;");
                     }

    %> <br>    
  </body>
</html>
4-3 練習題

下面有關會話(session)描述不正確的是( )。
會話保存在客戶端的內存裏

會話是用來保存用戶狀態的一種機制
會話保存在服務器的內存裏
每一個會話對應一個唯一的sessionId

4-4 session的生命週期

session的生命週期

  • 創建
    當客戶端第一次訪問某個jsp或者Servlet時候,服務器將會爲當前會話創建一個
    SessionId,每次客戶端向服務器發送請求時,都會將此SessionId攜帶過去,服務端
    會對此SessionId進行校驗。
  • 活動
    • 當某次會話當中通過超鏈接打開新的頁面屬於同一會話。
    • 只要當前會話頁面沒有完全關閉,重新打開新的瀏覽器窗口訪問統一項目
      資源時屬於同一會話。
    • 除非本次會話的所有頁面都關閉後再重新訪問某個Jsp或者Servlet將會創建
      新的會話。
      注意事項:注意原有會話還存在,只是這個舊的SessionId仍然存在於服務端,
      只是在有沒有客戶端會攜帶它交與服務端進行校驗。
  • 銷燬
    • 調用了session.invalidate()方法
    • Session過期(超時)
    • 服務器重新啓動
<%@ 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 '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>session內置對象</h1>
    <hr>
    <% 
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
      Date d = new Date(session.getCreationTime());
      session.setAttribute("username", "admin"); 
      session.setAttribute("password", "123456");
      session.setAttribute("age", 20);

      //設置當前session最大生成期限單位是秒
      //session.setMaxInactiveInterval(10);//10秒鐘
      //session.invalidate();//銷燬當前會話。
    %>

    Session創建時間:<%=sdf.format(d)%><br>    
    Session的ID編號:<%=session.getId()%><BR>
         從Session中獲取用戶名:<%=session.getAttribute("username") %><br>
    <% 
       //session.invalidate();//銷燬當前會話
    %>
    <a href="session_page2.jsp" target="_blank">跳轉到Session_page2.jsp</a>     

  </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 '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>session內置對象</h1>
    <hr>
    <% 
      //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
      //Date d = new Date(session.getCreationTime());
      //session.setAttribute("username", "admin"); 
    %>

    Session的ID編號:<%=session.getId()%><BR>
         從Session中獲取用戶名:<%=session.getAttribute("username") %><br>
    Session中保存的屬性有:<% 
                     String[] names =session.getValueNames();
                     for(int i=0;i<names.length;i++)
                     {
                        out.println(names[i]+"&nbsp;&nbsp;");
                     }

    %> <br>    
  </body>
</html>
<?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>
  <!-- 設置會話一分鐘後過期 -->
  <session-config>
    <session-timeout>1</session-timeout>
  </session-config>
</web-app>
4-5 練習題

有關session生命週期下列說法不正確的是( )。
每次重新打開新的瀏覽器窗口相當於開啓了一次新的會話

session的生命週期分爲創建、活動、銷燬三個階段
調用session.invalidate()方法可以銷燬當前會話
重啓web服務器會銷燬所有的會話

4-6 application對象
  • application對象實現了用戶數據的共享,可存放全局變量。
  • application開始於服務器的啓動,終止與服務器的關閉
  • 在用戶的前後連接或不同用戶的連接中,可以對application對象的同一屬性進行操作。
  • 在任何地方對application對象的操作,都會影響到其他用戶的訪問。
  • 服務器的啓動和關閉覺得了application對象的生命。
  • application對象是ServletContext類的實例。

常用方法如下:

  • public void setAttribute(String name,Object value) 使用指定名稱將對象綁定到此會話。
  • public Object getAttribute(String name) 返回與此會話中指定名稱綁定在一起的對象,如果沒有對象綁定在該名稱下,則返回null。
  • Enumeration getAttributeNames() 返回所有可用屬性的枚舉。
  • String getServerInfo() 返回JSP(SERVLET)引擎名及版本號。
<%@ 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>application內置對象</h1>
    <% 
       application.setAttribute("city", "北京");
       application.setAttribute("postcode", "10000");
       application.setAttribute("email", "[email protected]");

    %>
         所在城市是:<%=application.getAttribute("city") %><br>
    application中的屬性有:<% 
         Enumeration attributes = application.getAttributeNames();
         while(attributes.hasMoreElements())
         {
            out.println(attributes.nextElement()+"&nbsp;&nbsp;");
         }
    %><br>
    JSP(SERVLET)引擎名及版本號:<%=application.getServerInfo() %><br>              

  </body>
</html>
4-7 練習題

使用application 實現計數器效果,在application中保存整型變量num,需要調用application對象的setAttribute方法,以下選項正確的是( )。
setAttribute(”counter”,num);

4-8 page對象

page對象是指向當前JSP頁面本身,有點像類中的this指針,它是java.lang.Object類的實例。
常用方法如下:

  • class getClass() 返回此Object的類
  • int hashCode() 返回此Object的hash碼
  • boolean equals(Object obj) 判斷此Object是否與指針的Object對象相等
  • void copy(Object obj) 把此Object拷貝到指定的Object對象中
  • Object clone() 克隆此Object對象
  • String toString() 把此Object對象轉換成String類的對象
  • void notify() 喚醒一個等待的線程
  • void notifyAll() 喚醒所有等待的線程
  • void wait(int timeout) 使一個線程處於等待直到timeout結束或被喚醒
  • void wait() 使一個線程處於等待直到被喚醒
<%@ 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>page內置對象</h1>

         當前page頁面對象的字符串描述:<%=page.toString() %><br> 


  </body>
</html>
4-9 pageContext對象和config對象

pageContext對象

  • pageContext對象提供了對JSP頁面所有的對象及名字空間的訪問
  • pageContext對象可以訪問到本頁所在的session,也可以取本頁面所在的application的某一值
  • pageContext對象相當於頁面中所有功能集大成者
  • pageContext對象本類名也叫pageContext

常用方法:

  • JspWriter getOut() 返回當前客戶端響應被使用的JspWriter流(out)。
  • HttpSession getSession() 返回當前頁面中HttpSession對象(session)。
  • Object getPage() 返回當前頁面Object對象(page)。
  • ServletRequest getRequest() 返回當前頁面的ServletRequest對象(request)。
  • ServletResponse getResponse() 返回當前頁面的ServletResponse對象(response)。
  • void setAttribute(String name,Object attribute) 設置屬性及屬性值
  • Object getAttribute(String name,int scope) 在指定範圍內取屬性的值
  • int getAttributeScope(String name) 返回某屬性的作用範圍
  • void forward(String relativeUrlPath) 使當前頁面重導到另一頁面
  • void include(String relativeUrlPath) 在當前位置包含另一文件
<%@ 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>pageContext內置對象</h1>
    <hr>    
        用戶名是:<%=pageContext.getSession().getAttribute("username") %><br>      
    <% 
       //跳轉到註冊頁面
       //pageContext.forward("reg.jsp");
       pageContext.include("include.jsp");
    %>                
  </body>
</html>

Config對象
config對象實在一個Servlet初始化時,JSP引擎向它傳遞信息用的,此信息包括
Servlet初始化時要用到的參數(通過屬性名和屬性值構成)以及服務器的有關信息
(通過傳遞一個ServletContext對象),常用方法如下:

  • ServletContext getServletContext() 返回含有服務器相關信息的ServletContext對象。
  • String getInitParamter(name) 返回初始化參數的值。
  • Enumeration getInitParamterNames() 返回Servlet初始化所需所有參數的枚舉。
4-10 exception對象

exception對象是一個異常對象,當一個頁面在運行過程中發生了異常,就產生
這個對象。如果一個JSP頁面要應用此對象,就必須把isErrorPage設置爲true,
否則無法編譯。他實際上是java.lang.Throwable的對象,常用方法如下:

  • String getMessage() 返回描述異常的消息。
  • String toString() 返回關於異常的簡短描述消息。
  • void printStackTrace() 顯示異常及其棧軌跡
  • Throwable FillInStackTrace() 重寫異常的執行棧軌跡
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" errorPage="exception.jsp"%>
<%
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>

    <% 
      System.out.println(100/0); //拋出運行時異常,算數異常
    %>
  </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" isErrorPage="true" %>
<%
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>exception內置對象</h1>
    <hr>

        異常的消息是:<%=exception.getMessage()%><BR>
        異常的字符串描述:<%=exception.toString()%><br>
  </body>
</html>
4-11 階段案例——實現用戶登錄

實現用戶登錄小例子
用戶名admin,密碼admin,登錄成功使服務器內部轉發到login_success.jsp頁面,
並且提示登陸成功的用戶名。如果登陸失敗則重定向到login_failure.jsp頁面。

<%@ 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+"/";
  String username ="";
  String password ="";
  request.setCharacterEncoding("utf-8");//防止中文亂碼

  username = request.getParameter("username");
  password = request.getParameter("password");

  //如果用戶和密碼都等於admin,則登錄成功
  if("admin".equals(username)&&"admin".equals(password))
  {
     session.setAttribute("loginUser", username);
     request.getRequestDispatcher("login_success.jsp").forward(request, response);

  }
  else
  {
     response.sendRedirect("login_failure.jsp");
  }
%>
<%@ 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="dologin.jsp" 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>
第5章 JavaBeans
5-1 本章簡介
  • Javabean簡介
  • Javabean設計原則
  • Jsp中如何使用Javabean
  • Javabean的四個作用域範圍
  • Model1簡介
  • 項目案例
5-2 JavaBean簡介及設計原則

Javabean簡介
Javabeans就是符合某種特定規範的Java類。使用Javabeans的好處是
解決代碼重複編寫,減少代碼冗餘,功能區分明確,提高了代碼的維護性。

Javabean設計原則

  • 公有類
  • 無參公有構造方法
  • 私有屬性
  • getter和setter方法

public class Students {

    private String name;
    private int age;

    public Students(){}

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


}
5-3 什麼是JSP動作元素

JSP動作元素(action elements),動作元素爲請求處理階段提供信息。動作
元素遵循XML元素的語法,有一個包含元素名的開始標籤,可以有屬性、可選
內容、與開始標籤匹配的結束標籤。

  • 第一類是與存取Javabean有關的,包括:
  • 第二類是從JSP1.2就開始有的基本元素,包括6個動作元素
  • 第三類是JSP2.0新增加的元素,主要與JSP Document有關,包括六個元素
  • 第四類是JSP2.0新增加的動作元素,主要用來動態生成XML元素標籤的值,包括3個動作
  • 第五類是JSP2.0新增的動作元素,主要是用在Tag File中,有2個元素
5-4 使用普通方式創建JavaBean
  • 像使用普通java類一樣,創建javabean實例。
/*
 * 用戶類
 * */
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;
    }


}
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="com.po.Users" %>
<%
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>
    <% 
       Users user = new Users();
       user.setUsername("admin"); //設置用戶名
       user.setPassword("123456");//設置密碼
    %>
    <h1>使用普通方式創建javabean的實例</h1>
    <hr>
       用戶名:<%=user.getUsername() %><br>
       密碼:<%=user.getPassword() %><br>
  </body>
</html>
5-5 useBean動作元素
  • 在Jsp頁面通常使用jsp動作標籤來使用Javabean。
    • useBeans動作
    • setProperty動作
    • getProperty動作


作用:在Jsp頁面中實例化或者在指定範圍內使用javabean:

<%@ 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>
    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
    <h1>使用useBean動作創建javabean的實例</h1>
    <hr>
       用戶名:<%=myUsers.getUsername() %><br>
       密碼:<%=myUsers.getPassword() %><br>
  </body>
</html>
5-6 setProperty

作用:給已經實例化的Javabean對象的屬性賦值,一共有四種形式。

(跟表單關聯)
(跟表單關聯)
(手工設置)
(跟request參數關聯)

<%@ 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 'dologin.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>
    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
    <h1>setProperty動作元素</h1>
    <hr>
   <!--根據表單自動匹配所有的屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="*"/>  
   --%>
   <!--根據表單匹配所有部分的屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="username"/>  
   --%>
   <!--根表單無關,通過手工賦值給屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="username" value="lisi"/>
   <jsp:setProperty name="myUsers" property="password" value="888888"/>
   --%>
   <!--通過URL傳參數給屬性賦值 -->
   <jsp:setProperty name="myUsers" property="username"/>
   <jsp:setProperty name="myUsers" property="password" param="mypass"/>
   <!-- 使用getProperty方式來獲取用戶名和密碼 -->
      用戶名:<jsp:getProperty name="myUsers" property="username"/> <br>
      密碼:<jsp:getProperty name="myUsers" property="password"/><br>
   <br>
  </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 'login.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>
    <form name="loginForm" action="dologin.jsp?mypass=999999" method="post">
      <table>
        <tr>
          <td>用戶名:</td>
          <td><input type="text" name="username" value=""/></td>
        </tr>
        <tr>
          <td>密碼:</td>
          <td><input type="password" name="password" value=""/></td>
        </tr>
        <tr>
          <td colspan="2" align="center"><input type="submit" value="登錄"/></td>

        </tr>
      </table>
    </form>
  </body>
</html>
5-7 getProperty

作用:獲取指定Javabean對象的屬性值。

<%@ 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 'dologin.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>
    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
    <h1>setProperty動作元素</h1>
    <hr>
   <!--根據表單自動匹配所有的屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="*"/>  
   --%>
   <!--根據表單匹配所有部分的屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="username"/>  
   --%>
   <!--根表單無關,通過手工賦值給屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="username" value="lisi"/>
   <jsp:setProperty name="myUsers" property="password" value="888888"/>
   --%>
   <!--通過URL傳參數給屬性賦值 -->
   <jsp:setProperty name="myUsers" property="username"/>
   <jsp:setProperty name="myUsers" property="password" param="mypass"/>
   <!-- 使用傳統的表達式方式來獲取用戶名和密碼 -->
   <%--     
       用戶名:<%=myUsers.getUsername() %><br>
       密碼:<%=myUsers.getPassword() %><br> 
   --%>
   <!-- 使用getProperty方式來獲取用戶名和密碼 -->
      用戶名:<jsp:getProperty name="myUsers" property="username"/> <br>
      密碼:<jsp:getProperty name="myUsers" property="password"/><br>
  </body>
</html>
5-8 JavaBean四個作用域範圍

Javabean的四個作用域範圍

說明:使用useBeans的scope屬性可以用來指定javabean的作用範圍

  • page //僅在當前頁面有效
  • request //可以通過HttpRequest.getAttribute()方法取得JavaBean對象
  • session //可以通過HttpSession.getAttribute()方法獲得JavaBean對象
  • application //可以通過application.getAttribute方法獲得JavaBean對象
<%@ 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 'login.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>
    <form name="loginForm" action="dologin.jsp?mypass=999999" method="post">
      <table>
        <tr>
          <td>用戶名:</td>
          <td><input type="text" name="username" value=""/></td>
        </tr>
        <tr>
          <td>密碼:</td>
          <td><input type="password" name="password" value=""/></td>
        </tr>
        <tr>
          <td colspan="2" align="center"><input type="submit" value="登錄"/></td>

        </tr>
      </table>
    </form>
  </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 'dologin.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>
    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
    <h1>setProperty動作元素</h1>
    <hr>
   <!--根據表單自動匹配所有的屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="*"/>  
   --%>
   <!--根據表單匹配所有部分的屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="username"/>  
   --%>
   <!--根表單無關,通過手工賦值給屬性 -->
   <%-- 
   <jsp:setProperty name="myUsers" property="username" value="lisi"/>
   <jsp:setProperty name="myUsers" property="password" value="888888"/>
   --%>
   <!--通過URL傳參數給屬性賦值 -->
   <jsp:setProperty name="myUsers" property="username"/>
   <jsp:setProperty name="myUsers" property="password" param="mypass"/>
   <!-- 使用傳統的表達式方式來獲取用戶名和密碼 -->
   <%--     
       用戶名:<%=myUsers.getUsername() %><br>
       密碼:<%=myUsers.getPassword() %><br> 
   --%>
   <!-- 使用getProperty方式來獲取用戶名和密碼 -->
      用戶名:<jsp:getProperty name="myUsers" property="username"/> <br>
      密碼:<jsp:getProperty name="myUsers" property="password"/><br>
   <br>
   <br>
      <a href="testScope.jsp">測試javabean的四個作用域範圍</a>
      <% 
         request.getRequestDispatcher("testScope.jsp").forward(request, response);
      %>
  </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="com.po.Users" %>
<%
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 'testScope.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>Javabean的四個作用域範圍</h1>
    <hr>
    <jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
       用戶名:<jsp:getProperty name="myUsers" property="username"/><br>
       密碼:<jsp:getProperty name="myUsers" property="password"/><br>
    <!-- 使用內置對象獲取用戶名和密碼 -->
    <hr>
   <%-- 
       用戶名:<%=((Users)application.getAttribute("myUsers")).getUsername()%><br>
       密碼:<%=((Users)application.getAttribute("myUsers")).getPassword() %><br>
   --%>
   <%-- 
       用戶名:<%=((Users)session.getAttribute("myUsers")).getUsername()%><br>
       密碼:<%=((Users)session.getAttribute("myUsers")).getPassword() %><br>
   --%>
   <%-- 
       用戶名:<%=((Users)request.getAttribute("myUsers")).getUsername()%><br>
       密碼:<%=((Users)request.getAttribute("myUsers")).getPassword() %><br>
   --%>
   <% 
       String username = "";
       String password = "";
       if(pageContext.getAttribute("myUsers")!=null )
       {
          username = ((Users)pageContext.getAttribute("myUsers")).getUsername();
          password = ((Users)pageContext.getAttribute("myUsers")).getPassword();
       }

   %>

       用戶名:<%=username%><br>
       密碼:<%=password%><br>



  </body>
</html>
5-9 練習題

在Java Web 應用程序的jsp頁面中有如下一行代碼: 要使user對象可以作用於整個Web應用,下劃線中應填入( )。
application

5-10 Model1簡介

Model 1模型出現前,整個Web應用的情況:幾乎全部由JSP頁面
組成,JSP頁面接受處理客戶端請求,對請求處理後直接做出響應。

弊端:在界面層充斥着大量業務邏輯的代碼和數據訪問層的代碼,
Web程序的可擴展性和可維護性非常差。

javabean的出項可以使jsp頁面中使用Javabean封裝的
數據或者調用Javabean的業務邏輯代碼,這樣大大提升
了程序的可維護性。

Created with Raphaël 2.1.0瀏覽器瀏覽器jspjspjavabeanjavabean數據庫數據庫請求響應jsp+javabean -> Web服務器
5-11 練習題

以下關於Javabean說法不正確的是( )。
Javabean只能封裝數據不能封裝業務邏輯。

Javabean就是符合某種設計規範的java類。
在Model1中,由Jsp頁面去調用Javabean。
Javabean一般把屬性設計爲私有,使用setter和getter訪問屬性。

Javabean既可以封裝數據同時也可以封裝業務邏輯。

5-12 階段項目

使用jsp+javabean完成用戶登錄功能

//用戶的業務邏輯類
public class UsersDAO {

    //用戶登錄方法
    public boolean usersLogin(Users u)
    {
        if("admin".equals(u.getUsername())&&"admin".equals(u.getPassword()))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
//用戶類
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;
    }


}
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>

<% 
  request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="loginUser" class="com.po.Users" scope="page"/>
<jsp:useBean id="userDAO" class="com.dao.UsersDAO" scope="page"/>
<jsp:setProperty property="*" name="loginUser"/>

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

  //如果用戶和密碼都等於admin,則登錄成功
  if(userDAO.usersLogin(loginUser))
  {
     session.setAttribute("loginUser", loginUser.getUsername());
     request.getRequestDispatcher("login_success.jsp").forward(request, response);

  }
  else
  {
     response.sendRedirect("login_failure.jsp");
  }
%>
<%@ 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="dologin.jsp" 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>
<%@ 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">
             登錄失敗!請檢查用戶或者密碼!<br>
          <a href="login.jsp">返回登錄</a>   
        </div>
    </div>
    </body>
</html>
第6章 JSP狀態管理
6-1 http協議的無狀態性
  • http協議無狀態性
  • 保存用戶狀態的兩大機制
  • Cookie簡介
  • Cookie的創建與使用
  • Session與Cookie對比

http協議的無狀態性
無狀態是指,當瀏覽器發送請求給服務器的時候,服務器響應客戶端請求。
但是當同一個瀏覽器再一次發送請求給服務器的時候,服務器並不知道它
就是剛纔那個瀏覽器。
簡單的說,就是服務器不會去記得你,所以就是無狀態協議。

6-2 Cookie概述

保存用戶的狀態的兩大機制

  • Session
  • Cookie

什麼是Cookie?

Cookie:中文名稱爲“小甜餅”,是Web服務器保存在客戶端的一些列文本信息。

  • 典型應用一:判定註冊用戶是否已經登陸網站。
  • 典型應用二:“購物車”的處理。

生活中Cookie的應用

  • 系統會自動記錄已經瀏覽過的視屏
  • 記住用戶名和密碼實現自動登陸

Cookie的作用

  • 對特定的對象的追蹤
  • 保存用戶網頁瀏覽記錄與習慣
  • 簡化登陸

安全風險:容易泄露用戶信息

6-3 JSP頁面中創建與使用Cookie

Jsp中創建與使用Cookie

  • 創建Cookie對象
    Cookie newCookie = new Cookie(String key,Object value);
  • 寫入Cookie對象
    response.addCookie(newCookie);
  • 讀取Cookie對象
    Cookiep[] cookies = request.getCookies();

常用方法

方法名稱 說明
void setMaxAge(int expiry) 設置cookie的有效期,以秒爲單位
void setValue(String value) 在cookie創建後,對cookie進行賦值
String getName() 獲取cookie的名稱
String getValue() 獲取cookie的值
int getMaxAge() 獲取cookie的有效時間,以秒爲單位
6-4 案例:Cookie在登錄中的應用

實現記憶用戶名和密碼功能

<%@ page language="java" import="java.util.*,java.net.*" 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>
    <% 
      request.setCharacterEncoding("utf-8");
      String username="";
      String password = "";
      Cookie[] cookies = request.getCookies();
      if(cookies!=null&&cookies.length>0)
      {
           for(Cookie c:cookies)
           {
              if(c.getName().equals("username"))
              {
                   username =  URLDecoder.decode(c.getValue(),"utf-8");
              }
              if(c.getName().equals("password"))
              {
                   password =  URLDecoder.decode(c.getValue(),"utf-8");
              }
           }
      }
    %>
    <form name="loginForm" action="dologin.jsp" method="post">
       <table>
         <tr>
           <td>用戶名:</td>
           <td><input type="text" name="username" value="<%=username %>"/></td>
         </tr>
         <tr>
           <td>密碼:</td>
           <td><input type="password" name="password" value="<%=password %>" /></td>
         </tr>
         <tr>
           <td colspan="2"><input type="checkbox" name="isUseCookie" checked="checked"/>十天內記住我的登錄狀態</td>
         </tr>
         <tr>
           <td colspan="2" align="center"><input type="submit" value="登錄"/><input type="reset" value="取消"/></td>
         </tr>
       </table>
    </form>
  </body>
</html>
<%@ page language="java" import="java.util.*,java.net.*" 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 'dologin.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>
    <br>
    <br>
    <br>
    <% 
       request.setCharacterEncoding("utf-8");
       //首先判斷用戶是否選擇了記住登錄狀態
       String[] isUseCookies = request.getParameterValues("isUseCookie");
       if(isUseCookies!=null&&isUseCookies.length>0)
       {
          //把用戶名和密碼保存在Cookie對象裏面
          String username = URLEncoder.encode(request.getParameter("username"),"utf-8");
          //使用URLEncoder解決無法在Cookie當中保存中文字符串問題
          String password = URLEncoder.encode(request.getParameter("password"),"utf-8");

          Cookie usernameCookie = new Cookie("username",username);
          Cookie passwordCookie = new Cookie("password",password);
          usernameCookie.setMaxAge(864000);
          passwordCookie.setMaxAge(864000);//設置最大生存期限爲10response.addCookie(usernameCookie);
          response.addCookie(passwordCookie);
       }
       else
       {
          Cookie[] cookies = request.getCookies();
          if(cookies!=null&&cookies.length>0)
          {
             for(Cookie c:cookies)
             {
                if(c.getName().equals("username")||c.getName().equals("password"))
                {
                    c.setMaxAge(0); //設置Cookie失效
                    response.addCookie(c); //重新保存。
                }
             }
          }
       }
    %>
    <a href="users.jsp" target="_blank">查看用戶信息</a>

  </body>
</html>
<%@ page language="java" import="java.util.*,java.net.*" 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 'users.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>
    <% 
      request.setCharacterEncoding("utf-8");
      String username="";
      String password = "";
      Cookie[] cookies = request.getCookies();
      if(cookies!=null&&cookies.length>0)
      {
           for(Cookie c:cookies)
           {
              if(c.getName().equals("username"))
              {
                   username = URLDecoder.decode(c.getValue(),"utf-8");
              }
              if(c.getName().equals("password"))
              {
                   password = URLDecoder.decode(c.getValue(),"utf-8");
              }
           }
      }
    %>
    <BR>
    <BR>
    <BR>
         用戶名:<%=username %><br>
         密碼:<%=password %><br>
  </body>
</html>
6-5 Session與Cookie的對比
session cookie
在服務端保存用戶信息 在客戶端保存用戶信息
session中保存的是Object類型 cookie中保存的是String類型
隨會話的結束而將其存儲的數據銷燬 cookie可以長期保存在客戶端
保存重要信息 保存不重要信息
6-6 練習題

下面關於Cookie與Session的對比描述不正確的是()
Cookie與Session都可以保存任意大小的對象類型

Cookie是客戶端保存用戶狀態的機制
Session是服務器端保存用戶狀態的機制
Cookie與Session都可以設置生存期限

Cookie中對保存對象的大小是有限制的

6-7 練習題

如果想要設置當前Cookie的生存期限爲24小時,以下代碼正確的是
setMaxAge(86400);

第7章 JSP指令與動作元素
7-1 include指令
  • include指令
  • include動作
  • include指令與include動作的區別
  • 動作
  • 動作
  • 動作

include指令
語法:
<%@ include file=”URL” %>

<%@ 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 'Include_Command.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>Include指令</h1>
    <hr>
    <%@ include file="date.jsp"%>
  </body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="java.text.*" %>
<%
   Date d = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
   String s = sdf.format(d);
   out.println(s);
%>
7-2 include動作

include動作

語法:

<%@ 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 'Include_Command.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>Include動作</h1>
    <hr>
    <jsp:include page="date.jsp" flush="false"/>
  </body>
</html>
7-3 include指令與include動作的區別
include指令 jsp:include動作
語法格式 <%@include file=”..” %>
發生作用的時間 頁面轉換期間
包含的內容 文件的實際內容
轉換成的Servlet 主頁面和包含頁面轉換成一個Servlet
編譯時間 較慢–資源必須被解析
執行時間 稍快
public final class include_005fcommand_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  static {
    _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1);
    _jspx_dependants.put("/date.jsp", Long.valueOf(1504776944846L));
  }

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=utf-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\r');
      out.write('\n');

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

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("    \r\n");
      out.write("    <title>My JSP 'Include_Command.jsp' starting page</title>\r\n");
      out.write("    \r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("\t<!--\r\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");
      out.write("\t-->\r\n");
      out.write("\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("    <h1>Include指令</h1>\r\n");
      out.write("    <hr>\r\n");
      out.write("    ");
      out.write("\r\n");
      out.write("\r\n");

   Date d = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
   String s = sdf.format(d);
   out.println(s);

      out.write('\r');
      out.write('\n');
      out.write("\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
public final class include_005faction_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=utf-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\r');
      out.write('\n');

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

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("    \r\n");
      out.write("    <title>My JSP 'Include_Command.jsp' starting page</title>\r\n");
      out.write("    \r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("\t<!--\r\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");
      out.write("\t-->\r\n");
      out.write("\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("    <h1>Include動作</h1>\r\n");
      out.write("    <hr>\r\n");
      out.write("    ");
      org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "date.jsp", out, false);
      out.write("\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
public final class date_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=utf-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("\r\n");

   Date d = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
   String s = sdf.format(d);
   out.println(s);

      out.write('\r');
      out.write('\n');
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
7-4 forward動作

forward動作

語法:

等同於:
request.getRequestDispatcher(“/url”).forward(request,response);

7-5 param動作

param動作

語法:

常常與一起使用,作爲其的子標籤。

<%@ 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 'login.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>
    <form name="loginForm" action="dologin.jsp" method="post">
      <table>
        <tr>
          <td>用戶名:</td>
          <td><input type="text" name="username"/></td>
        </tr>
        <tr>
          <td>密碼:</td>
          <td><input type="password" name="password"/></td>
        </tr>
        <tr>
          <td colspan="2"><input type="submit" value="登錄"/></td>
        </tr>
      </table>
    </form>
  </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 'dologin.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>
    <jsp:forward page="user.jsp">
      <jsp:param value="[email protected]" name="email"/>
      <jsp:param value="888888" name="password"/>
    </jsp:forward>
  </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 'user.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>
    <% 
       request.setCharacterEncoding("utf-8");
       String username = "";
       String password = "";
       String email = "";
       if(request.getParameter("username")!=null)
       {
          username = request.getParameter("username");
       }
       if(request.getParameter("password")!=null)
       {
          password = request.getParameter("password");
       }
       if(request.getParameter("email")!=null)
       {
          email = request.getParameter("email");
       }

    %>
        用戶名:<%=username %><br>
        密碼:<%=password %><br>
        電子郵箱:<%=email %><br>
  </body>
</html>
7-6 練習題

下面關於include指令與include動作的對比描述不正確的是()
動作在編譯期間被執行,而include指令在頁面請求期間被執行

頁面內容經常變化時更適合使用動作
頁面內容不經常變化時更適合使用include指令
動作包含的是執行結果,而include指令包含的是文件內容

第8章 案例項目
8-1 項目總體介紹

案例:商品瀏覽記錄的應用

採用Model1(Jsp+Javabean)實現

  • 實現DBHelper類
  • 創建實體類
  • 創建業務邏輯類(DAO)
  • 創建頁面層
8-2 項目原型
  • 列表頁面
  • 詳情頁面
8-3 DBHelper類設計

實現DBhelper類型
String driver = “com.mysql.jdbc.Driver”;//數據庫驅動
String url = “jdbc:mysql://localhost:3306/shopping?useUnicode=true&charaterEncoding=UTF”;//連接數據庫的url地址
String username = “root”;//數據庫的用戶名
String password = “”;//數據庫密碼

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();
        }

    }
}
8-4 商品實體類設計

採用Model1(JSP+JavaBean)實現

  • 實現DBhelper類
  • 創建實體類
  • 創建業務邏輯類(DAO)
  • 創建頁面層
//商品類
public class Items {

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

    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;
    }

}
8-5 獲取所有商品資料方法的實現
//商品的業務邏輯類
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();
                }
            }
        }

    }


}
8-6 所有商品信息顯示
<%@ 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">
       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>
8-7 商品詳細信息顯示
8-8 使用Cookie實現保存商品瀏覽記錄
//商品的業務邏輯類
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;
        }

    }

}
<%@ 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">
    -->
    <style type="text/css">
       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;
       }
    </style>
  </head>

  <body>
    <h1>商品詳情</h1>
    <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="4"><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> 
             </table>
          </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>您瀏覽過的商品</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>

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

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