JSP

JSP(Java Server Pages),其根本是一個簡化的 Servlet 設計,實現(xiàn)了在 Java 當中使用 HTML 標簽。JSP 是一種動態(tài)網(wǎng)頁技術標準,也是Java EE的標準。JSP與Servlet一樣,是在服務器端執(zhí)行的。

常見動態(tài)網(wǎng)站開發(fā)技術對比

  • JSP:Java平臺,安全性高,適合開發(fā)大型的,企業(yè)級的Web應用程序。
  • Asp.net:.Net平臺,簡單易學。但是安全性以及跨平臺型差。
  • Php:簡單,搞笑,成本低,開發(fā)周期短,特別適合中小型企業(yè)的Web應用開發(fā)。(LAMP:linux+Apache+MySql+Php)

JSP 基本語法

Jsp頁面元素構成

  • 指令
  • 表達式
  • 小腳本
  • 聲明
  • 注釋
  • 靜態(tài)內(nèi)容

指令

  • page 指令。
  • include 指令。將一個外部文件嵌入到當前jsp文件中,同時解析這個頁面中的jsp語句。
  • taglib 指令。使用標簽庫定義新的自定義標簽,在jsp頁面中啟用定制行為。

page

page 指令。通常位于jsp頁面的頂端,同一個頁面可以有多個page指令。

語法:

<%@ page 屬性1="屬性值" 屬性2="屬性值1,屬性值2" ... 屬性n="屬性值n" %>

屬性 描述 默認值
language 指定jsp頁面使用的腳本語言 java
import 通過該屬性來引用腳本語言中使用到的類文件
contentType 用來指定jsp頁面所采用的編碼格式 IntelliJ IDEA中:text/html;charset=UTF-8<br />Eclipse中:text/html; charset=ISO-8859-1

【Eclipse 新建jsp默認代碼如下】

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

【IntelliJ IDEA 新建jsp默認代碼如下】

<%--
  Created by IntelliJ IDEA.
  User: zdy
  Date: 2016/12/28 0028
  Time: 11:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

</body>
</html>

include

include 指令。將一個外部文件嵌入到當前jsp文件中,同時解析這個頁面中的jsp語句。

語法:

<%@ include file="url" %>

【示例】

<%@include file="date.jsp" %>

date.jsp

<body>
<%
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日");
    Date date=new Date();
    String s=simpleDateFormat.format(date);
    out.println(s);
%>
</body>

taglib

taglib 指令。使用標簽庫定義新的自定義標簽,在jsp頁面中啟用定制行為。

注釋

HTML注釋,客戶端源代碼可見

<!--html注釋-->

JSP 注釋,客戶端源代碼不可見

<%--JSP注釋--%>

JSP 腳本注釋,客戶端源代碼不可見。位于<% %>中的注釋。

//單行注釋
/**/多行注釋

腳本

在jsp中執(zhí)行的java代碼。

語法:

<% java 代碼 %>

【示例】

<body>
    你好,JSP!
    <!--我是html注釋-->
    <%--我是jsp注釋--%>
    //我是注釋嗎?我不是注釋
    /*我是注釋嗎?我不是注釋*/
    <%
        //單行注釋
        /*多行注釋*/
        out.println("大家好,我能顯示在頁面上!");
        System.out.println("大家好,我不能顯示在頁面上,我打印在控制臺上!");
    %>
</body>

聲明

在jsp頁面中定義變量或者方法。

語法:

<%! java 代碼 %> //語句以分號結束

表達式

在jsp頁面中執(zhí)行的表達式。

語法:

<%= 表達式 %> //表達式不以分號結束

【示例】

<body>
    <%!
        String s="zdy";//聲明一個變量
        //聲明一個函數(shù)
        int add(int x,int y){
            return x+y;
        }
    %>
    你好,<%=s%>,10+5=<%=add(10,5)%>
</body>

【頁面顯示】

你好,zdy,10+5=15

【實例2】

<%!
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  String s=sdf.format(new Date());
%>
今天是:<%=s%>

【頁面顯示】

今天是:2016-12-28    

JSP 頁面生命周期

JSP 頁面生命周期
jspService()

JSP 生命周期 菜鳥教程

JSP 內(nèi)置對象

JSP內(nèi)置對象是Web容器創(chuàng)建的一組對象,不適用new關鍵字就可以使用的內(nèi)置對象。

JSP 九大內(nèi)置對象

  • 常用的:out,request,response,session,application
  • 不常用的:page,pageContext,exception,config

Web 程序的請求響應模式

  • 用戶發(fā)送請求(request)
  • 服務器給用戶響應(response)

緩沖區(qū)buffer,內(nèi)存的一塊區(qū)域用來保存臨時數(shù)據(jù)。

out

JspWriter類的實例,是向客戶端輸出內(nèi)容常用的對象。

  • void println() 向客戶端打印字符串
  • void clear() 清除緩沖區(qū)的內(nèi)容,如果在flush之后調(diào)用會拋出異常
  • void clearBuffer() 清除緩沖區(qū)的內(nèi)容,如果在flush之后調(diào)用不會拋出異常
  • void flush() 將緩沖區(qū)內(nèi)容輸出到客戶端
  • int getBufferSize() 返回緩沖區(qū)字節(jié)數(shù)的大小,如不設緩沖區(qū)則為0
  • int getRemaining() 返回緩沖區(qū)還剩余多少可用
  • boolean isAutoFlush() 返回緩沖區(qū)滿時,是自動清空還是拋出異常
  • void close() 關閉輸出流

【示例】

緩沖區(qū)大?。?lt;%=out.getBufferSize()%>Byte<br />
緩沖區(qū)剩余大?。?lt;%=out.getRemaining()%>Byte<br />
是否自動清空緩沖區(qū):<%=out.isAutoFlush()%><br />

request

客戶端的請求信息被封裝在 request 對象中,通過他才能了解到客戶的需求,然后做出響應。它是 HttpServletRequset 類的實例。request 對象具有請求域,即完成客戶端的請求之前,該對象一直有效。

常用方法

  • String getParameter(String name) 返回name指定參數(shù)的參數(shù)值
  • String[] getParameterValues(String name) 返回包含參數(shù)name的所有值的數(shù)組
  • void setAttribute(String,Object) 存儲此請求中的屬性
  • object getAttribute(String name) 返回指定屬性的屬性值
  • String getContentType() 得到請求體的MIME類型
  • String getProtocol() 返回請求用的協(xié)議類型及版本號
  • String getServerName() 返回接收請求的服務器主機名
  • int getServerPort() 返回服務器接受此請求所用的端口號
  • String getCharacterEncoding() 返回字符編碼方式
  • void setCharacterEncoding(String) 設置請求的字符編碼方式
  • int getContentLength() 返回請求體的長度(字節(jié))
  • String getRemoteAddr() 返回發(fā)送此請求的客戶端ip地址
  • String getRealPath(String path) 返回一虛擬路徑的真實路徑【已經(jīng)被棄用deprecated】
  • String request.getContextPath() 返回上下文路徑

解決表單中文亂碼問題:

<%
    request.setCharacterEncoding("utf-8");
%>

解決URL中文亂碼問題:

<Connector port="8888" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8" />

【示例】

index.jsp

<body>
    <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>愛好:</td>
        <td>
          <input type="checkbox" name="f" value="read">讀書
          <input type="checkbox" name="f" value="music">音樂
          <input type="checkbox" name="f" value="movie">電影
          <input type="checkbox" name="f" value="internet">上網(wǎng)
        </td>
      </tr>
      <tr>
        <td colspan="2"><input type="submit" value="login"></td>
      </tr>
    </table>
    </form>
    <a href="dologin.jsp?username=張丹陽">link</a>
</body>

dologin.jsp

<body>
    登錄成功!<br />
    <%
        request.setCharacterEncoding("utf-8");
        request.setAttribute("attr","123456");
    %>
    用戶名:<%=request.getParameter("username")%><br />
    密碼:<%=request.getParameter("password")%><br />
    attr:<%=request.getAttribute("attr")%><br />
    愛好:
    <%
        String[] f=request.getParameterValues("f");
        if (f!=null){
            for (String s:f) {
                out.println(s);
            }
        }
    %><br />
    MIME類型:<%=request.getContentType()%><br />
    協(xié)議類型及版本號:<%=request.getProtocol()%><br />
    服務器主機名:<%=request.getServerName()%><br />
    服務器端口號:<%=request.getServerPort()%><br />
    請求文件的長度:<%=request.getContentLength()%><br />
    請求客戶端的IP地址:<%=request.getRemoteAddr()%><br />
    請求的上下文路徑:<%=request.getContextPath()%>
</body>

【頁面顯示 http://localhost:8888/MyWeb/dologin.jsp

登錄成功!
用戶名:張丹陽
密碼:8888888888
attr:123456
愛好: read music 
MIME類型:application/x-www-form-urlencoded
協(xié)議類型及版本號:HTTP/1.1
服務器主機名:localhost
服務器端口號:8888
請求文件的長度:71
請求客戶端的IP地址:0:0:0:0:0:0:0:1
請求的上下文路徑:/MyWeb

response

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

常用方法

  • String getCharacterEncoding() 返回響應用的是何種字符編碼
  • void setContentType(String type) 設置相應的MIME類型
  • PrintWriter getWriter() 返回可以向客戶端輸出字符的一個對象(跟out對象對比,此對象輸出總是先于out對象輸出)
  • sendRedirect(java.lang.String location) 重新定向客戶端的請求

【示例】

<body>
<%
    response.setContentType("text/html;charset=UTF-8");
    out.println("這是out輸出");
    out.flush();
    PrintWriter outer=response.getWriter();
    outer.println("response.getWriter()實例輸出");
%>
</body>

<%
    response.sendRedirect("index.jsp");//請求重定向
%>

請求轉發(fā)與請求重定向

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

請求轉發(fā)與請求重定向

imooc相關視頻

【示例】

//請求重定向
response.sendRedirect("request.jsp");
//請求轉發(fā)
request.getRequestDispatcher("dologin.jsp").forward(request,response);

session

  • session 表示客戶端與服務器的一次會話
  • Web 中的 session 指的是用戶在瀏覽某個網(wǎng)站時,從進入網(wǎng)站到瀏覽器關閉所經(jīng)過的這段時間,也就是用戶瀏覽這個網(wǎng)站所花費的時間
  • session 實際是一個特定的時間概念
  • 在服務器的內(nèi)存中保存著不同用戶的 session ,與用戶一一對應
  • session 對象是一個jsp內(nèi)置對象
  • session 對象在第一個jsp頁面被裝載時自動創(chuàng)建,完成會話期管理
  • 從一個客戶打開瀏覽器并連接到服務器開始,到客戶關閉瀏覽器離開這個服務器結束,被稱為一個會話
  • 當一個客戶訪問一個服務器時,可能會在服務器的幾個頁面之間切換,服務期應當通過某種方法知道這是一個客戶,就需要session對象
  • session 對象是 HttpSession 類的實例

常用方法

  • long getCreationTime() 返回session創(chuàng)建時間
  • public String getId() 返回session創(chuàng)建時jsp引擎為他設置的唯一ID號
  • public Object setAttribute(String name,Object value) 使用指定名稱將對象綁定到此會話
  • public Object getAttribute(String) 返回與此會話中的指定名稱綁定在一起的對象,如果沒有對象綁定在該名稱下,則返回null
  • Enumeration getAttributeNames() 返回一個包含此session中所有可用屬性的數(shù)組
  • int getMaxInactiveInterval() 返回兩次請求間隔多長時間此session被取消掉(單位秒)

【示例】

session.jsp

<body>
<%
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date=new Date(session.getCreationTime());
    session.setAttribute("username","zdy");
    session.setAttribute("password","pwd");
    session.setAttribute("age",20);
    session.setMaxInactiveInterval(10);//10s
%>
Session創(chuàng)建時間:<%=simpleDateFormat.format(date)%><br />
Session ID:<%=session.getId()%><br />
從Session中獲取用戶名:<%=session.getAttribute("username")%><br />
Session中保存的屬性有:
<%
    Enumeration<String> m=session.getAttributeNames();
    Enumeration enumeration=session.getAttributeNames();
    while (enumeration.hasMoreElements()){
        Object e=enumeration.nextElement();
        out.println("屬性名:"+ e.toString());
        out.println("屬性值:"+session.getAttribute(e.toString()));
    }
%>
<a href="session2.jsp" target="_blank">跳轉</a>
</body>

session2.jsp

<body>
<%
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date=new Date(session.getCreationTime());
%>
Session創(chuàng)建時間:<%=simpleDateFormat.format(date)%><br />
Session ID:<%=session.getId()%><br />
從Session中獲取用戶名:<%=session.getAttribute("username")%><br />
</body>

session 生命周期

  • 創(chuàng)建:當客戶端第一次訪問某個jsp或者Servlet時,服務器會為當前會話創(chuàng)建一個SessionId,每次客戶端向服務端發(fā)送請求時,都會將此SessionId攜帶過去,服務端會對此SessionId進行校驗。
  • 活動:
    • 某次會話當中通過超鏈接打開的新頁面屬于同義詞會話
    • 只要當前會話頁面沒有全部關閉,重新打開新的瀏覽器窗口訪問同一項目資源時屬于同一次會話
    • 除非本次會話的所有頁面都關閉后再重新訪問某個jsp或者Servlet將會創(chuàng)建新的會話
      • 注意:原有會話還在,只是這個舊的SessionId依然存在于服務端,只不過再也沒有客戶端會攜帶它然后交與服務端校驗。
  • 銷毀:
    • 調(diào)用了session.invalidate()方法
    • session過期(超時)
    • 服務器重新啟動

設置session超時時間的方式

方法1:session.setMaxInactiveInterval(10);//單位秒

方法2:web.xml中配置(單位是分鐘):

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

application

  • application對象實現(xiàn)了用戶間數(shù)據(jù)的共享,可存放全局變量
  • application開始于服務器的啟動,終止于服務器的關閉
  • 在用戶的前后連接或不同用戶之間的連接中,可以對application對象的同一屬性進行操作
  • 在任何地方對application對象屬性的操作,都將影響到其他用戶對此的訪問
  • 服務器的啟動和關閉決定了application對象的生命
  • application對象是ServletContext類的實例

常用方法

  • public void setAttribute(String name,Object value)使用指定名稱將對象綁定到此會話
  • public Object getAttribute(String names) 返回與此會話中的指定名稱綁定在一起的對象,如果沒有對象綁定在該名稱下,則返回null
  • Enumeration getAttributeNames() 返回所有可用屬性名的枚舉
  • String getServerInfo() 返回 JSP (Servlet) 引擎名及版本號

【示例】

<body>
<%
    application.setAttribute("city","北京");
    application.setAttribute("postcode","100000");
    application.setAttribute("extel","010");
%>
城市:<%=application.getAttribute("city")%><br />
application屬性有:
<%
    Enumeration enumeration=application.getAttributeNames();
    while (enumeration.hasMoreElements()){
        out.println(enumeration.nextElement().toString()+"&nbsp;&nbsp;&nbsp;");
    }
%><br />
JSP(SERVLET)引擎名與版本號:<%=application.getServerInfo()%><br />
</body>

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() 使一個線程出于等待直到被喚醒

pageContext

  • pageContext 對象提供了對jsp頁面內(nèi)所有對象及名字空間的訪問
  • pageContext 對象可以訪問到本業(yè)所在的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) 在指定范圍內(nèi)獲取屬性的值
  • int getAttributeScope(String name) 返回某屬性的作用范圍
  • void forward(String relativeUrlPath) 使當前頁面重導到另一頁面,url不變
  • void include(String relativeUrlPath) 在當前位置包含另一文件

【示例1】

用戶名是:<%=pageContext.getSession().getAttribute("username")%>

【示例2】

<%
    pageContext.forward("index.jsp");
%>

【示例3】

<%
    pageContext.include("index.jsp");
%>

Config

config 是在一個 Servlet 初始化時,jsp引擎向它傳遞信息用的,此信息包括 Servlet 初始化時所要用到的參數(shù)(通過屬性名和屬性值構成)以及服務器的有關信息(通過傳遞一個ServletContext對象)

常用方法

  • ServletContext getServletContext() 返回含有服務器相關信息的 ServletContext 對象
  • String getInitParameter(String name) 返回初始化參數(shù)的值
  • Enumeration getInitParameterNames() 返回 Servlet 初始化所需所有參數(shù)的枚舉

exception

exception 對象是一個異常對象,當一個頁面中在運行過程中發(fā)生了異常,就產(chǎn)生這個對象。如果一個JSP頁面要應用此對象,就必須把 isErrorPage 設為true(在page指令中設置),否則無法編譯。他實際上是java.lang.Throwable 的對象。

常用方法

  • String getMessage() 返回描述異常的消息
  • String toString() 返回關于異常的簡短描述信息
  • void printStackTrace() 顯示異常及其棧軌跡
  • Throwable FillStackTrace() 重寫異常的執(zhí)行棧軌跡

【示例】

exception.jsp 在page指令中將錯誤頁面定向到error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" errorPage="error.jsp" %>
<html>
<head>
    <title>exception</title>
</head>
<body>
<%
    System.out.println(100/0);
%>
</body>
</html>

error.jsp 在page指令中指定 isErrorPage 為true

<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
異常消息是:<%=exception.getMessage()%><br />
異常的字符串描述:<%=exception.toString()%>
</body>
</html>

【運行結果】頁面url未該變,是exception.jsp

異常消息是:/ by zero
異常的字符串描述:java.lang.ArithmeticException: / by zero

關于登錄的一個小視頻教程,來自慕課網(wǎng)

JavaBean

JavaBean 就是符合某種特定規(guī)范的java類。使用 JavaBeans 的好處是解決代碼重復編寫,減少代碼的冗余,功能區(qū)分明確,提高代碼的維護性。

設計原則

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

Jsp動作

jsp動作元素(action elements)為請求處理階段提供信息。動作元素遵循xml元素的語法,有一個包含元素明德開始標簽,可以有屬性、可選的內(nèi)容、與開始標簽匹配的結束標簽。

第一類:與存取JavaBean有關的

<jsp:useBean><jsp:setProperty><jsp:getProperty>

【講解&實例】見下面的javabean部分

第二類:基本的動作元素,6個 (JSP1.2+)

<jsp:include><jsp:forward><jsp:param><jsp:plugin><jsp:params><jsp:fallback>

<jsp:include>

語法:

<jsp:include page="url" flush="true|false" />

page 要包含的頁面

flush 被包含的頁面是否從緩沖區(qū)讀取

【示例】

<jsp:include page="date.jsp" flush="false"/>
include 指令 與 include 動作比較
- include指令 include動作
語法格式 <%@ include file="url" %> <jsp:include page="url">
發(fā)生作用的時間 頁面轉換期間 請求期間
包含的內(nèi)容 文件的實際內(nèi)容 頁面的輸出
轉化成的Servlet 主頁面和包含頁面轉換成一個Servlet 主頁面和包含頁面轉換為獨立的Servlet
編譯時間 較慢,資源必須被解析 較快
執(zhí)行時間 較快 較慢,每次資源必須被解析
  • <jsp:include>動作在請求期間被執(zhí)行,而include指令在編譯期頁面間被執(zhí)行
  • 頁面內(nèi)容經(jīng)常變化時更適合使用<jsp:include>動作
  • 頁面內(nèi)容不經(jīng)常變化時更適合使用include指令
  • <jsp:include>動作包含的是執(zhí)行結果,而include指令包含的是文件內(nèi)容

<jsp:forward>

語法:

<jsp:forward page="url" />

等同于轉發(fā):

request.getRequestDispatcher("/url").forward(request,response);

【示例】

<jsp:forward page="userinf.jsp" />

等價于

<%
    request.getRequestDispatcher("userinf.jsp").forward(request,response);
%>

<jsp:param>

語法:

<jsp:param name="參數(shù)名" value="參數(shù)值">

常常與<jsp:forward>一起使用,作為其子標簽

【示例】

<jsp:forward page="userinf.jsp" >
    <jsp:param name="email" value="email@gmail.com" />
</jsp:forward>

第三類:主要與JSP document有關的,6個 (JSP2+)

<jsp:root><jsp:declaration><jsp:scriptlet><jsp:expression><jsp:text><jsp:output>

第四類:主要用來動態(tài)生成XML元素標簽的值,3個(JSP2+)

<jsp:attribute><jsp:body><jsp:element>

第五類:主要用在Tage File中,2個(JSP2+)

<jsp:invoke><jsp:dobody>

在jsp頁面中使用javabean

使用普通方式創(chuàng)建javabean實例

<%
    User u=new User();
    u.setName("zdy");
%>
用戶名:<%=u.getName()%>

使用jsp動作標簽使用javabean

在jsp頁面中實例化或者在指定范圍內(nèi)使用javabean。

useBean

在jsp中實例化或者在指定范圍內(nèi)使用javabean

<jsp:useBean id="標識符" class="java類名" scope="作用域" />

setProperty

給已經(jīng)實例化的JavaBean對象的屬性賦值,一共有四種方式:

<jsp:setProperty name="JavaBean 實例名" property="*" />(跟表單關聯(lián))

<jsp:setProperty name="JavaBean 實例名" property="JavaBean屬性名" />(跟表單關聯(lián))

<jsp:setProperty name="JavaBean 實例名" property="JavaBean屬性名" value="BeanValue" />(手動設置)


<jsp:setProperty name="JavaBean 實例名" property="JavaBean屬性名" param
="request對象中的參數(shù)名" />(跟request參數(shù)關聯(lián))

【示例】com.po下的User類

public class User {
    private String username;
    private String password;
    public User(){

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

【頁面1:index.jsp】

  <form action="javabean.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="login"></td>
      </tr>
    </table>
  </form>

【頁面2:javabean.jsp 實例1】根據(jù)表單自動匹配所有的屬性

<jsp:useBean id="myUser" class="com.po.User" scope="page"/>
<jsp:setProperty name="myUser" property="*"/>
用戶名:<%=myUser.getUsername()%>
密碼:<%=myUser.getPassword()%>

亂碼處理,下同

<%
    request.setCharacterEncoding("utf-8");
%>

【頁面顯示】

用戶名:張丹陽 密碼:123456

【頁面2:javabean.jsp 實例2】根據(jù)表單匹配部分屬性

<jsp:useBean id="myUser" class="com.po.User" scope="page"/>
<jsp:setProperty name="myUser" property="username"/>
用戶名:<%=myUser.getUsername()%>
密碼:<%=myUser.getPassword()%>

【頁面顯示】

用戶名:張丹陽 密碼:null

【頁面2:javabean.jsp 實例3】跟表單無關,手動賦值

<jsp:useBean id="myUser" class="com.po.User" scope="page"/>
<jsp:setProperty name="myUser" property="username" value="張Sir"/>
<jsp:setProperty name="myUser" property="password" value="888888"/>
用戶名:<%=myUser.getUsername()%>
密碼:<%=myUser.getPassword()%>

【頁面顯示】

用戶名:張Sir 密碼:888888

【頁面2:javabean.jsp 實例3】通過request賦值

<jsp:useBean id="myUser" class="com.po.User" scope="page"/>
<jsp:setProperty name="myUser" property="username" param="username"/>
<jsp:setProperty name="myUser" property="password" param="password"/>
用戶名:<%=myUser.getUsername()%>
密碼:<%=myUser.getPassword()%>

【頁面顯示】

用戶名:張丹陽 密碼:123456

getProperty

獲取指定JavaBean對象的屬性值

<jsp:getProperty name="JavaBean 實例名" property="屬性名" />

【示例】

<jsp:useBean id="myUser" class="com.po.User" scope="page"/>
<jsp:setProperty name="myUser" property="*" />
用戶名:<jsp:getProperty name="myUser" property="username"/>
密碼:<jsp:getProperty name="myUser" property="password"/>

四個作用域范圍

使用useBean的scope屬性指定javabean的作用范圍。

  • page 僅在當前頁面有效
  • request 可以通過 HttpRequest.getAttribute() 取得javabean對象
  • session 可以通過 HttpSession.getAttribute() 取得javabean對象
  • application 可以通過 application.getAttribute() 取得javabean對象

【示例】

javabean.jsp

<jsp:useBean id="myUser" class="com.po.User" scope="application"/>
<jsp:setProperty name="myUser" property="*" />

testScope.jsp

<jsp:useBean id="myUser" class="com.po.User" scope="application"/>
用戶名:<%=((User)application.getAttribute("myUser")).getUsername()%>
密碼:<%=((User)application.getAttribute("myUser")).getPassword()%>

更詳細的教程,來自慕課網(wǎng)

Model1

Model1

關于登錄的一個javabean小視頻教程,來自慕課網(wǎng)

JSP 狀態(tài)管理

http 協(xié)議無狀態(tài)性

保存用戶狀態(tài)的兩大機制

session、cookie

Cookie

Cookie是Web服務器保存在客戶端的一系列文本信息。

【應用】

  • 判斷注冊用戶是否已經(jīng)登錄網(wǎng)站
  • 購物車

【作用】

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

【安全風險】

容易泄漏用戶信息

創(chuàng)建與使用Cookie

創(chuàng)建Cookie對象

Cookie newCookie=new Cookie(String key,Object value);

寫入Cookie對象

response.addCookie(newCookie);

讀取Cookie對象

Cookie[] cookies=request.getCookies();

常用方法

  • void setMaxAge(int expiry) 設置cookie有效期,以秒為單位
  • void setValue(String value) 在cookie創(chuàng)建后,對cookie進行賦值
  • String getName() 獲取cookie的名稱
  • String getValue() 獲取cookie的值
  • int getMaxAge() 獲取cookie的有效時間,以秒為單位

【實例:十天內(nèi)記住登錄狀態(tài)】

index.jsp

<body>
<%
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=c.getValue();
      username= URLDecoder.decode(c.getValue(),"utf-8");
    }else if(c.getName().equals("password")){
      password=c.getValue();
    }
  }
}
%>
<form action="login.jsp" name="loginForm" 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"/>十天內(nèi)記住我的登錄狀態(tài)</td>
  </tr>
  <tr>
    <td colspan="2"><input type="submit" value="login"></td>
  </tr>
</table>
</form>
</body>

login.jsp

<body>
<%
    request.setCharacterEncoding("utf-8");
    //判斷用戶是否選擇記住登錄狀態(tài)
    String[] isUseCookies=request.getParameterValues("isUseCookie");
    if (isUseCookies!=null&&isUseCookies.length>0){
        //把用戶名和密碼保存在Cookie對象里面
        String username= URLEncoder.encode(request.getParameter("username"),"utf-8");
        //String username=request.getParameter("username");
        String password=request.getParameter("password");
        Cookie usernameCookie=new Cookie("username",username);
        Cookie passwordCookie=new Cookie("password",password);
        usernameCookie.setMaxAge(864000);//設置最大生存期限為10天
        passwordCookie.setMaxAge(864000);
        response.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="userinf.jsp">跳轉查看保存在cookie的信息</a>
</body>

userinf.jsp

<body>
<%
    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=c.getValue();
               username= URLDecoder.decode(c.getValue(),"utf-8");
            }else if(c.getName().equals("password")){
                password=c.getValue();
            }
        }
    }
%>
用戶名:<%=username%><br />
密碼:<%=password%><br />
</body>

session 與 cookie 對比

session cookie
在服務器端保存用戶信息 在客戶端保存用戶信息
保存的是Object類型 保存的是String類型
隨會話的結束而將其存儲的數(shù)據(jù)銷毀 長期保存在客戶端
保存重要的信息 保存不重要的信息

實例

商品列表、詳情以及最近瀏覽記錄:慕課網(wǎng)

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 一、jsp定義及作用 JSP技術使用Java編程語言編寫類XML的tags和scriptlets,來封裝產(chǎn)生動態(tài)網(wǎng)...
    yzw12138閱讀 1,464評論 0 0
  • 一、表單提交方式之Get和Post的區(qū)別 Get:以明文的方式通過URL提交數(shù)據(jù),數(shù)據(jù)在URL中可以看到。提交的數(shù)...
    潛心之力閱讀 2,349評論 1 2
  • 什么是jsp? 很久之前,我們的網(wǎng)頁都是靜態(tài)的,就是我們所看到的頁面在編寫好之后總是唯一的。后來有人便提出動態(tài)頁面...
    ezsync小智閱讀 1,666評論 0 13
  • 1.什么是JSP (1)jsp全稱是Java Server Pages,它和Servlet技術一樣都是sun公司定...
    yjaal閱讀 3,834評論 5 99
  • 終于見到“他”了,傳說中來自戰(zhàn)斗民族俄羅斯的神車---拉達。 《老柳說車》的節(jié)目與自媒體矩陣去年就專門介紹過這款車...
    老柳說車閱讀 663評論 0 0

友情鏈接更多精彩內(nèi)容