qiyadeng

专注于Java示例及教程
posts - 84, comments - 152, trackbacks - 0, articles - 34

SCWCD笔记转载

Posted on 2005-10-23 23:50 qiyadeng 阅读(1485) 评论(0)  编辑  收藏 所属分类: Collection

Cloud's SCWCD 1.4 筆記

1:The Servelt Technology Model
 
1. HttpServlet class:

public class MyServlet extends HttpServlet { 

    public void init() throws ServletException {  } 
 //只執行一次

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  }  
    //  如果被overwrite時有可能不會呼叫doXXX()的method,要留意題意的陷阱

    protected void doXXX(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  } 
    //  XXX代表Get,Post...etc
    //不見的程式中一定要寫這個method,不寫的話它會繼承GeneralServlet.doXXX()

    public void destroy() {  }
 //只執行一次

}
 

2. Http的method
POST method可用來處理上傳檔案的問題。
OPTIONS
method可以列出目前處理的HTTP method為何(ex:TRACE,GET,POST)。
GET、PUT、HEAD method有idempotent的特質。
 
3. HTML FORM預設使用 HTTP GET request
 
4. ServletResponse的method
void setContentType(String type)
PrintWriter getWriter()  //
取得 response 的 text stream 傳送字元資料
ServletOutputStream getOutputStream()  //
取得 response 的 binary stream 傳送任何資料

Http
ServletResponse的method
void addHeader(String headerName, String value)
void addIntHeader(String headerName, int value)
void addDateHeader(String headerName, long millisecs)
void sendRedirect(String newURL)
void sendError(int status_code)
void sendError(int status_code, String Message)
void setStatus(int sc)
void setStatus(int sc,
String Message)
void addCookie(Cookie cookie)  //輸入的參數型別是Cookie,要留意題意的陷阱

跟HTTP protocal相關的method屬於HttpServletResponse,其它的methods通通是屬於ServletResponse
 
5. ServletRequest的method
String getParameter(String paramName)
String[] getParameterValues(String param)
Enumeration getParameterNames()
BufferedReader getReader()  //
取得 request 的 text stream 可用來接收表單上傳的文字檔案
ServletInputStream getIutputStream()  //取得 request 的 binary stream 可用來接收表單上傳的任何檔案

HttpServletRequest的method
String getHeader(String headerName)
int getIntHeader(String name)
long getDateHeader(String name)
Enumeration getHeaders(String name)
Enumeration getHeaderNames()
Enumeration getHeaderValues(String headerName)
public Cookie [] getCookies()  //傳回的是Cookie的陣列,要留意題意的陷阱

跟HTTP protocal相關的method屬於HttpServletRequest,其它的methods通通是屬於ServletRequest
 
6. Servlet life-cycle:
Load
class --> Creates instance of class --> calling the init method --> calling the service method --> calling the doXXX method --> calling the destroy method
 
7. 繼承GenericServlet的class必需實作service() method
繼承HttpServlet的class可以不實作service()、doXXX() method
 
2: The Structure and Deployment of Web Applications
 
1. 要背web.xml中紅字部份的義意與用法
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”
  version=”2.4”>

  <display-name>A Simple Application</display-name>
       
  <context-param>
   <param-name>Webmaster</param-name>
   <param-value>webmaster@mycorp.com</param-value>
  </context-param>

     <jsp-config>
      <taglib>
       <taglib-uri>...</taglib-uri>
       <taglib-location>...</taglib-location>
      </taglib>
      <jsp-property-group>
       <url-pattern>...</url-pattern>
       <el-ignored>true/false</el-ignored>                       //設成true時,JSP若有EL expression會被當作純文字來處理
       <scripting-invalid>true/false</scripting-invalid>    //設成true時,JSP若有scripting的語法會使JSP在Compile成Servlet時產生translation error
       <include-prelude>...</include-prelude>
       <include-code>...</include-coda>
       <is-xml>true/false</is-xml>
      </jsp-property-group>
     </jsp-config>


  <servlet>
   <servlet-name>catalog</servlet-name>
   <servlet-class>com.mycorp.CatalogServlet</servlet-class> or <jsp-file>/test.jsp</jsp-file>
   <init-param>
    <param-name>catalog</param-name>
    <param-value>Spring</param-value>
   </init-param>

            <load-on-startup>1</load-on-startup>

   <security-role-ref>
    <role-name>MGR</role-name>
    <role-link>manager</role-link>
   </security-role-ref>
  </servlet>
  <servlet-mapping>
   <servlet-name>catalog</servlet-name>
   <url-pattern>*.*</url-pattern>  //要了解url-pattern的設定方式
  </servlet-mapping>

  <security-role>
   <role-name>manager</role-name>
  </security-role>

  <security-constraint>
   <web-resource-collection>
    <web-resource-name>SalesInfo</web-resource-name>
    <url-pattern>/salesinfo/*</url-pattern>
    <http-method>GET</http-method> 
                //可以0到多個<http-method>,當0個時,代表外界沒有人可以用http的方法存取設限的資料(其餘方法如forward,include可被內部程式叫用)
   </web-resource-collection>
   <auth-constraint>
    <role-name>manager</role-name>    
                //可以0到多個<role-name>或是設成"*",當設成"*"時所有人都可以存取,當設成<auth-constraint/>,沒有人可以存取
   </auth-constraint>
   <user-data-constraint>
    <transport-guarantee>NONE/CONFIDENTIAL/INTEGRAL</transport-guarantee>
                //
NONE implies HTTP;CONFIDENTIAL,INTEGRAL imply HTTPS
   </user-data-constraint>
  </security-constraint>

        <login-config>
           <auth-method>
BASIC/FORM/DIGEST/CLIENT-CERT</auth-method>          
          //當<auth-method>為FORM時才需設定<form-login-config>
           <form-login-config>
              <form-login-page>/formlogin.html</form-login-page>
              <form-error-page>/formerror.html</form-error-page>
           </form-login-config>
           //當<auth-method>為FORM時才需設定<form-login-config>
        </login-config>

  <session-config>
   <session-timeout>30</session-timeout>  //單位是分鐘,當值 <= 0 時表示不會自動 timeout
  </session-config>

  <mime-mapping>
   <extension>pdf</extension>
   <mime-type>application/pdf</mime-type>
  </mime-mapping>

  <welcome-file-list>
   <welcome-file>index.jsp</welcome-file>  //一個至多個<welcome-file>,被叫用時照設定時的先後順序
  </welcome-file-list>

  <error-page>
   <error-code>404</error-code> or <exception-type>...</exception-type>
   <location>/404.html</location>
  </error-page>

        <filter>
           <filter-name>Example Filter</filter-name>
           <filter-class>examples.ExampleFilter</filter-class>
        </filter>

        <filter-mapping>
           <filter-name>Example Filter</filter-name>
           <servlet-name>FilterMe.jsp</servlet-name> or <url-pattern>/myContext/*</url-pattern>  //<url-pattern>的優先權高於<servlet-name>
           <dispatcher>REQUEST/INCLUDE/FORWARD/ERROR</dispatcher>  //一個至多個<dispatcher>
        </filter-mapping>

       <listener>
           <listener-class>Listener 的類別名稱</listener-class>  //一個至多個<listener-class>,要注意多個listener時的寫法
       </listener>
       <listener>
           <listener-class>Listener 的類別名稱</listener-class>
       </listener>
</web-app>
 

2. 要了解Web application的檔案目錄架構(ex:/WEB-INF/裡可以放那些東西...etc)
 
3: The Web Container Model
 
1. 只有request scope的資料在傳送時是thread safe
 
2. Filter class
public class TimingFilter implements Filter
{
    public void init(FilterConfig filterConfig) throws ServletException
    {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException,IOException
    {
        chain.doFilter(request, response);  //這行的程式非必填的程式碼,也可以不寫
    }

    public void destroy()
    {
    }
}
 
3. listener class
分成三類:
ServletContextListener,HttpSessionListener,ServletRequestListener
注意Method的不同處:HttpSessionListener.sessionCreated(...),ServletContextListener.contextInitialized(...),ServletRequestListener.requestInitialized(...)
 
4. attribute listener class
分成三類,名稱上相似:都叫XXX
AttributeListener
提供的Method名稱一樣:attributeAdded(...),attributeRemoved(...),attributeReplaced(...)
 
5. HttpSessionAttributeListener.某個Method(HttpSessionBindingEvent e)
HttpSessionBindingListener.某個Method(HttpSessionBindingEvent e)
二者輸入參數的型別都必為HttpSessionBindingEvent
 
6. HttpSessionBindingListener的使用不需在web.xml裡作宣告 ,要很清楚HttpSessionBindingListener的使用方式
 
7. listener本身是個Interface,所以可以實作一個class繼承多個不同的listener
 
8. HttpSessionActivationListener被使用在多個JVM的環境下
 
9. RequestDispatcher rd=request.getRequestDispatcher(相對或絕對路徑)
RequestDispatcher rd=getServletContext().getRequestDispatcher(絕對路徑)  //如果設成相對路徑還是可以Compile,return值是null
 
10. RequestDispatcher ServletRequest.getRequestDispatcher(String path)  //來自ServletRequest,不是HttpServletRequest
RequestDispatcher ServletContext.getRequestDispatcher(String path)
4: Session Management
 
1. HttpSession的method
Object getAttribute(String name)
void setAttribute(String name, Object  value)
void removeAttribute(String name)
Enumeration getAttributeNames()
void
invalidate()
boolean isNew()

void
setMaxInactiveInterval(int seconds)  //單位是,當值 < 0 時表示不會自動 timeout
 
2. HttpServletRequest.getSession(false)在取得HttpSession時,如果HttpSession不存在,不會自動產生,會return null
 
3. Sesssion tracking mechanisms:Cookies,SSL Sessions,URL Rewriting
4. HttpServletResponse的URL rewriting Method
String encodeURL(String url)
String encodeRedirectURL(String url)
 
5: Web Application Security
 
1. Web Application Security的特質有四種:
(a)authentication(認証)
(b)authorization(授權)
(c)data integrity(資料完整性):指資料從發送方傳送到接收方,在傳送過程中資料不會被篡改。
(d)confidentiality(私密性):指除了資料接收方以外,其他人不會存取到這個敏感性資訊的能力及權限。
 
2. HttpServletRequest中與驗証使用者相關的Method
String getRemoteUser()
java.security.Principal getUserPrincipal()
boolean isUserInRole(String role)
 
3. Authentication types有下列四種
BASIC:傳輸的資料不加密(不安全),不需自訂輸入帳號與密碼的Form(Browser會pop up一個輸入的表單)
DIGEST:傳輸的資料加密(安全),不需自訂輸入帳號與密碼的Form(Browser會pop up一個輸入的表單)
FORM:傳輸的資料不加密(不安全),要自訂輸入帳號與密碼的Form
CLIENT-CERT:用Public Key Certificate的機制(安全)
 
6: The JavaServer Pages (JSP) Technology Model
 
1.
Elements
語 法
描 述
TEMPLATE TEXT 要輸出"<%"則須寫"<\%"來 Any text that is not JSP "code"; usually HTML or XML
SCRIPTING comments <%-- 註解內容 --%> A JSP comment.
撰寫JSP的註解文字
directives <%@ 標準指令 %> A JSP directive.
設定JSP網頁整體組態 (6.2)
declarations <%! 宣告式 %> A Java declaration that becomes part of the servlet class.
宣告JSP內所使用的變數或方法
scriptlets <% 程式碼 %> Java code that is inserted in the jspService method.
撰寫任何JAVA程式碼
expressions <%= 運算式 %> Java code that generates text printed to the response stream.
相當於out.print(運算式);
ACTIONS/TAGS <jsp:動作項目 屬性="值"/> XML-based tags that perform dynamic actions while generating the response. There are three fundamental variations:
 1. An emtpy tag. Notice the '/' at the end of the tag.
  <my:tag attr='value' />

 2. A tag with a body.
  <my:tag>
   <%-- JSP code --%>
  </my:tag>


 3. Nested tags, use standard HTML/XML nesting rules.
  <my:tag1>
   <my:tag2>...</my:tag2>
  </my:tag1>

目的在減少JAVA程式碼
EXPRESSION LANGUAGE ${ EL-expr } A rich language for generating "presentation content".
'${' is the opening token of an EL expression and '}' is the closing token.
 
2.
JSP SCRIPTING DIRECTIVE 範例
page <%@page import="java.text.*,java.io.*" session="false" contentType="text/html" isELIgnored="true" %>
include <%@include file="tra.jsp" %>
taglib <%@taglib prefix="myTag" uri="http://localhost:8080/taglib" %> ( prefix不可使用 jspjspxjavaservletsunsunw)
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> (使用tag file時才要用tagdir的屬性)
 
3.
語 法 比 較 SCRIPTING LANUAGE XML-based document
DIRECTIVE <%@標準指令 屬性="值"%>
<%@page import="java.util.*"%>
<jsp:directive.標準指令 屬性="值"%>
<jsp:directive.page import="java.util.*">
DECLARATION <%! 初始宣告 %>

<%! int i=1;%>
<jsp:declaraction>
        初始宣告
</jsp:declaration>
<jsp:declaraction>
         int i=1;
</jsp:declaration>
SCRIPTLET <% JAVA程式 %>

<% if (X>0)
       {
           result=true;
       }
%>
 
<jsp:scriptlet>
       JAVA程式
</jsp:scriptlet>

 

<jsp:scriptlet>    
   if (X>0)
          {
              result=true;
          }
</jsp:scriptlet>
EXPRESSION <%= 運算式 %>

<%= new Date()%>

 
<jsp:expression>
         運算式
</jsp:expression>
<jsp:expression>
          new Date()
</jsp:expression>
COMMENT <%-- JSP註解 --%> <!-- 使用HTML註解-->

4. JSP page life cycle(JSP的本質是Servlet):
JSP page translation --> JSP page compilation --> load class --> create instance --> call the jspInit method(可以被改寫)--> call the _jspService method(不能被改寫) --> call the jspDestroy method(可以被改寫)
 
5.
JSP隱含物件 介面或類別 用途 範圍
request javax.servlet.http.HttpServletRequest Client送出的request request
response javax.servlet.http.HttpServletResponse 送回Client的response page
out javax.servlet.jsp.JspWriter response的(output Stream) page
session javax.servlet.http.HttpSession 存取某user在HTTP連線階段內容 session
config javax.servlet.ServletConfig 該JSP網頁內的Servlet page
application javax.servlet.ServletContext 含WEB應用程式內的ServletContext 物件 application
page java.lang.Object 相當於JAVA語言中的"this" page
pageContext javax.servlet.jsp.PageContext 包含JSP網頁中, 單一request的環境 page
exception java.lang.Throwable 只能在JSP錯誤處理網頁中使用 page

6.
include 用途 備註
<%@include file="relativeURL" %> Translation Time靜態include進來的HTML或JSP,不能是Servlet
  • 此法效能較好
  • 只能使用原有request參數,不能靠Query String增加參數
<jsp:include page="relativeURL"> Run Time時將HTML或JSP執行結果動態include進來,可以指向Servlet
  • 會自動UPDATE
  • RunTime可使用<jsp:param name="" value=""/>來傳遞參數

7. include directive不能指向 servlet,include action, forward action 可以指向 servlet
 
8.

JSP轉譯成Servlet的class
public class MyServlet
_jsp extends XXXXXX

    public void jspInit() {  } 
    // 這個Method繼承自javax.servlet.jsp.JspPage這個interface
 //只執行一次,可以在JSP檔案中用declaration的方式改寫

    public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  }
    //這個Method繼承自javax.servlet.jsp.HttpJspPage這個interface
    //不能在JSP檔案中改寫

    public void jspDestroy() {  }
    //這個Method繼承自javax.servlet.jsp.JspPage這個interface
 //只執行一次,可以在JSP檔案中用declaration的方式改寫

}
 

9. <%  = "Hello" ; %>  //會產生exception,要了解exception的原因
 
10. 下列的JSP DECLARATION是合法的
<%!
      Hashtable ht = new Hashtable();
      {
           ht.put("max", "10");                              // { }拿掉會導致Compile error
      }
%>

 
7: Building JSP Pages Using the Expression Language (EL)
 
1.

Implicit objects provided by the expression language

Implicit Object

Content

applicationScope A collection of scoped variables from applications scope
pageScope A collection of all page scope objects
requestScope A collection of all request scope objects
sessionScope A collection of all session scope objects
pageContext The javax.servlet.jsp.PageContext object for the current page
initParam A collection of all application parameter names
param A collection of all request parameters as strings
paramValues All request parameters as collections of strings
header HTTP request headers as strings
headerValues HTTP request headers as collections of strings
cookie A collection of all cookies

2. EL operators: property access (the . operator), collection access (the [] operator).
. operator只能用在物件型別為Map或JavaBean,[] operator則無任何限制
 
3. EL operators中比較需要注意之處
Relational :
==, eq, !=, ne, <, lt, >, gt, >=, ge, <=, le
Empty : ${!empty param.Add}
Conditional :  A ? B : C
 
4. EL function的寫法

package mypkg;
    public class MyLocales {
    ...
    public static boolean equals( String a, String b ) {   //必為 public static
        return a.equals(b);
  }
}
 
5. EL function在xxx.tld中的宣告方式
<function>
    <name>equals</name>
    <function-class>mypkg.MyLocales</function-class>
    <function-signature>boolean equals( java.lang.String, java.lang.String )</function-signature>
</function>
 
6. EL expression的出題陷阱
${10 * 1.5}       //結果是15.0
${123 / 0}         //結果是Infinity
${0 / 0}             //結果是NaN
${"" + 1}           //結果是1
${" " + 1 }         //產生Exception
${123 % 0}   
   //產生Exception
${0 % 0}           //產生Exception
 
8: Building JSP Pages Using Standard Actions
 
1.
JavaBean
語 法
描 述
jsp:useBean <jsp:useBean id="JavaBean的變數名稱"
                class="完整的package.類別名稱 "
                type=" id屬性值的變數型別 "
                scope=" 存取範圍 " />

<jsp:useBean id="cs" class="scwcd.CsClass" scope="page" />
 
相當於:
       <%@ page import="scwcd.*" %>
       <% CsClass cs=new CsClass(); %>

scope 可以是
      application (相當ServletContext 物件),  
      session (相當HttpSession 物件 ),
      request (相當ServletRequest 物件),
      page (相當PageContext 物件)
jsp:setProperty <jsp:setProperty name="JavaBean的變數名稱"
                    property="欲設定的JavaBean屬性名稱"
                    param="HTTP請求所傳的參數名稱"
                    value=" 參數的數值"/>

<jsp:setProperty name="cs" property="*" />

 
自省機制Introspection:
      1.可用( property="*")全部設完JavaBean所有方法
      2 但是對應的HTTP <form>中的個數與名稱都要一致
jsp:getProperty <jsp:getProperty name="JavaBean的變數名稱"
                    property="欲設定的JavaBean屬性名稱" />

<jsp:getProperty name="cs" property="name" />

 
相當於:
       <%=cs.getName(); %>

 
JavaBean:
目的   - 1.減少JSP中Java程式碼   2.REUSABLE              3.便於網頁維護開發
規定   - 1.他是public類別            2. constructor無參數      3.(g)setXXX()符合命名規則

初始化- 若是scope中的Name Space無相同id名稱, 才會new instance (和初始化)
           <jsp :useBean id="cs" class="scwcd.CsClass" scope="page">
                <jsp:setProperty name="cs" property="name" />
           </jsp:useBean>
 

2.
傳遞型
Standard Action
程 式
對應的JSP Scriptlet Tag
jsp:forward <jsp:forward page="欲轉往的JSP或HTML" />

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

 
1.<% RequestDispatcher rd=
        request.getRequestDispatcher("相對或絕對路徑");
        rd.forward(request,response);
   %>

2. <% pageContext.forward("Banner.jsp"); %>
jsp:include <jsp:include page="欲加入的JSP或HTML" />

<jsp:include page="include.jsp" />

 
1.<% RequestDispatcher rd=
        request.getRequestDispatcher("相對或絕對路徑");
        rd.include(request,response);
   %>

2. <% pageContext.include("include.jsp"); %>
jsp:param <jsp:param name="參數名" value="參數值" />

<jsp:forward page="Banner.jsp">
    <jsp:param name="Wellcome" value="Hello" />
</jsp:include>
 
<% String title=request.getParameter("Wellcome"); %>
 
3. <jsp :useBean id="persion" type="scwcd.Person" class="scwcd.Employee" />
//scwcd.Person是scwcd.Employee的super class,利用此方法可以達到polymorphic的效果
 
4. 在<jsp:useBean ... />中
If type is used wtihout class,the bean must already exit.不然會產生exception.
If class is used(with or without type) the class must Not be  abstract or interface,and must have a public no-arg constructor

<jsp:useBean id="mybean" beanName="my.app.MyBean" type="my.app.MyBean" />,beanName只能與type同時出現
 
5. <% out.flush() %>
<jsp:forward .../>
此種寫法會使forward失效,不被執行,而且不會產生exception
 
9: Building JSP Pages Using Tag Libraries
 
1. JSTL的Core Tag Library

<c:out value="${username}" escapeXml="false" />  //要了解escapeXml代表的義意

<c:
set var="four" scope="session" value="${3+1}" />


<c:
remove var="dommed" scope="session" />

<c:catch var="e">      //var的值可以在catch block之外被使用,<c:catch>的功能與try...catch寫法中的catch相似
... Program code that may throw an exception ...
</c:catch>
<c:
if test="${e != null}"> The caught exception is <c:out value="${e}"/> </c:if>
<c:if test="${e == null}"> No exception was thrown </c:if>

<c:choose>
    <c:
when test="${error1}"> Error1 </c:when>     //一定要有test這個attribute
    <c:when test="${error2}"> Error2 </c:when>
    <c:when test="${error3}"> Error3 </c:when>
    <c:
otherwise> Otherwise </c:otherwise>            //不能有test這個attribute,此外<c:otherwise>這個tag非必需
</c:choose>


<c:forEach items="${user.medicalConditions}" var="aliment">
    <c:out value="${aliment}"/>   //如果這行改成<%=aliment %>會產生exception,不能用scriptling來存取<c:forEach>中的值
</c:forEach>

<c:forTokens items="a;b;c;d" delims=";" var="current">
    <c:out value="${current}"/>
</c:forTokens>

<c:url value="buy.jsp">     //<c:url>的功能是url rewriting,不是url encoding,url帶參數時要用範例中的寫法
    <c:param name="stock" value="IBM"/>
</c:url>

<c:import context="/other" url="/directory/target.jsp"/>   //可以import其它Web application的的資料
    <c:param name="first" value="one"/>
    <c:param name="second" value="two"/>
</c:import>

<c:redirect context="/brokerage" url="/buy.jsp">         //可以redirect其它Web application的的資料
    <c:param name="stock" value="IBM"/>
</c:redirect>

 
2. <c:set target="${myDog}" property="dogName" value="可魯" />
target必需放Object,不能是String。利用此法可以設定Bean的property。
 
10: Building a Custom Tag Library
 
1. tag file與simple tag相似,tag file在執行前會先被轉換成simple tag才被執行。二者在接收到新的request時都會產生新的instance。二者的body content設定都不能設為JSP
 
2. tag support與body tag support相似,二者都只產生一個instance被多個request共用(跟Servlet的架構相似)
 
3. classic tag
Method Return Value/Type
Tag.doStartTag() SKIP_BODYEVAL_BODY_INCLUDE, (EVAL_BODY_BUFFERED, implements BodyTag)
IterationTag.doAfterBody() SKIP_BODYEVAL_BODY_AGAIN
Tag.doEndTag() SKIP_PAGEEVAL_PAGE
 
4. tag support與body tag support用 PageContext class 取得 implicit variable
simple tag用getJspContext() method取得 implicit variable
 
5. 抓取parent tag的method
Tag getParent()
static Tag findAncestorWithClass (Tag from, java.lang.Class klass)
 
6. Simple tag class的寫法
public class MySimpleTag extends SimpleTagSupport
{
   StringWriter sw = new StringWriter();

   public void doTag() throws JspException, IOException
    {
       getJspContex().getOut().write(sw.toString());
       getJspBody().invoke(null);
    }
}

Tag support class的寫法(body tag support class的寫法與它相似)
public class MyTag extends TagSupport
{
    public int doStartTag() throws JspException{
        ...
        return
SKIP_BODY/EVAL_BODY_INCLUDE;
    }

    public int doAfterBody() throws JspException{
        ...
        return
SKIP_BODY/EVAL_BODY_AGAIN ;
    }

    public int doEndTag() throws JspException{
        ...
       return
SKIP_PAGE/EVAL_PAGE;
    }
}

要了解simple tag與classic tag二者在寫法上的不同處   
 
7. Tag file的寫法
<%@ attribute name="fontColor" required="true" rtexprvalue="true" %>
<%@ tag body-content="empty/tagdependent/scriptless"%>
<font color="${fontColor}"><jsp:doBody/></font><br>

Tagfile可以使用的directives: taglib, include, tag, attribute, variable.
 
8. tag class在xxx.tld的宣告方式
<uri>...</uri>
<tag>
   <name>callEJB</name>
   <tag-class>com.example.web.tags.EJBCallTagHandler</tag-class>
   <body-content>empty/tagdependent/scriptless/JSP</body-content>
   //設成empty時,如果JSP檔裡的tag body卻包含資料,會在執行時產生Exception
   //設成scriptless時,如果JSP檔裡的tag body卻包含scripting的敘述,會在執行時產生Exception
   //設成tagdependent的話表示不作任何處理,直接將本體內容傳給標籤庫,由標籤庫自行處理本體內容
   <attribute>
      <name>user</name>
      <required>true/false/yes/no</required>            //設成true時,如果JSP檔裡面沒有設定這個attribute會在執行時產生Exception
      <rtexprvalue>true</rtexprvalue>   //設成false時,如果JSP檔裡面有rtexprvalue的寫法會在執行時產生Exception
   </attribute>
</tag>
 
9. SkipPageException stops only the page thata directly invoked the simple tag
 
10. Simp tag life cycle
Load class --> Instantiate class --> call setJspContext() method --> call setParent() method --> call attribute setters(不一定會執行) --> call setJspBody()(不一定會執行) --> call doTag()
 
11. classic tag life cycle
Load class --> Instantiate class --> call setPageContext() method --> call setParent() method --> call attribute setters(不一定會執行) --> call doStartTag() --> call doAfterBody() --> call doEndTag()
 
12. SimpleTag在xxx.tld中的<body-content>設定不能設為JSP,body content不可以使用sriptlet的語法
Tag file的<%@ tag body-content="..."%>不能設為JSP,body content不可以使用sriptlet的語法
 
13. <prefix:sometag>
    <jsp:attribute name='attrA'>val1</jsp:attribute>   //不能寫成<jsp:attribute name='attrA' value='val1' />,要注意
</prefix:sometag>
 
14. public class MyTag extends TagSupport
{
    public int doStartTag() throws JspException{
        if(somecondition)
        {
            return EVAL_BODY_INCLUDE;
        }
        else
        {
            PageContext.forward(...) or PageContext.include(...)  //有些考題會在這部份作陷井,要注意
        }
    }
    ...etc
}
 
15. If we extend BodyTagSupport, then we use BodyTagSupport.getPreviousOut() to get the "previous" or "enclosing" JspWriter.
 
16. 如果tag class被包在jar file裡面。在使用tag class之前不需在web.xml作taglib的設定。只要在JSP檔裡宣告<%@ taglib prefix...etc %>就可以使用這個tag
 
11: J2EE Patterns
 
1. Business Delegate Pattern(參照HeadFirstSevlet&JSP p:746)
 
2. Service Locator Pattern(參照HeadFirstSevlet&JSP p:747)
 
3. Transfer Object Pattern(參照HeadFirstSevlet&JSP p:748)
 
4. Intercepting Filter Pattern(參照HeadFirstSevlet&JSP p:749)
 
5. MVC Pattern(參照HeadFirstSevlet&JSP p:750)
 
6. Front Controller Pattern(參照HeadFirstSevlet&JSP p:751)
 
12: 雜七雜八無法分類的部份
 
1. Servlet與Filter class寫法相似,二者在web.xml的設定方式亦相似
 
2. EL function與tag class二者在xxx.tld的設定方式相似
 
3. 要能分出下面三者的差異
<%@ include file="myTest.jsp" %>                          //Static的include方式
<jsp:include page="myTest.jsp"/>                             //dynamic的include方式
<c:import url="/myTest.jsp" context="/OtherSite"/>   //dynamic的include方式,而且可以inlcude不同Web application的資料
 
4. 在Deployment Descriptoer中呼叫的先後順序:listener->filter->servlet
 
5. Both - GenericServlet class and ServletContext interface, provide methods log(String msg) and log(String, Throwable) that write the information to a log file.
 
6. JSP Page directive中比較少見的attribute:language,extends,buffer,autoFlush,info
 
7. java.net.URL ServletContext.getResource()
java.io.InputStream ServletContext.getResourceAsStream()
 
8. ServletException provides the getRootCause() method that returns the wrapped exception. It's return type is Throwable, so you have to cast it to appropriate business exception type.
 
9. <servlet-mapping>
     <servlet-name>XServlet</servlet-name>
     <url-pattern>*.x</url-pattern>
</servlet-mapping>
<servlet-mapping>
     <servlet-name>YServlet</servlet-name>
     <url-pattern>/y/*</url-pattern>
</servlet-mapping>
 
/y/test //執行YServlet
/y.x //執行XServlet
/y/test.x //執行YServlet.This is because an extension mapping is considered ONLY if there is no path matching.
/y/x //執行YServlet
/y/test.jsp //執行YServlet

要了解HeadFirstSevlet&JSP p:588的考題練習
 
10. Request URL = protocol://host:port + contextpath + requestpath + pathinfo

註:紅字部份是特別要注意的考題陷井


只有注册用户登录后才能发表评论。


网站导航: