Day20-jsp & el & jstl

Keywords: Attribute JSP SQL Session

EL expression

${EL expression}
EL (Express Lanuage) expressions can be embedded in jsp pages to reduce the writing of jsp scripts. The purpose of EL is to replace the writing of scripts in jsp pages.

Expression language Expressions Language, borrowing js, jquery grammar
Effect:
1) Simplify the code in jsp, mainly to replace the JSP script <%=%>
2) Obtaining data from domain objects;
3) Depends on pageContext.findAttribute ()
4) Perform operations

Functions:
1) Get the objects in the domain
2) Perform operations
3) Getting Common web Objects

Function 1: EL expression performs operations

(1) Perform operations + - */%

 ${ 4+6 }

It should be noted that:
${ 4+"7" }
The result is 11
Note: + - must be a numeric or numeric string;

(2) Logic operators and comparison operators
2.1) Logical Operator: & |! (and or not)

${ 3>4 && 4<5  }  or ${ 3>4 and 4<5  }
${ ! (3>5)}

2.2) Comparing operator: > >===== <==!=
${ 4==4 }
Character comparisons can also be made:

           <%
                 pageContext.setAttribute("city", "Shanghai");
           %>
           ${ city=="Shanghai" }

2.3)empty: judge whether it is empty or not;
1) Judging whether the content is an empty string
2) Judging whether the object is null
3) Judging whether the length of the set is 0

${ empty aaa}
${ empty city }
  <%
  List<String> list = new ArrayList<String>();
  list.add("value1");
  list.add("value2");
  pageContext.setAttribute("list", list);
//Make sure you add pageContent after you create the list, otherwise it's equivalent to not creating it.
  %>
  ${empty list } <br/>
  ${empty list2 }

2.4) ternary operators

${ 5>3 ? 5 : 3 }

Function 2: EL expression to obtain data in the domain

If the data is found, it will be returned, otherwise it will be returned.

2.1) Shortcut access to data
Find the specified properties from pageScope, requestScope, sessionScope, and application Scope in turn
If found, return immediately and stop looking backwards.
If you can't find it, go back to ""

 If special symbols such as ".""+""-" appear in attributes, they should be used when shortcuts cannot be obtained.
      ${xxxScpoe ["attribute name"]}
  • Get simple data
    ${pageScope|requestScope|sessionScope|applicationScope. Property name}
  • Getting complex data

    • Gets the value ${array attribute name [index]} in the array in the field
    • Get the value ${list attribute name [index]} in the list in the domain
    • Get the value ${map attribute name. key} in the map in the domain
    • Get the data in JavaBean ${javabean property name. bean property}

    • Get the data in the array:

           <%
           String[] arr = new String[3];
           arr[0] = "aaa";
           arr[1] = "bbb";
           arr[2] = "ccc";
           pageContext.setAttribute("arr",arr);
           %>

           <%= ((String[])pageContext.getAttribute("arr"))[1] %>   <br/>
           ${ arr[1] }
* Get the data in the list collection
      <%
                 List<String> list = new ArrayList<String>();
                 list.add("aaa");
                 list.add("bbb");
                 list.add("ccc");
                 pageContext.setAttribute("list", list);
           %>
            <%=((List<String>)pageContext.getAttribute("list")).get(1) %>  <br/>
           ${ list[1] }
* Get the data in the map collection
          <%
                 Map<String,String> map = new HashMap<String,String>();
                 map.put("akey","avalue");
                 map.put("bkey","bvalue");
                 map.put("ckey","cvalue");
                 pageContext.setAttribute("map", map);
           %>
            <%=((Map<String,String>)pageContext.getAttribute("map")).get("ckey") %>
            <br/>
           ${ map.ckey }
* Special map writing:
         <%
                 Map<String,String> map = new HashMap<String,String>();
                 map.put("akey","avalue");
                 map.put("bkey","bvalue");
                 map.put("ckey","cvalue");
                 map.put("s.key","svalue");
                 pageContext.setAttribute("map", map);
           %>
            <%=((Map<String,String>)pageContext.getAttribute("map")).get("ckey") %>
           <br/>
           ${ map["s.key"]}
* Get data from objects
          <%
                 User user = new User();
                 user.setUsername("zhangsan");
                 user.setPassword("123");
                 pageContext.setAttribute("user",user);
           %>
            <%=((User)pageContext.getAttribute("user")).getUsername() %><br/>
           ${user.username }

Introspective principles correspond to attributes rather than fields.

2.2) Getting data from a specified range

Writing pageScope only takes out all the attributes in the domain and the form of key-value pairs.

${pageScope }
${requestScope }
${sessionScope }
${applicationScope }

When special characters are included:

EL's built-in objects

11 Big Built-in Objects
Domain object:
pageScope | requestScope | sessionScope | applicationScope
- Request parameter correlation:
- Param (understanding)
- ParamValues (Understanding)
- Request Header Related (Understanding)
- header
- headerValues

  • Global Initialization Related (Understanding)
    - initParam

  • cookie*

    • Gets a map collection: map < Cookie name, Cookie Object >
    • Get the value ${cookie.lastTime.value}
  • pageContext*
    - pageContext.request.contextPath: Get the project path {pageContext.request.contextPath} dynamically in the jsp page
    EL expression code reference:
   <%
        pageContext.setAttribute("pkey", "pvalue");
        request.setAttribute("rkey", "rvalue");
        session.setAttribute("skey", "svalue");
        application.setAttribute("akey", "avalue");
    %>
    Old way: <%=pageContext.getAttribute("pkey")%><br>
    EL mode:${pageScope.pkey }
    <hr>
    Old way: <%=request.getAttribute("rkey")%><br>
    EL mode:${requestScope.rkey }
    <hr>
    Old way: <%=session.getAttribute("skey")%><br>
    EL mode:${sessionScope.skey }
    <hr>
    Old way: <%=application.getAttribute("akey")%><br>
    EL mode:${applicationScope.akey }
    <hr>

    Quick Way: ${ pkey } ,${ rkey },${ skey },${ akey }

    <h3>Request parameters</h3>
    ${param }
    ${param.name }
    ${param.hobby }
    <br>
    ${paramValues }
    ${paramValues.name[0] }
    ${paramValues.hobby[1] }
    ${fn:length(paramValues.hobby) }

    <h3>Request header</h3>
    ${header }<br>
    ${header.cookie }<br>
    ${headerValues }

    <h3>Global initialization parameters</h3>
    ${initParam.root }

    <h3>Obtain cookie Relevant content</h3>
    ${cookie }<br>
    ${cookie.JSESSIONID.value }

    <h3>Get other objects</h3>
    ${pageContext.request.contextPath }

jstl: jsp standard tag library

JSTL (JSP Standard Tag Library), JSP standard tag library, can be embedded in JSP pages in the form of tags to complete business logic and other functions. JSTL appears for the same purpose as el to replace script code in JSP pages. JSTL standard label library has five sublibraries, but with the development of JSTL standard label library, its core library is commonly used.

Use steps:
1) Import before use: two jar packages

2) Import the core tag library with jsp instruction taglib instruction: the code is as follows:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

JSTL's five word libraries:
core Core Library:c
I18N internationalization: fmt (hardly needed)
sql: sql-related sql (obsolete)
xml:xml-related x (obsolete)
functions: Universal function fn (rarely used)

Core tag library: if tag
This tag is dedicated to completing conditional judgment in jsp pages
The test attribute is used to set the logical expression.
The var attribute is used to specify the name of a variable in a logical expression
The scope attribute is used to specify the scope of the var variable, and the default is page.

      <% pageContext.setAttribute("city", "shanghai"); %>
      <c:if test="${city=='shanghai'}">
           Conditions for Export to Shanghai
      </c:if>

There is no else tag in the core tag library.

Core tag library: choose tag
Similar to switch statements

   <% pageContext.setAttribute("city", "shanghai"); %>
      <c:choose>
           <c:when test="${city=='shanghai' }">Shanghai
           </c:when>
           <c:when test="${city=='shenzhen' }">Shenzhen
           </c:when>
           <c:otherwise>Welcome to Beijing
           </c:otherwise>
      </c:choose>

Core tag library: forEach tag
This tag is specifically used to iterate over elements in collection objects, such as set, list, map, array, and so on. And can repeat the content in the tag body;
The var attribute is used to refer to the name of the element currently iterated into the page field
The items attribute is used to specify the set of objects to iterate over
varStatus: Loop state, such as the number of current loops; name of the object used to specify the current iteration status information stored in the page field
The begin attribute is used to specify the number of elements in the collection to start iteration; the index value starts at 0.
End property, to what end
The step attribute is used to specify the iteration compensation, which is the increment of iteration factor.

      <c:forEach var="i" begin="1" end="20" step="2" varStatus="status">
           //This is the ${status.count}The data traversed is ${i };<br/>
      </c:forEach>
     forEach ergodiclistaggregate
      <% List<String> list = new ArrayList<String>();
           list.add("aaa");
           list.add("bbb");
           list.add("ccc");
           pageContext.setAttribute("list", list);
      %>
      <c:forEach var="i" items="${list }">
           ${i }
      </c:forEach>
     forEach ergodicmapaggregate
      <%   Map<String,String> map = new HashMap<String,String>();
           map.put("aaa","a");
           map.put("bbb","b");
           map.put("ccc","c");
           pageContext.setAttribute("map", map);
      %>
      <c:forEach var="j" items="${map }">
           ${j }
      </c:forEach>
      <c:forEach var="k" items="${map }">
           ${k.key }:${k.value }
      </c:forEach>

Case: Write a case of displaying commodity information with jstl.

      <!-- use jstl Write it down. -->
      <table border="1px" align="center" style="background-color:green" >
           <tr>
                 <th>commodity id</th>
                 <th>Trade name</th>
                 <th>commodity price</th>
                 <th>Commodity Description</th>
           </tr>
      <c:forEach var="list" items="${products }">
           <tr>
                 <td>${list.getId() }</td>
                 <td>${list.getPname() }</td>
                 <td>${list.getPrice() }</td>
                 <td>${list.getPdesc() }</td>
           </tr>
      </c:forEach>

      </table>

Or:

      <!-- use jstl Write it down. -->
      <table border="1px" align="center" style="background-color:green" >
           <tr>
                 <th>commodity id</th>
                 <th>Trade name</th>
                 <th>commodity price</th>
                 <th>Commodity Description</th>
           </tr>
      <c:forEach var="list" items="${products }">
           <tr>
                 <td>${list.id }</td>
                 <td>${list.pname }</td>
                 <td>${list.price }</td>
                 <td>${list.pdesc }</td>
           </tr>
      </c:forEach>

      </table>

MVC Design Patterns

Short Description of Model-View-Controller
MVC is a software architecture pattern in software engineering. It is a design method of separating business logic and display interface. It divides software system into three basic parts: model, view and controller.
controller: Handles requests and forwards requests
view: Interface designers design graphical interfaces;
model: Write the function of program application, implement algorithm, database management, etc.

Posted by swasheck on Thu, 20 Dec 2018 18:12:05 -0800