SCWCD笔记转载

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
  [url]http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd[/url]”
  version=”2.4”>
  <display-name>A Simple Application</display-name>
       
  <context-param>
   <param-name>Webmaster</param-name>
   <param-value>[email][email protected][/email]</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
注:红字部份是特别要注意的考题陷井
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章