当前位置:网站首页>JSP expression library, dry goods tag

JSP expression library, dry goods tag

2021-03-26 22:26:07 Never too old_ How old are you

JSP(Java Server Pages) Be similar to ASP technology , It is On traditional web pages HTML file (.htm,.html) in Insert Java Procedures section (Scriptlet) and JSP Mark (tag), Thus forming JSP file , Suffix named (.jsp).JSP It's essentially a simplified Servlet Design ,JSP Implementation process : .jsp Papers will be JSP engine ( Provided by the server , Such as Tomcat Of Jasper) Translated into .java file , The resulting .class file .


JSP grammar

except HTML grammar , Other extensions are as follows

nesting Java Format of code

  • Declaration label :<%! Variable declaration or method declaration %>
  • Expression tags :<%= expression %> The value of the expression is output to JSP The corresponding position of the page
  • Code tags : <% Java Code %> What's dynamically displayed on the page

JSP Instructions

be used for Statement JSP Page attribute , Such as the coding method 、 Document type, etc . There are three kinds of instructions :page、include、taglib.

Instructions use the format

<%@ directive attribute1="value1" attribute2="value2" ... %>

  • directive finger page、include、taglib One of them
  • attribute Property name
  • value Property value
  • ... This is not grammar , Of others not written attribute="value"

page Instructions

Property name Property value describe
language java explain JSP The language of the document . The default is java
extends The full name of the class From the JSP The class generated by the file inherits which class ,JSP by Servlet, So when you specify inheriting a normal class, you need to implement Servlet Of init、destroy Other methods
import Package name / Class name import Is the only one that can be declared more than once page Command attribute . You can import more than one class at a time , Separated by commas
session true/false whether built-in session object . The default is true
autoFlush true/false true On behalf of the use of out.println() The output string is temporarily stored in the cache , When the cache is full or the program is finished or executed out.flush() Output to the client during operation . The default is true
buffer none/nKB Specify cache size , for example 4KB
isThreadSafe true/false Is it thread safe . The value is true Allows many threads to execute the JSP, Otherwise, you have to queue up to execute . The default is false
isErrorPage true/false The JSP Whether the page is an error display page . by true When JSP Have built-in exception object , Otherwise no . The default is false
errorPage Some JSP The relative path of the page Indicates an error page , If it's time to JSP The program throws an uncapped exception , The exception is passed to errorPage Appoint JSP Page and jump to errorPage Appoint JSP page
contentType The document type The client browser determines the document type based on this attribute . for example ,HTML:text/html、 Pure text :text/plain、JPG Images :image/jpeg、GIF Images :image/gif、WORD file :application/msword
pageEncoding Character set Specify the JSP The character set of the page , Such as UTF-8、ISO-8859-1 etc.

include Instructions

Will others JSP file 、HTML file 、 The text is contained in the JSP And compile it together . This is a kind of Static inclusion , It's equivalent to directly copying and pasting in , So in compiling this JSP When it comes to documents, it will Compile the included files together

  • Property name :file
  • Property value :URL Relative paths
  • example :<%@ include file=" File relative url Address " %>

taglib Instructions

JSP Support label technology , We'll talk about the use of tags later ,JSTL Tag library Use, etc. .

effect : Used to indicate JSP Used within the page JSP Tag library ,taglib Instructions have two properties ,uri Is the address of the class library ,prefix Prefix the label with

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

JSP Of 9 Built in objects

Easy development with built-in objects , Most of them are HttpServlet Objects used in ( except pageContext and out), About HttpServlet Please have a look at Last blog post

object type sketch
request HttpServletRequest The object is client HTTP request , The scope is a request , Include header information 、 system information 、 Request method, etc
response HttpServletResponse HTTP The response object , The scope is JSP page
session HttpSession The scope is a session
application ServletContext The scope is Servlet Containers , Until the server is shut down
config ServletConfig Server configuration information .config In the last post Servlet Level initialization parameter Used in .
page HttpServlet It refers to the JSP Compiled into Java In code Servlet Class object (Servlet yes Single instance Of , So the direction is clear ), amount to this
exception Exception Only the current page is an error page (<%@ page isErrorPage="true" %>) Can be used , If it's not the wrong page to use exception It will result in compilation error .
out JspWriter Used to output... To a page ( Include js Code ), As mentioned above page The directive autoFlush Property is to control the object
pageContext PageContext Represents the context of the page , Can get request、response、session、application、config etc.

EL expression

EL(Expression Language) Expressions make it easier to display variables and objects , To avoid the HTML Embedded in Java Code ( It's very confusing )

Basic usage format

${EL expression } Variable names don't need quotation marks

obtain 4 Domains (pageContext、request、session、application) The median

EL expression Only values in the field can be obtained , Can't get Java Values in the code ! The variables that need to be used must first exist in the domain .

for example :<% session.setAttribute("score",99) %> , At this point you can read score This value ${score}

Another point , If If no value is found, an empty string is returned "", instead of null

Completely limited Access method
  • obtain pageContext Variables of the field :${pageScope.key}
  • obtain request Variables of the field :${requestScope.key}
  • obtain session Variables of the field :${sessionScope.key}
  • obtain application Variables of the field :${applicationScope.key}
Implicit obtain

${key} Will take pageContextrequestsessionapplication Sequential read , The scope of the domain is From small to large

  • About aggregate The exhibition of
<%
	List list = new ArrayList();
    list.add("one");
    list.add("two");
    list.add("three");
    pageContext.setAttribute("aList",list);
    Map map = new HashMap();
    map.put("color","red");
    map.put("shape","square");
    pageContext.setAttribute("aMap",map);
%>
${aList}<br/>		<!-- Direct output array -->
${aList[0]}<br/>	<!-- Read array by subscript -->
${aList[2]}<br/>	<!-- Read array by subscript -->
${aMap}<br/>		<!-- Direct output mapping -->
${aMap.shape}<br/>	<!-- Press the key to read the mapping -->
  • Here's the output from the web page
[one, two, three]
one
three
{color=red, shape=square}
square
The presentation of objects
  • test
<%
	class Student{
        private final String name = "Tom";
        private final String sex = "boy";
        @Override
        public String toString() {
            return name+" is a "+sex;
        }
	}
	Student student = new Student();
	pageContext.setAttribute("aStudent",student);
%>
${aStudent}<br/>

Here's the output from the web page

Tom is a boy

You can see it EL The presentation of objects is actually Called toString() Method , It's the same with collections . If the object is not overridden toString() Method , Then call the parent class toString() Method . For example, the parent class is Object, Then it will output hashcode.

Object's Field ( attribute ) Acquisition
  • Access method : ${object.field} To get the fields of the object ( attribute )
  • Test code

com.java.webtest.Student

package com.java.webtest;

public class Student {
    private String name = "Jack";
    public String getName() {
        return name;
    }
}

myTest.jsp

<%@ page import="com.java.webtest.Student" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>myTest</title>
</head>
<body>
    <%
        Student s1 = new Student();
        pageContext.setAttribute("s1",s1);
    %>
    name = ${s1.name}<br/>
</body>
</html>
  • Running results
name = Jack

️ EL Expressions get object fields ( attribute ) It's through Reflection Mechanism .${s1.name} The underlying logic is to put the initials "n" Put one more in the front "get", And then reflection gets "getName" Method . So the object has to provide get Method , Can be used EL expression ${object.field} , If you don't write it, you will report an error , Or you let get Method returns something unrelated to the corresponding field to prove that get Method to get the value of .

EL Arithmetic

Arithmetic type describe
Arithmetic type Add + reduce - ride * except /div Remainder %mod
The logical model and&&or||!not
Relational type ==eq!=ne<lt>gt<=le>=ge
empty Determines whether a value is null Or for empty, Such as ${empty ""} The return value is true
Three mesh operation expression ? valueA : valueB if expression by true return valueA Otherwise return to valueB
  • Do a test
<%
    class Person{
        private int id;
        private String sex;
        public Person(int id,String sex){ this.id = id; this.sex = sex; }
        @Override
        public boolean equals(Object o) { return id == ((Person) o).id; }
    }
    Person p1 = new Person(777,"boy");
    Person p2 = new Person(777,"girl");
    Person p3 = new Person(666,"boy");
    pageContext.setAttribute("p1",p1);
    pageContext.setAttribute("p2",p2);
    pageContext.setAttribute("p3",p3);
%>

1 + 2 = ${1 + 2}<br/>
1 - 2 = ${1 - 2}<br/>
3 * 3 = ${3 * 3}<br/>
10 / 3 = ${10 / 3}<br/>
10 div 3 = ${10 div 3}<br/>
10 % 3 = ${10 % 3}<br/>
10 mod 3 = ${10 mod 3}<br/>
true and false -> ${true and false}<br/>
true && false ->${true && false}<br/>
true or false -> ${true or false}<br/>
true || false -> ${true || false}<br/>
not true -> ${not true}<br/>
!true -> ${!true}<br/>
666 == 666 -> ${666 == 666}<br/>
p1 == p2 -> ${p1 == p2}<br/>
p1 == p3 -> ${p1 == p3}<br/>
"ABCDEFG" == "abcdefg" -> ${"ABCDEFG" == "abcdefg"}<br/>
"ABCDEFG" == "ABCDEFG" -> ${"ABCDEFG" == "ABCDEFG"}<br/>
"ABCDEFG" eq "abcdefg" -> ${"ABCDEFG" eq "abcdefg"}<br/>
"ABCDEFG" eq "ABCDEFG" -> ${"ABCDEFG" eq "ABCDEFG"}<br/>
"ABCDEFG" != "abcdefg" -> ${"ABCDEFG" != "abcdefg"}<br/>
"ABCDEFG" != "ABCDEFG" -> ${"ABCDEFG" != "ABCDEFG"}<br/>
"ABCDEFG" ne "abcdefg" -> ${"ABCDEFG" ne "abcdefg"}<br/>
"ABCDEFG" ne "ABCDEFG" -> ${"ABCDEFG" ne "ABCDEFG"}<br/>
10 < 3 -> ${10 < 3}<br/>
10 lt 3 -> ${10 lt 3}<br/>
10 > 3 -> ${10 > 3}<br/>
10 gt 3 -> ${10 gt 3}<br/>
10 <= 3 -> ${10 <= 3}<br/>
10 le 3 -> ${10 le 3}<br/>
10 >= 3 -> ${10 >= 3}<br/>
10 ge 3 -> ${10 ge 3}<br/>
empty "" -> ${empty ""}<br/>
empty null -> ${empty null}<br/>
empty 666 -> ${empty 666}<br/>
55 > 60 ? "you pass!" : "you fail..." -> ${55 > 60 ? "you pass!" : "you fail..."}<br/>
  • The output of the page
1 + 2 = 3
1 - 2 = -1
3 * 3 = 9
10 / 3 = 3.3333333333333335
10 div 3 = 3.3333333333333335
10 % 3 = 1
10 mod 3 = 1
true and false -> false
true && false ->false
true or false -> true
true || false -> true
not true -> false
!true -> false
666 == 666 -> true
p1 == p2 -> true
p1 == p3 -> false
"ABCDEFG" == "abcdefg" -> false
"ABCDEFG" == "ABCDEFG" -> true
"ABCDEFG" eq "abcdefg" -> false
"ABCDEFG" eq "ABCDEFG" -> true
"ABCDEFG" != "abcdefg" -> true
"ABCDEFG" != "ABCDEFG" -> false
"ABCDEFG" ne "abcdefg" -> true
"ABCDEFG" ne "ABCDEFG" -> false
10 < 3 -> false
10 lt 3 -> false
10 > 3 -> true
10 gt 3 -> true
10 <= 3 -> false
10 le 3 -> false
10 >= 3 -> true
10 ge 3 -> true
empty "" -> true
empty null -> true
empty 666 -> false
55 > 60 ? "you pass!" : "you fail..." -> you fail...
  • I think we should Particular attention At two o 'clock
    • Two Divide an integer by The result is not an integer
    • p1 == p2 -> true and "ABCDEFG" == "ABCDEFG" -> true. Obviously different from Java,EL Expression overloaded == , Use between objects == When comparing , It is not a reference variable of a comparison object ( That's the object address or pointer ), It USES equals(Object o) Method .!= The same is true of the objects of comparison , You can test it yourself .

JSTL Tag library

JSTL(Java server pages standarded tag library) It's a JSP Standard label library , It encapsulates the JSP Common core functionality for applications .JSTL Support General purpose 、 Structured task , Such as iteration , conditional ,XML The document operation , International label ,SQL label . In addition to these , It also provides a framework to use integration JSTL Custom labels for . The following will explain Some commonly used JSTL label .EL and JSTL The core tag library usually works best with

Preparation before use

Tags use syntax

<prefix:tag attribute="value" ... >
	...
</prefix:tag>

Important labels

disclaimer : The following summary of tag attributes is not comprehensive , Just talk about the common attributes ; And because of uri Different attributes are different . For details, please check the standard.jar

<c:tag> label

Don't forget to import tags before using them , however IDEA It will also automatically import . Core tags can be divided into

  • Expression operation : out、set、remove、catch
  • Process control : if、choose、when、otherwise
  • Iterative operations : forEach、forTokens
  • URL operation : import、param、url、redirect
<c:set> label
attribute default explain
value - The value of a variable stored in a field
var - The name of the variable stored in the domain
scope page Specifies that the data stored in 4 Which of these domains
target - Java object
property - Java Object field ( attribute ). Because it's reflective technology , With the front EL Expressions get field values in the same way : The field must have set Method
<c:out> label
attribute default explain
value - The values that need to be displayed
default - If value The value of is null, Is displayed default Value
escapeXml true Whether or not to paraphrase xml character . Some characters such as &lt stay xml Is considered to be <, If you want its literal meaning , You need to use transfer

Case study

com.java.testclass.Person

package com.java.testclass;

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name+" is "+age+" years old.";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

JSTL-test.jsp

<%@ page import="com.java.testclass.Person" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt" %>
<html>
<head>
    <title>JSTL-test</title>
</head>
<body>

<%
    pageContext.setAttribute("person1",new Person("Tom",18));
    pageContext.setAttribute("person2",null);
%>

<h6>********** set & out Test **********</h6>
<%-- Store values in fields --%>
<c:set var="fruit" value="apple"></c:set>
<c:set var="fruit" value="banana" scope="session"></c:set>
<%-- Set up Java Object field --%>
<c:set value="David" target="${person1}" property="name"></c:set>
<c:set target="${person1}" property="age">18</c:set><br>
<%-- Output --%>
<c:out value="${fruit} is fruit." default="fruit is null!"></c:out><br>
person1 : ${person1}<br>
person2 : <c:out value="${person2}" default="person2 is null!"></c:out><br>
<c:out value="&lt==when escapeXml is true==&gt"></c:out><br>
<c:out value="&lt==when escapeXml is false==&gt" escapeXml="false"></c:out><br>

</body>
</html>

result

********** set & out Test **********

apple is fruit.
person1 : David is 18 years old.
person2 : person2 is null!
&lt==when escapeXml is true==&gt
<==when escapeXml is false==>
<c:if> label
attribute default explain
test - if Conditional expression for
var - Define a variable to store if The result of the conditional expression
scope page var Variable JSP Range
<c:choose> label
attribute default explain
test nothing If the result of the expression is true, Then the executor content ,false On the contrary
<c:choose>
    <c:when test="boolean expression ">
    </c:when>
    <c:otherwise>
    </c:otherwise>
</c:choose>
<c:forEach> label

Used to traverse collection elements

attribute default explain
var - Loop variables for traversal
items - Collection objects that are traversed
varStatus - Store the parameters related to the variables of this cycle
begin 0 Traversal starting point subscript
end Last element subscript Traversing the end subscript
step 1 The number of intervals per iteration

Let's look at an example

<%
    int[] arr = {100,200,300,400,500,600,700,800,900,1000};
    pageContext.setAttribute("arr",arr);
%>

<h6>********** process control Test **********</h6>
foreach arr
<c:forEach items="${arr}" var="it" begin="1" end="7" step="2" varStatus="status">
    <c:if test="${status.count==1}">
        from ${status.begin} to ${status.end} by step = ${status.step}<br>
    </c:if>
    arr[${status.index}] = ${it} , count = ${status.count}<br>
</c:forEach>

result

********** process control Test **********

foreach arr from 1 to 7 by step = 2
arr[1] = 200 , count = 1
arr[3] = 400 , count = 2
arr[5] = 600 , count = 3
arr[7] = 800 , count = 4

From results count Attributes are not related to index The value associated with the property ,index Is the subscript of an array ,count Counter as loop only .

<fmt:tag > label

<fmt:formatDate > label

This tag is used to format the output Date Type variable , More commonly used

attribute default explain
value - Used to specify the formatted object
pattern - Formatting patterns , And SimpleDateFormat The parameter settings are the same
var - Specifies the variables to be stored in the resulting formatted string , If not specified, it will be directly output in the page
scope page Appoint var The storage domain of variables
type date explain value Object contains time or date or both . The value is date/time/both
fmt:parseDate label

<fmt:formatDate> The reverse process of , Used to convert a specified string to a date type

attribute explain
value Used to specify the converted String
pattern Specifies the format of the parse string
var Specifies the variables to be stored in the generated time object

See the test code

<%
    pageContext.setAttribute("now",new Date());
%>

<h6>******************** fmt Test ********************</h6>
before formatting : ${now}. <br>
<fmt:formatDate value="${now}" pattern="yyyy-MM-dd" var="parse_date"></fmt:formatDate>
after formatting  : ${parse_date}. <br>
<fmt:parseDate value="${parse_date}" var="gotten_date" pattern="yyyy-MM-dd"></fmt:parseDate>
date get from string : ${gotten_date}. <br>

result

******************** fmt Test ********************

before formatting : Sat Mar 13 23:03:16 CST 2021.
after formatting : 2021-03-13.
date get from string : Sat Mar 13 00:00:00 CST 2021

Notice the difference between the first date and the third date , This is due to the loss of time information during the first conversion

<fmt:formatNumber> label

It is mainly used to control the display format of numbers . Remember the front EL operation 10/3 The results show that 3.3333333333333335, Usually we don't want to show so many decimal places .

attribute explain
maxIntegerDigits The largest number of digits in the integer part
minIntegerDigits The least number of digits in the integer part
maxFrctionDigits The largest number of decimal places
minFrctionDigits The least number of decimal places
var Specifies the variable that stores the formatted results
scope Appoint var The scope of the property

版权声明
本文为[Never too old_ How old are you]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/03/20210314112929116e.html

随机推荐