Jsp詳解


1Jsp基礎

1.1 Jsp引入

Servlet的作用: 用java語言開發動態資源的技術!!!

Jsp的作用:用java語言+html語言)開發動態資源的技術!!!

Jsp就是servlet!!!

1.2 Jsp的特點

1jsp的運行必須交給tomcat服務器!!!!

tomcatwork目錄: tomcat服務器存放jsp運行時的臨時文件

2jsp頁面既可以寫html代碼,也可以寫java代碼。

html頁面不能寫java代碼 。而jsp頁面可以寫java代碼)

1.3 體驗jsp頁面作用

需求:顯示當前時間到瀏覽器上

 

可以把jsp頁面當做html頁面在tomcat訪問!!!

 

1.4 Jsp的執行過程

問題: 訪問http://localhost:8080/day12/01.hello.jsp  如何顯示效果?

 

1)訪問到01.hello.jsp頁面,tomcat掃描到jsp文件,在%tomcat%/workjsp文件翻譯成java源文件

(01.hello.jsp   ->   _01_hello_jsp.java) (翻譯)

2tomcat服務器把java源文件編譯成class字節碼文件 (編譯)

_01_hello_jsp.java  ->  _01_hello_jsp.class

3tomcat服務器構造_01_hello_jsp類對象

4tomcat服務器調用_01_hello_jsp類里面方法,返回內容顯示到瀏覽器。

 

第一次訪問jsp

走(1)(2)(3)(4

n次訪問jsp

走(4

 

注意:

1jsp文件修改了或jsp的臨時文件被刪除了,要重新走翻譯(1)和編譯(2)的過程

 

1.5 疑問

問題: 為什么Jsp就是servlet!!!

jsp翻譯的java文件:

public final class _01_hello_jsp extends org.apache.jasper.runtime.HttpJspBase

    implements org.apache.jasper.runtime.JspSourceDependent {

 

HttpJspBase類:

public abstract class org.apache.jasper.runtime.HttpJspBase extends javax.servlet.http.HttpServlet implements javax.servlet.jsp.HttpJspPage {

 

結論: Jsp就是一個servlet程序!!!

servlet的技術可以用在jsp程序中

jsp的技術並不是全部適用於servlet程序!

 

 

Servlet的生命周期:

1)構造方法(第1次訪問)

2)init方法(第1次訪問)

3)service方法

4)destroy方法

Jsp的生命周期

1)翻譯: jsp->java文件

2)編譯: java文件->class文件(servlet程序)

3)構造方法(第1次訪問)

4)init方法(第1次訪問):_jspInit()

5)service方法:_jspService()

6)destroy方法:_jspDestroy()

 

2 Jsp語法

2.1 Jsp模板

jsp頁面中的html代碼就是jsp的模板

2.2 Jsp表達式

語法:<%=變量或表達式%>

作用: 向瀏覽器輸出變量的值或表達式計算的結果

注意:

1)表達式的原理就是翻譯成out.print(“變量” );通過該方法向瀏覽器寫出內容

2)表達式后面不需要帶分號結束。

2.3 Jsp的腳本

語法:<%java代碼 %>

作用: 執行java代碼

注意:

1)原理把腳本中java代碼原封不動拷貝到_jspService方法中執行。

2.4 Jsp的聲明

語法:<%! 變量或方法 %>

作用: 聲明jsp的變量或方法

注意:

1)變量翻譯成成員變量,方法翻譯成成員方法。

2.5 Jsp的注釋

語法: <%!--  jsp注釋  --%>

注意;

1)html的注釋會被翻譯和執行。而jsp的注釋不能被翻譯和執行。

3 Jsp的三大指令

3.1 include指令

作用: 在當前頁面用於包含其他頁面

語法: <%@include file="common/header.jsp"%>

注意:

1)原理是把被包含的頁面(header.jsp)的內容翻譯到包含頁面(index.jsp),合並成翻譯成一 java源文件,再編譯運行!!,這種包含叫靜態包含(源碼包含)

2)如果使用靜態包含,被包含頁面中不需要出現全局的html標簽了!!!(如htmlhead body

3.2 page指令

作用: 告訴tomcat服務器如何翻譯jsp文件

<%@ page 

language="java"   --告訴服務器使用什么動態語言來翻譯jsp文件

import="java.util.*" --告訴服務器java文件使用什么包

導入包,多個包之間用逗號分割

pageEncoding="utf-8"  --告訴服務器使用什么編碼翻譯jsp文件(成java文件)

 contentType="text/html; charset=utf-8" 服務器發送瀏覽器的數據類型和內容編碼

注意:在開發工具中,以后只需要設置pageEncoding即可解決中文亂碼問題

errorPage="error.jsp"

isErrorPage="false"

buffer="8kb"

session="true"

isELIgnored="false"

%>

基本練習:生成9*9乘法表以及一些基本操作:

 

<%@ page language="java" import="java.util.*" pageEncoding="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>JSP語法</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>
  <%--逗比啊 --%>
  <%@include file="common/1.hello.jsp" %>
    <%
        String name="handsomecui";
        int a = 15;
        int b = 20;
     %>
     <%=name %>
     <%=(a-b) %>
     <%=(a/b) %>
     <hr/>
     <!-- 生成隨機數 -->
     <%
         Random ran = new Random();
         Float num = ran.nextFloat();
      %>
      <%=num %>
      <%
          for(int i = 1; i <= 6; i++){
              %>
              <h<%=i %>>標題<%=i %></h<%=i %>>
              <%              
          }
      %>
      <%
          for(int i = 1; i <= 9; i++){
              for(int j = 1; j <= i; j++){
                  %>
                  <%=j %>*<%=i %>=<%=(j*i) %>&nbsp;
                  <%
              }
              %>
              <br/>
              <% 
          }
      %>
      <%!
     String name = "崔哥哥";
      %>
  </body>
</html>

 

 

Jsp的內置對象(重點)

2.1 什么是內置對象?

jsp開發中,會頻繁使用到一些對象

。例如HttpSession,ServletContext,ServletContext,HttpServletRequet。如果我們每次要使用這些對象都去創建這些對象就顯示非常麻煩。所以Sun公司設計Jsp時,在jsp頁面加載完畢之后就會自動幫開發者創建好這些對象,而開發者只需要直接使用這些對象調用方法即可!,這些創建好的對象就叫內置對象!!!!

 

舉例:

servlet:

HttpSession session = request.getSession(true); (需要開發者做)

 

jsp:

tomcat服務器: HttpSession session = request.getSession(true);(不需要開發者做)

開發者做的: session.getId();

 

2.2 9大內置對象

內置對象名          類型

   request    HttpServletRequest

  response      HttpServletResponse

   config        ServletConfig

application        ServletContext

 session         HttpSession

exception        Throwable

page            Object(this)

out             JspWriter

pageContext     PageContext

 

  2.3 Out對象

out對象類型,JspWriter類,相當於帶緩存的PrintWriter

 

PrintWriter

wrier(內容): 直接向瀏覽器寫出內容。

 

JspWriter

writer(內容): jsp緩沖區寫出內容

 

當滿足以下條件之一,緩沖區內容寫出:

1)緩沖區滿了

2)刷新緩存區

3)關閉緩存區

4)執行完畢jsp頁面

 

  2.4 pageContext對象

pageContext對象的類型是PageContext,叫jsp的上下文對象

 

     1)可以獲取其他八個內置對象

 

public class 01_hello_jsp {

public void _jspService(request,response){

創建內置對象

HttpSession session =....;

ServletConfig config = ....;

 

8個經常使用的內置對象封裝到PageContext對象中

PageContext pageContext  = 封裝;

調用method1方法

method1(pageContext);

}

 

public void method1(PageContext pageContext){

希望使用內置對象

PageContext對象中獲取其他8個內置對象

JspWriter out =pageContext.getOut();

HttpServletRequest rquest = pageContext.getRequest();

........

}

}

 

使用場景: 在自定義標簽的時候,PageContext對象頻繁使用到!!!

       2)本身是一個域對象

ServletContext context

HttpServletRequet  request

HttpSession    session域     --Servlet學習的

PageContext   page        --jsp學習的

 

 

