12th Chapter Web12-jsp&el&jstl

Source: Internet
Author: User

Today's mission
? Display of commodity information
Teaching navigation
Teaching objectives
Mastering the basic use of JSP
Mastering the use of El's expressions
Master the use of common JSTL tags
Teaching methods
Case-driven approach
1.1 Previous lesson Content review:
Cookie: Is the session technology that saves data to the client browser.

  • Get Cookie:request.getCookies () from the browser;
  • Write back Cookie:response.addCookie (cookie cookie) to the browser;
  • Related APIs for cookies:
    • SetPath (String path); --/DAY11/DAY11/AAA
    • Setmaxage (int time); -Effective duration.
    • SetDomain (String domain);
  • Classification of Cookies:
    • Session Level Cookie: Session level when the browser is closed, the cookie is destroyed. Default
    • Persistent level cookie: Set a cookie that is valid for a long time and will not be destroyed when the browser is closed.
      Session: This is the conversation technology that saves the data to the server side. Based on cookie writeback SessionID.
  • Session Access data:
    • SetAttribute (String name,object value);
    • GetAttribute (String name);
  • Session Scope:
    • The scope of the session: one conversation. (Multiple requests)
    • Session Life cycle:
      • Create: The session is created the first time you call getsession.
      • Destroyed:
        • Shut down the server abnormally.
        • Session expires
        • When you call the Invalidate method manually
          1.2 Case One: Displays information about the item in the JSP page. 1.2.1 Requirements:
          The database contains a lot of product information, and now the information of the product is displayed to the page.
          1.2.2 Analysis: 1.2.2.1 Technical Analysis:
          "Overview of JSPs"
          ? What is a JSP:
  • Java servers pages (Java server-side pages)
    ? Why learn to JSP:
  • The servlet introduced by Sun is flawed and has no way to compete with asp,php. Launched the Dynamic Web development technology JSP.
    ? Using JSP:
  • JSP = HTML + Java code + JSP's own stuff.
    ? The process of executing the JSP:
  • The JSP translates into a servlet, compiles the servlet's class, and generates a class file. Get executed.
    "Script for JSP"
    ? <%! %>: Translates into a member content in a servlet. Define variables, methods, classes.--not recommended.
    ? <%%>: Translated into the content inside the service method in the servlet. Defining classes, variables
    ? <%=%>: Translated into servlet in the service method Out.print ();
    "Comments for JSP"-understanding
    ? HTML comment:<!--Comment--
    ? Comments for Java code://single-line comment/ multiline comment//* document Comment /
    ? Comment for JSP: <%--JSP annotation--%>
    "Instructions for JSP"
    ? Syntax of the instruction:
    <%@ directive Name Property name = "Property Value" Property name = "Property value" ...%>
    ? There are three directives in the JSP: Page directive, include directive, taglib directive.
    ? JSP in Page directive: <%@ page%>--set JSP.
  • The language used in the language:jsp script. Now only Java can be written.
  • ContentType: Sets the encoding of the default character set used by the browser when opening this JSP.
  • Pageencoding: The encoding that the servlet saves to the hard disk after the settings file is saved to the local hard disk and the servlet is generated.
  • Import: A class object is introduced into the JSP. But import can appear multiple times.
    <% @page import= "Java.util.ArrayList"%>
    <% @page import= "Java.util.List"%>
  • Extends: Sets the class that the JSP inherits after it is translated into a servlet, the default value: Org.apache.jasper.runtime.HttpJspBase, this value is to be modified, this class must be a subclass of HttpServlet
  • AutoFlush: Sets the cache of the JSP to be automatically brushed out. true: Auto-swipe out.
  • Buffer: Sets the size of the buffer for the JSP, default 8KB.
  • Session: Sets whether the session object can be used directly in the JSP. The default value is true.
  • Iselignored: Sets whether the El expression is ignored in the JSP. The default value is false and not ignored.
  • ErrorPage: Tips for setting up an error-friendly page.
  • Iserrorpage: Displays the JSP error message through this setting.
    • Set the global error-friendly page:
      • Set in Web. xml:
        <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
        </error-page>
        <error-page>
        <error-code>500</error-code>
        <location>/500.jsp</location>
        </error-page>
        ? Include directive in JSP: Indicates that the JSP contains additional pages.
        <%@ include file= "logo.jsp"%>
        <%@ include file= "menu.jsp"%>
        <%@ include file= "footer.jsp"%>
        ? TAGLIB directive in JSP: instructs JSP to introduce tag library.
        <%@ taglib uri= "The path of the URI of the label" Prefix= "the alias of the label"%>
        "Built-in objects for JSPS (* * * * * * *)"
        ? Built-in objects for JSPs: objects that can be used directly in a JSP.
        ? There are 9 large built-in objects in the JSP:
  • Request HttpServletRequest GetParameter (), SetAttribute (String name,object value);
  • Response HttpServletResponse SetHeader (String name,string value); Getoutputstream (); getwriter ();
  • Session HttpSession SetAttribute (); getattribute ();
  • Application ServletContext setAttribute (); getattribute ();
  • Page Object toString (); wait ();
  • PageContext PageContext SetAttribute (); getattribute ();
  • Config servletconfig getservletname (); Getservletcontext ();
  • Out JspWriter write (), print ();
  • Exception Throwable getMessage (), Getcause (); Set iserrorpage= "true"
    ? Page built-in object: The real object is the reference to the class after the JSP is translated into a servlet.
    ? Out built-in objects: are out and response.getwriter the same object? What is the difference?
  • Not the real object JspWriter, response get writer is printwriter.
    ? PageContext built-in objects:
  • Get the other 8 built-in objects: when you write a generic code or a framework.
  • To access data in four domains of a JSP:
    Four domain scopes for JSPs:
    • Pagescope: Active on the current page. Pagecontextpagecontext
    • Requestscope: One request range. requesthttpservletrequest
    • Sessionscope: one session range. sessionhttpsession
    • Applicationscope: Application Range Applicationservletcontext
      The "Action tag for JSP" lists 6.
      ? The role of Tags: simplifying code.
      ? <jsp:forward/>: Used for forwarding of pages.
  • <jsp:forward page= "/demo1-jsp/demo3-object/demo3.jsp" ></jsp:forward>
    ? <jsp:include/>: For the inclusion of pages. (dynamically included)
    What are the differences between static inclusions and dynamic inclusions? (<%@ include%> and <jsp:include>)
    ? <jsp:param/>: Used to pass parameters under a label with a path.
    ? <jsp:usebean/>: Used to use JavaBean in JSPs.
    ? <jsp:setproperty/>: Used to set properties to JavaBean in a JSP.
    ? <jsp:getproperty/>: The property used to obtain JavaBean in the JSP.
    1.2.2.2 El Expression:
    "Overview of El"
    ? What is el:

    ? Why study el:
  • Simplifies JSP code, and reduces <%%>
    ? Using an EL expression:
  • Syntax: ${el expression}
    ? El's Features:
  • Get data: (four domains of JSP)
  • Perform the operation:
  • Common objects for manipulating Web development:
  • Calling methods in Java:--seldom used.
    "El Get Data"
    <%
    Pagecontext.setattribute ("name", "PValue");
    Request.setattribute ("name", "RValue");
    Session.setattribute ("name", "svalue");
    Application.setattribute ("name", "Avalue");
    %>
    <%=pagecontext.getattribute ("name")%> <!--if not found returns null--
    <%=request.getattribute ("name")%>
    <%=session.getattribute ("name")%>
    <%=application.getattribute ("name")%>
    ${Pagescope.name} <!--returns ""-
    ${Requestscope.name}
    ${Sessionscope.name}
    ${Applicationscope.name}
    ${name} <!--similar to Findattribute ("name") first looked up from the page domain, did not find the query in the request domain, did not find to go to the session domain to find, did not find to go to the application domain to find--
    <%
    String[] Arrs = {"Li Xuhua", "Li Guanchi", "Yang Feng", "Yang Lu Flower"};
    Pagecontext.setattribute ("Arrs", Arrs);
    %>
    ${Arrs[0]}
    ${Arrs[1]}
    ${Arrs[2]}
    ${Arrs[3]}
    <%
    list<string> list = new arraylist<string> ();
    List.add ("Mrs. Li Furong");
    List.add ("Yang Fu");
    List.add ("Wang");
    Pagecontext.setattribute ("list", list);
    %>
    ${List[0]}
    ${List[1]}
    ${List[2]}
    <%
    map<string,string> map = new hashmap<string,string> ();
    Map.put ("AAA", "Li Xuhua");
    Map.put ("BBB", "Yang Jiujun");
    Map.put ("CCC", "Li Rui");
    Map.put ("ddd", "Li Feng");
    Pagecontext.setattribute ("map", map);
    %>
    ${MAP.AAA}
    ${MAP.BBB}
    ${MAP.CCC}
    ${MAP.DDD}
    <%
    User user = new User (1, "AAA", "123");
    Pagecontext.setattribute ("user", user);
    %>
    ${User.ID}
    ${User.username}
    ${User.password}
    <%
    User User1 = new User (1, "AAA", "123");
    User User2 = New User (2, "BBB", "123");
    User User3 = New User (3, "CCC", "123");

    List<User> userList = new ArrayList<User>();userList.add(user1);userList.add(user2);userList.add(user3);pageContext.setAttribute("userList", userList);

    %>
    ${Userlist[0].id}-${Userlist[0].username}-${Userlist[0].password}<br/>
    ${Userlist[1].id}-${Userlist[1].username}-${Userlist[1].password}<br/>
    ${Userlist[2].id}-${Userlist[2].username}-${Userlist[2].password}<br/>
    . and [] the difference.

    • [] used to have subscript data (array, list collection). Data for attributes (map, object)
    • If the property name contains special characters. You must use []
      "El execution Operation"
      <%
      Pagecontext.setattribute ("N1", "10");
      Pagecontext.setattribute ("N2", "20");
      Pagecontext.setattribute ("N3", "30");
      Pagecontext.setattribute ("N4", "40");
      %>
      ${N1 + n2 + n3}
      ${N1 < N2}-${N1 lt N2} <!--less than--><br/>
      ${n1 > N2}-${n1 GT N2} <!--great than--><br/>
      ${N1 <= N2}-${n1 le n2} <!--less equal--><br/>
      ${N1 >= N2}-${n1 ge N2} <!--great equal--><br/>
      ${N1 = = n2}-${n1 eq n2} <!--equal--><br/>
      ${n1<n2 && n3 < N4}-${n1<n2 and N3 < N4}<br/>
      ${N1<n2 | | N3 < N4}-${n1<n2 or N3 < N4}<br/>
      ${ ! (N1 < N2)} -${Not (N1&LT;N2)}
      ${N1 < N2? "Correct": "Error"}
      ${user = = null}-${empty user}
      ${user! = null}-${not empty user}
      "El Operations Web development common Objects 11"
      The parameter that receives the request <%= Request.getparameter ("id")%><%= request.getparameter ("name")%><%= arrays.tostring ( Request.getparametervalues ("hobby"))%> ${param.id}${param.name}${paramvalues.hobby[0]}${paramvalues.hobby[1]} Gets the request header <%= Request.getheader ("User-Agent ")%> ${header["User-agent"} gets global initialization parameters ${Initparam.username} Gets the value in the cookie ${Cookie.history.value} Gets the object in the PageContext IP address: $ {PAGECONTEXT.REQUEST.REMOTEADDR} project path: ${pageContext.request.contextPath}1.2.2.3 JSTL "Overview of JSTL"? What is Jstl:

? Why Study Jstl:

    • Jstl and El combined replacement page <%%>
      ? Jstl version:
    • JSTL1.0: El expression is not supported.
    • JSTL1.1 and 1.2: El expressions are supported.
      ? Jstl Tag Library: contains five categories of tags.
    • Core (kernel tag), FMT (internationalized tag), XML (XML tag), SQL (SQL tag), FN (Jstl provides El function library)
      ? Using Jstl:
    • Introduces the associated jar package for Jstl.
    • Introduce a tag library in the page. <%@ taglib uri= "" prefix= ""%>
      "The use of Jstl's core tags"
    • If
    • Foreach
      "Jstl provides El's Library of Functions"
      <H1>JSTL provides a library of El functions ${fn:contains ("Hello World", "Hello")}
      ${fn:length ("HelloWorld")}
      ${fn:tolowercase ("ABCDE")}
      <c:foreach var= "i" items= ' ${fn:split ("a-b-c-d", "-")} ' >
      ${i}
      </c:forEach>
      1.2.3 Code implementation: 1.2.3.1 CREATE DATABASE:
CREATE TABLE `product` (  `pid` varchar(32) NOT NULL,  `pname` varchar(50) DEFAULT NULL,  `market_price` double DEFAULT NULL,  `shop_price` double DEFAULT NULL,  `pimage` varchar(200) DEFAULT NULL,  `pdate` date DEFAULT NULL,  `is_hot` int(11) DEFAULT NULL,  `pdesc` varchar(255) DEFAULT NULL,  `pflag` int(11) DEFAULT NULL,  `cid` varchar(32) DEFAULT NULL,  PRIMARY KEY (`pid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1.2.3.2 page Display:

<c:forEach var="p" items="${list }"><tr><td>${ p.pid }</td><td>${ p.pname }</td><td>${ p.shop_price }</td><td><c:if test="${ p.is_hot == 1 }">是</c:if><c:if test="${ p.is_hot != 1 }">否</c:if></td><td>${ p.pdesc }</td></tr></c:forEach>

12th Chapter Web12-jsp&el&jstl

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.