作用: 保存數據和獲取數據,用於共享數據

 

#保存數據

1)默認情況下,保存到page

pageContext.setAttribute("name");

2)可以向四個域對象保存數據

pageContext.setAttribute("name",域范圍常量)

 

#獲取數據

1)默認情況下,從page域獲取

pageContext.getAttribute("name")

2)可以從四個域中獲取數據

pageContext.getAttribute("name",域范圍常量)

 

域范圍常量:

PageContext.PAGE_SCOPE

PageContext.REQUEST_SCOPE

PageContext..SESSION_SCOPE

PageContext.APPLICATION_SCOPE

3)自動在四個域中搜索數據

pageContext.findAttribute("name");

順序: page-> request-> session- > context域(application域)

3 Jsp中的四個域對象

四個域對象:

pageContext      page

request          request

session          session

application       context

 

1)域對象作用:

保存數據   獲取數據 ,用於數據共享。

 

2)域對象方法:

setAttribute("name",Object) 保存數據

getAttribute("name")  獲取數據

removeAttribute("name") 清除數據

 

3)域對象作用范圍:

page域: 只能在當前jsp頁面中使用(當前頁面)

request域: 只能在同一個請求中使用(轉發)

session域: 只能在同一個會話(session對象)中使用(私有的)

    context域: 只能在同一個web應用中使用。(全局的)

4 Jsp的最佳實踐

Servlet技術: 開發動態資源。是一個java類,最擅長寫java代碼

jsp技術: 開發動態資源。通過java代碼最擅長輸出html代碼。

 

 

各取所長:

web項目中涉及到邏輯:

1)接收參數      servlet

2)處理業務邏輯,返回結果    servlet

3)顯示數據到瀏覽器      jsp

4)跳轉到其他頁面        servlet

 

 

servlet+jsp模式

 

  servlet:

1)接收參數

2)處理業務邏輯

3)把結果保存到域對象中

4)跳轉到jsp頁面

Jsp:

1)從域對象取出數據

2)把數據顯示到瀏覽器

 

servlet的數據    ->   jsp頁面

List<Contact>    使用域對象 共享數據

 

5 EL表達式

5.1 EL作用

jsp的核心語法: jsp表達式 <%=%>jsp腳本<%  %>

以后開發jsp的原則: 盡量在jsp頁面中少寫甚至不寫java代碼。

 

使用EL表達式替換掉jsp表達式

 

EL表達式作用: 向瀏覽器輸出域對象中的變量值或表達式計算的結果!!!

 

語法: ${變量或表達式}

 

5.2 EL語法

1)輸出基本數據類型變量

1.1 從四個域獲取

${name}

1.2 指定域獲取

${pageScope.name}

                    域范圍: pageScoep / requestScope / sessionScope / applicationScope

 

    2)輸出對象的屬性值

Student

3)輸出集合對象

   List  Map

4EL表達式計算

6 jsp標簽

6.1 jsp標簽的作用

jsp標簽作用:替換jsp腳本。

 

1)流程判斷(if   for循環)

2)跳轉頁面(轉發,重定向)

3)。。。。。

 

6.2 Jsp標簽分類

1)內置標簽(動作標簽): 不需要在jsp頁面導入標簽

2jstl標簽: 需要在jsp頁面中導入標簽

3)自定義標簽 : 開發者自行定義,需要在jsp頁面導入標簽

6.3 動作標簽

  轉發標簽: <jsp:forward />

            參數標簽:  <jsp:pararm/>

包含標簽:  <jsp:include/>

原理: 包含與被包含的頁面先各自翻譯成java源文件,然后再運行時合並在一起。

(先翻譯再合並),動態包含

 

靜態包含  vs  動態包含的區別?

 

1) 語法不同

靜態包含語法: <%@inclue file="被包含的頁面"%>

動態包含語法: <jsp:include page="被包含的頁面">

 

2)參數傳遞不同

靜態包含不能向被包含頁面傳遞參數

動態包含可以向被包含頁面傳遞參數

 

3)原理不同

靜態包含: 先合並再翻譯

動態包含: 先翻譯再合並

 

6.4 JSTL標簽

JSTL (全名:java  standard  tag  libarary   -  java標准標簽庫  )

 

核心標簽庫 c標簽庫) 天天用

國際化標簽(fmt標簽庫)

EL函數庫(fn函數庫)

xml標簽庫(x標簽庫)

sql標簽庫(sql標簽庫)

6.5 使用JSTL標簽步驟

1) 導入jstl支持的jar包(標簽背后隱藏的java代碼)

注意:使用javaee5.0的項目自動導入jstl支持jar

2)使用taglib指令導入標簽庫

<%@taglib uri="tld文件的uri名稱" prefix="簡寫" %>

3)在jsp中使用標簽

 

核心標簽庫的重點標簽:

保存數據:

<c:set></c:set>   

獲取數據:

             <c:out value=""></c:out>

單條件判斷

            <c:if test=""></c:if>

多條件判斷

          <c:choose></c:choose>

       <c:when test=""></c:when>

          <c:otherwise></c:otherwise>

    循環數據

          <c:forEach></c:forEach>

          <c:forTokens items="" delims=""></c:forTokens>

重定向

          <c:redirect></c:redirect>

 代碼練習:

<%@ page language="java" import="java.util.*,com.base.others.*" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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 'core.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>
      <%--保存到域中(默認page域) --%>
    <c:set var="name" value="rose" scope="request"></c:set>
    ${requestScope.name }
    <c:out value="${name }"></c:out>
    <br/>
    <%
        String msg = null;
           pageContext.setAttribute("msg", msg);
    %>
    <c:out value="${msg }" default="<h3>默認值</h3>" escapeXml="false"></c:out>
      <hr/>
      <c:if test="${empty msg}">
          條件成立
      </c:if>
      <hr/>
      <c:set var = "score" value="85"></c:set>
      <c:choose>
          <c:when test="${score>=90 && score <= 100 }">
              優秀
          </c:when>
          <c:when test="${score>=80 && score < 90 }">
              良好
          </c:when>
          <c:when test="${score>=700 && score < 80 }">
              一般
          </c:when>
          <c:when test="${score>=60 && score < 70 }">
              及格
          </c:when>
          <c:otherwise>
              不及格
          </c:otherwise>
      </c:choose>
      <hr/>
      <%
        List<Contact>list = new ArrayList<Contact>();
        list.add(new Contact("崔俊勇","男",12,"1568445","15152","154@qq.com"));
        list.add(new Contact("崔勇","男",12,"1568445","15152","154@qq.com"));
        list.add(new Contact("崔帥","男",12,"1568445","15152","154@qq.com"));
        pageContext.setAttribute("list",list);
    %>
    <c:forEach begin="0" end="2" items="${list }" step="1" var="contact" varStatus="varsta">
        序號:${varsta.count } - 姓名:${contact.name } - 年齡:${contact.age }
        <br/>
    </c:forEach>
    <%
        String str = "java-php-net-好吧";
        pageContext.setAttribute("str", str);
    %>
    <c:forTokens items="${str }" delims="-" var = "s">
        ${s }<br/>
    </c:forTokens>
    <%-- <c:redirect url="http://handsomecui.top"></c:redirect>--%>
  </body>
</html>
<%@ page language="java" import="java.util.*,com.base.others.*" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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 'el1.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>
  <%--使用標簽 --%>
  <%--<c:set></c:set>
  
  <c:out value=""></c:out>
  
  <c:if test=""></c:if>
  
  <c:choose></c:choose>
  <c:when test=""></c:when>
  <c:otherwise></c:otherwise>
  
  <c:forEach></c:forEach>
  <c:forTokens items="" delims=""></c:forTokens>
 
  <c:redirect></c:redirect>
   --%>
  <jsp:include page="bq.jsp"></jsp:include>
    <%
        Contact contact = new Contact("崔俊勇","男",12,"1568445","15152","154@qq.com");
        List<Contact>list = new ArrayList<Contact>();
        list.add(new Contact("崔俊勇","男",12,"1568445","15152","154@qq.com"));
        list.add(new Contact("崔勇","男",12,"1568445","15152","154@qq.com"));
        list.add(new Contact("崔帥","男",12,"1568445","15152","154@qq.com"));
        
        pageContext.setAttribute("contact",contact);
        pageContext.setAttribute("list",list);
        String name = "";
        pageContext.setAttribute("name", name);
    %>
    ${contact.name} - ${contact.age }
    ${list[1].name} - ${list[1].age }
    ${list[2].name} - ${list[2].age }
    ${name==null} ${empty name }
    <%-- <jsp:forward page="/guess.jsp"></jsp:forward> --%>
    <jsp:forward page="/bq.jsp">
        <jsp:param name="name" value="崔俊勇"/>
        <jsp:param name="name1" value="handsomecui"/>
    </jsp:forward>
  </body>
</html>

 

自定義標簽

2.1 引入

需求: 向瀏覽器輸出當前客戶的IP地址 (只能使用jsp標簽)

 

2.2 第一個自定義標簽開發步驟

1)編寫一個普通的java類,繼承SimpleTagSupport類,叫標簽處理器類

 

/**

 * 標簽處理器類

 * @author APPle

 * 1)繼承SimpleTagSupport

 *

 */

public class ShowIpTag extends SimpleTagSupport{

private JspContext context;

 

/**

 * 傳入pageContext

 */

@Override

public void setJspContext(JspContext pc) {

this.context = pc;

}

 

/**

 * 2)覆蓋doTag方法

 */

@Override

public void doTag() throws JspException, IOException {

//向瀏覽器輸出客戶的ip地址

PageContext pageContext = (PageContext)context;

 

HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();

 

String ip = request.getRemoteHost();

 

JspWriter out = pageContext.getOut();

 

out.write("使用自定義標簽輸出客戶的IP地址:"+ip);

 

}

}

 

2)在web項目的WEB-INF目錄下建立itcast.tld文件,這個tld叫標簽庫的聲明文件。(參考核心標簽庫的tld文件)

 

<?xml version="1.0" encoding="UTF-8" ?>

 

<taglib 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-jsptaglibrary_2_1.xsd"

    version="2.1">

  <!-- 標簽庫的版本 -->

  <tlib-version>1.1</tlib-version>

  <!-- 標簽庫前綴 -->

  <short-name>itcast</short-name>

  <!-- tld文件的唯一標記 -->

  <uri>http://gz.itcast.cn</uri>

 

  <!-- 一個標簽的聲明 -->

  <tag>

    <!-- 標簽名稱 -->

    <name>showIp</name>

    <!-- 標簽處理器類的全名 -->

    <tag-class>gz.itcast.a_tag.ShowIpTag</tag-class>

    <!-- 輸出標簽體內容格式 -->

    <body-content>scriptless</body-content>

  </tag>

 

</taglib>

 

 

3) 在jsp頁面的頭部導入自定義標簽庫

    <%@taglib uri="http://gz.itcast.cn" prefix="itcast"%>

 

4) 在jsp中使用自定義標簽

<itcast:showIp></itcast:showIp>

 

2.3 自定義標簽的執行過程

問題: http://localhost:8080/day14/01.hellotag.jsp  如何訪問到自定義標簽?

 

前提: tomcat服務器啟動時,加載到每個web應用,加載每個web應用的WEB-INF目錄下的所有文件!!!例如。web.xml, tld文件!!!

1)訪問01.hellotag.jsp資源

2tomcat服務器把jsp文件翻譯成java源文件->編譯class->構造類對象->調用_jspService()方法

3)檢查jsp文件的taglib指令,是否存在一個名為http://gz.itcast.cntld文件。如果沒有,則報錯

4)上一步已經讀到itcast.tld文件

5)讀到<itcast:showIp> itcast.tld文件中查詢是否存在<name>showIp<tag>標簽

6)找到對應的<tag>標簽,則讀到<tag-class>內容

7)得到 gz.itcast.a_tag.ShowIpTag

 

構造ShowIpTag對象,然后調用ShowIpTag里面的方法

 

2.4 自定義標簽處理器類的生命周期

SimpleTag接口:

void setJspContext(JspContext pc)  --設置pageContext對象,傳入pageContext(一定調用)

通過getJspCotext()方法得到pageContext對象

void setParent(JspTag parent)  --設置父標簽對象,傳入父標簽對象,如果沒有父標簽,則不 調用此方法。通過getParent()方法得到父標簽對象。

void     setXXX()             --設置屬性值。

void setJspBody(JspFragment jspBody) --設置標簽體內容。標簽體內容封裝到JspFragment對象 中,然后傳入JspFragment對象。通過getJspBody()方法 得到標簽體內容。如果沒有標簽體內容,則不會調 用此方法

void doTag()                     --執行標簽時調用的方法。(一定調用)

 

2.5 自定義標簽的作用

1)控制標簽體內容是否輸出

2)控制標簽余下內容是否輸出

3)控制重復輸出標簽體內容

4)改變標簽體內容

5)帶屬性的標簽

步驟:

5.1 在標簽處理器中添加一個成語變量和setter方法

 

//1.聲明屬性的成員變量

private Integer num;

 

//2.關鍵點: 必須提供公開的setter方法,用於給屬性賦值

public void setNum(Integer num) {

this.num = num;

}

 

 

2.6 輸出標簽體內容格式

JSP   在傳統標簽中使用的。可以寫和執行jspjava代碼。

scriptless:  標簽體不可以寫jspjava代碼

empty:    必須是空標簽。

tagdependent : 標簽體內容可以寫jspjava代碼,但不會執行。

2.7 案例

核心標簽庫: c:if   c:choose+c:when+c:otherwise   c:forEach

高仿核心標簽庫

hellotag.jsp:

<%@ page language="java" import="java.util.*,com.base.others.*"
 pageEncoding="utf-8"%>
<%@taglib uri="http://top.handsomecui.hbc" prefix="hbc" %>
<%@taglib uri="http://top.handsomecui.simple" prefix="simple" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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 'hellotag.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>
  <%--使用自定義標簽 --%>
      <form action="#" method="post">
          <simple:login username="user" password="passwd"></simple:login>
          
      </form>
      <br/>
      <hbc:if test="${10>5 }">
          條件成立
      </hbc:if>
      <br/>
      <c:set var = "score" value="56"></c:set>
      <hbc:choose>
          <hbc:when test="${score>=90 && score <= 100 }">
              優秀
          </hbc:when>
          <hbc:when test="${score>=80 && score < 90 }">
              良好
          </hbc:when>
          <hbc:when test="${score>=700 && score < 80 }">
              一般
          </hbc:when>
          <hbc:when test="${score>=60 && score < 70 }">
              及格
          </hbc:when>
          <hbc:otherwise>
              不及格
          </hbc:otherwise>
      </hbc:choose>
      <hr/>
      <%
  //List
     List<Student>  list = new ArrayList<Student>();
     list.add(new Student("rose",18));
     list.add(new Student("jack",28));
     list.add(new Student("lucy",38));
     //放入域中
     pageContext.setAttribute("list",list);
     
     //Map
     Map<String,Student> map = new HashMap<String,Student>();
     map.put("100",new Student("mark",20));
     map.put("101",new Student("maxwell",30));
     map.put("102",new Student("narci",40));
     pageContext.setAttribute("list", list);
     pageContext.setAttribute("map", map);
      %>
      <%--
      <c:set var="list" value=list></c:set>
      <c:set var="map" value=map></c:set>
       --%>
      

      <hbc:forEach items="${list }" var="student">
      姓名:${student.name } - 年齡:${student.age } <br/>
      </hbc:forEach>
      <hbc:forEach items="${map }" var="entry">
      編號:${entry.key } - 姓名:${entry.value.name } - 年齡:${entry.value.age } <br/>
      </hbc:forEach>
      <hr/>
      <jsp:useBean id="stu" class="com.base.others.Student"></jsp:useBean>
      <jsp:setProperty property="name" name="stu" value = "張三"/>
      <jsp:getProperty property="name" name="stu"/>
      <hr/>
    <hbc:showip></hbc:showip>
    <hbc:tagdemo>HANDSOMECUI<br/></hbc:tagdemo>
        標簽余下內容
        
  </body>
</html>
View Code

if:

package com.bussy.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class If extends SimpleTagSupport{
    private boolean test;
    public void setTest(boolean test) {
        this.test = test;
    }
    @Override
    public void doTag() throws JspException, IOException {
        JspFragment jspbody = getJspBody();
        if(test){
            jspbody.invoke(null);
        }
    }
}
View Code

choose:

package com.bussy.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class Choose extends SimpleTagSupport{
    private boolean flag;
    
    public boolean isFlag() {
        return flag;
    }

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

    @Override
    public void doTag() throws JspException, IOException {
        setFlag(false);
        getJspBody().invoke(null);
    }
}
View Code

when:

package com.bussy.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class whenTag extends SimpleTagSupport{
    private boolean test;
    public void setTest(boolean test) {
        this.test = test;
    }
    @Override
    public void doTag() throws JspException, IOException {
        JspFragment jspBody2 = getJspBody();
        Choose parent = (Choose)getParent();
        if(test){
            parent.setFlag(test);
            jspBody2.invoke(null);
        }
    }
}
View Code

otherwise:

package com.bussy.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class otherwiseTag extends SimpleTagSupport{
    @Override
    public void doTag() throws JspException, IOException {
        Choose parent = (Choose)getParent();
        boolean test = parent.isFlag();
        if(!test){
            getJspBody().invoke(null);
        }
    }
}
View Code

foreach:

package com.bussy.tag;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.base.others.Student;

public class foreachTag extends SimpleTagSupport{
    private Object items;

    public void setItems(Object items) {
        this.items = items;
    }
    public void setVar(String var) {
        this.var = var;
    }
    private String var;
    @Override
    public void doTag() throws JspException, IOException {
//        if(items instanceof List){
//            List list = (List)items;
//            for(Object e:list){
//                ((PageContext)this.getJspContext()).setAttribute(var, e);
//                getJspBody().invoke(null);
//            }
//        }else if(items instanceof Map){
//            Map mp = (Map)items;
//            Set<Entry> entrySet = mp.entrySet();
//            for(Entry entry:entrySet){
//                ((PageContext)this.getJspContext()).setAttribute(var, entry);
//                getJspBody().invoke(null);
//            }
//        }
//        
        Collection coll = null;
        if(items instanceof List){
            coll = (Collection) items;
        }
        if(items instanceof Map){
            coll = ((Map)items).entrySet();
        }
        for(Object obj:coll){
            ((PageContext)this.getJspContext()).setAttribute(var, obj);
            getJspBody().invoke(null);
        }
    }
}
View Code

3 編碼實戰

3.1 JavaBean

JavaBean,  咖啡豆。 JavaBean是一種開發規范,可以說是一種技術。

 

 JavaBean就是一個普通的java類。只有符合以下規定才能稱之為javabean

  1)必須提供無參數的構造方法

  2)類中屬性都必須私有化(private)

  3)該類提供公開的getter setter方法

 

JavaBean的作用: 用於封裝數據,保存數據。

訪問javabean只能使用gettersetter方法

 

JavaBean的使用場景:

1)項目中用到實體對象(entity)符合javabean規范

2EL表達式訪問對象屬性。${student.name}  調用getName()方法,符合javabean規范。

3jsp標簽中的屬性賦值。 setNumInteger num)。符合javabean規范。

4jsp頁面中使用javabean。符合javabean規范

 

問題:

         以下方法哪些屬於javabean的規范的方法? 答案 :( 1356  )

注意: boolean類型的get方法名稱叫 isXXX()方法

1getName()    2)getName(String name)

3)setName(String name)   4)setName()

5) setFlag(boolean flag)   6)isFlag()

 

3.2 web開發模式

 

總結:

 1)自定義標簽

自定義標簽作用

 案例

2)編碼實戰

JavaBean規范: 三點

    MVC開發模式:

Model - JavaBean實現。用於封裝業務數據

View - Jsp實現。用於顯示數據

Controller-  servlet實現。用於控制modelview

三層結構:

dao層: 和數據訪問相關的操作

service層: 和業務邏輯相關的操作

web層: 和用戶直接交互相關的操作(傳接參數,跳轉頁面)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM