jsp syntax, EL expression custom EL expression, JSTL custom label library custom label library template

Posted by lovesmith on Wed, 08 Sep 2021 19:06:58 +0200

1 jsp page element

Can be HTML and CSS static text                                     For example: <h1>I am rich<h1>
        Notes <!-- Notes-->  <%--  Note Content-- %>                 for example    <!--I'm annotated-->
        Instructions to <%@ Instruction Content  %>                                     for example    <%@ page language = "java"%
        Expression <%=Expression %>                                            for example    <%=student%>
        Script    <%java Code%>                                             for example    <%student ="123";%>
        statement    <%! Declare a java Class or Method%>                       for example     <%! public class Person{}%>
        action    <jsp:Action Name>start   </jsp:Action Name End>          for example      <jsp:include page="top.jsp"></jsp:include>

Instruction Element

extends specifies that the class inherited by the Servlet after the jsp page has been converted usually does not need to use this property. The jsp container will provide the default class

import specifies the classes that a jsp page can use

Session is used to specify whether a page has a session built in. If the property is false and it will not be built in, then there is no built-in session object on the page.

Buffer is used to specify the size of the output of the out object. If a buffer is defined, it will not only be passed to

PrintWriter output is now stored in the cache

autoFlush specifies whether to refresh the default True when the buffer is full

isThreadSafa is used to specify whether the jsp is thread-safe if set to ture The page can be accessed by multiple clients simultaneously If set to false Only one user can be processed at a time

The info info property prepares a meaningful string property value for the jsp page A string can get the info property value through the getServletInfo() method

The errorPage errorPage property is used to specify when a jsp page will be forwarded to the specified page when an exception occurs

isErrorPage isErroPage is used to specify whether the current page handles default exceptions If True can handle exceptions from another jsp page Default is false is usually used with errorPage

contentType is used to specify the MIME type and character set that your jsp pages output to the client. The default MIME is text/html The default character set is ISO-8859-1 This must be at the top of the file

The pageEncoding pageEncoding property specifies the character set encoding used by the jsp page If this property is used then the jsp page will use the encoding set specified by the contentType property

isELIgnored is used to specify whether El expressions are ignored in jsp pages If true expressions are ignored If false EL expressions will be executed
taglib is used to import specified custom table labels and
include is a file resource contained in a file on a jsp page. The file resource is parsed at compile time and then inserted into the source file only once

Action Elements

The jsp:include include include action is the same as the include directive, but he inserts at run time or not at compile time. There are two properties of the page property that contain the relative path of the resource
flush optional setting whether to refresh buffers
jsp:forward Sends a client's message to a specified JSP or Servlet or static source file with an attribute page to set the forwarding address There can be sub-action labels <jsp:parm name = ""value=">
<jsp:param name="" value=">Action elements are often used for name-sum values to provide additional information often used with jsp:include jsp:forwordjsp:plugin action elements as their subtags
jsp:useBean can reference a javaBean in an identifier program that creates a javaBean in jsp with a parameter id used to define a javaBean: specify the scope of javaBean. The optional values are page, request, sesson, and the default value of application is page calss: specify the full Class name of java beanName specifies the full Class name of JavaCannot coexist with lass,
jsp:getProperty is used to read or set properties of javaBean where each parameter is name The property of javabBean to read or set If'*'represents all properties
value specifies assignment to JavaBean properties

<%-- Instruction Element Chestnut--%>
<%@ page  extends="Class Name"
          import= "java Class List"
          buffer="namo|custom size  <%-- Define buffer size--%>
          info  ="Page Content"
          errorPage="Page error is the page to convert to"
          contentType="text/html"ï¼›charset="gb2312"<%--Set file type and encoding for output to client --%>
          pagEncoding="UTF-8"    <%--Specify settings jps Page encoding is utf-8--%>
          isELIgnored="true|false"     <% Is this setting available el Expression%>
          taglib url= "http: //Java.sun.com/jsp/jstl/core "prefix=" C "<%--Here's an example of importing the JSTL tag library--%>
          include file="foot.html"  
          include file="D:\\jsp"
          include file="www.baidu.com"<%-- You can import local and relative paths as well as network resource paths--%>

       <%--jsp Action Element Chestnut--%>
<jsp: include  page="5.html" fluseh="true">
         <jsp:param  name="title"  value="english'> <%-- Here is where the included files are set init Parameter here imports 5.html --%>
         <jsp:param   name="content" value="fugui">

<jsp:forward page="b.jsp">  
     <jsp:parm name ="paramName' value="fugui">  <%--The parameters set here for forwarding can be passed through request.getParameter("paramName")Get --%>

<jsp:useBean id="name" scope ="page'  class="fistbean.FBean" >   
<jsp:setParoperty name="name' property="propertyname" value="fugui"><%--Set up name  propertyname Property's value is set to fugui--%>
<jsp:getParoperty  name="name"  property="propertyname">  <%--Get the value of the property The only thing shown on the page is the value of the property--%>


html comments This comment is not safe, for example Show as <! -- 2010-6-249:20:07 -->
jsp comment <%----%>Hidden comment The first line of comment at run time is Hidden Not Shown

Introduction to 3 jsp built-in objects

   request: This is the user's request object that encapsulates the requested and all the information, but he does not have the actual protocol available so he is often forced into his subclass HttpServletRequest There's a lot more inside http Protocol Method Scope is Request Period
       response  This information returned to the client generally needs to be cast to its subclass HttpServletResponse Object Scope is Corresponding Period
       out   Output results to the client can be directed to set the size scope of the cache for the duration of page execution
       session Session objects are automatically created technologies that are not introduced into a session and will be created unless an instruction element is present page Attribute Meet Pending Close Scope Is One Session
       application Used to transfer parameters to the entire application web application
       page    This object is the page itself
       pageContext It is used to get jsp Built-in objects for pages 
       config  Used to read server configuration information
       exception Only when a page produces an error

Request request request information

Http Request Information
http request has one or more information. Each title has a name and a value. Return the title name of all customer requests. Return the title name of all customer requests. getHeaderNames() method obtains the corresponding title name and value through getHeader() Each Title header has the following meaning
Accept: MIME type acceptable to browsers
Accept-Charset: How browsers can decode data
Accept-Encoding: How browsers can decode data
Accept-Language: The kind of language browsers want
connection: is a persistent link required
content-Length: Indicates the length of the request message body
Cookies: Cookies returned to the server that were previously sent to the browser by the server
Host: Host and port of the initial url
Solutions for Chinese Scrambling

<%  String name = new String(request.getParamenter("name").getBytes("ISO-8859-1"),"UTF-8");//When the request parameter is out of order%>
          <%  request.setCharacterEncoding("utf-8") //When submitting the form, the Chinese information is garbled and the encoding format can be set%> 

response Response Object

Set corresponding header
Request information comes with a header The corresponding header was used to respond to the browser with a message that helped him correctly display the content either by using tags and their attribute settings or by setHeader("header name", "attribute value") addHeader("header name", "attribute value")) to set corresponding headers and create custom headers and examples:

<%-- adopt meta Label Set Cache and Validity Period--%>
<meta http-equiv="pragma" content="no-cache">   
<meta http-equiv="cache-control" content="no-cache">   
<meta http-equiv="expires" content="0">
<%--Set up by scripting--%>
 <% response.setHeader( "Pragma", "no-cache" );   
    response.setDateHeader("Expires", 0);   
    response.addHeader( "Cache-Control", "no-cache" );//Neither browser nor cache server should cache page information
<% response.setHrader("Refresh","1");//Client receives this header without an interval of 1s to refresh the page

Request redirection
When the server receives a request, sometimes it needs to take the client to a new resource, use sendRedirect() redirection, or specify an error status code with response This method can accept an error status code and return an optional error message to the client This method is sendError(200, "This page is wrong").

EL expression

Used to get simple data to prevent a lot of java code from getting messy inside the jsp
Basic usage of EL expressions
${Data} If you want the el expression to fail, add a backslash before it
Example of variable acquisition

${pageScope.username}   //Find the username attribute in the page and return null if it is not found
${requestScope.username}//Find in request if return null is not found
${sessionScope.username}//Find in session if return null is not found
${applicationScope.username}//Search for Zhao in the application if no return null is found

//Use el to get properties of javaBean An example is userBean
${userBean.username}//Get username property of userBean
${userBean[username]}//Same as above but in a different way

//Use El to get the value of the array list map An example is to get the values of the array user and list list user and map user under request
${request.user[0]} //Remove the 0 data from the user array
${reqeust.userlist[0]}//Remove the 0 data from the table below userlist
${reqeust.usermap["nema"]}//Remove the name attribute under usermap

EL arithmetic operator
el has + - * /% and so on, just like java
Note: Use the el expression in ${reqeust.name == request.nema2};
You can use ternary operators like java

${password=="123"?"Password is correct": "Password error"}

Empty operator returns true if empty is null

${empty expression} //Determine if expression is empty

el access built-in objects
Built-in pair object pageContext param paramValues header headerValues cookie initPram pageScope requestScope sessionScope applicationScopedu
There are two ways to access property values or built-in objects
An el expression that uses the dot syntax and always uses square brackets plus single quotation marks for a single parameter with operators such as + - * considers that this is not a parameter name but an operation and you need to use ['] for example
Supplement: In fact, all fields are map s made up of key and value. We take out his value through his key. If we need to get the properties of the domain object, we also need pageCaonext to take out the request object to use. In order for pageContext to take out the jsp implied object

//When a field has a specified special character, such as an attribute called student-x, the point grammar will not get the object because - will be interpreted as a minus sign The grammar should be used
requestScope.student-x //This is an incorrect unavailable value
requestScope['student-x'] //This is correct
requestScope["student-x"]//Single quotes are the same as double quotes

${pageContext.request.scheme}  // Gets the protocol properties inside the request object
${pageContext['request']}//The second method is the same as the one above
${pageContext.response}//Get response object

${param.user}//Get the parameter value of user
${paramValues.subject[0]} //Used to get a parameter that has multiple values Take out the specified value The first value taken out here

${header.host} //Get the host property of the header
${header[host]}//Same as above

${cookie.username.value}//Gets the properties of username in a cookie object
${initParam.username}//Gets the specified web initialization parameters

Custom el function

Requires configuring xml Mapping Files Typically create a.tib file under web-inf
An implementation class needs to be configured
Customize templates to tib files

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  <!-- Description of Label Library -->
  <description>JSTL 1.1 functions library</description>

  <display-name>JSTL functions sys</display-name>

  <!-- Version number of label Library -->
<!-- taglib In directive prefix You can write whatever you want, but try to be consistent with the file name for ease of administration. -->

<!-- taglib In directive URI You can write any part you want -->

<!-- Custom Function Label -->
   <!-- Custom Function Description -->
    <description>Get a list of dictionary objects</description>

    <!-- in use EL Function name used in expression -->

   <!-- Custom functions need to be bound Class Full name -->

   <!-- Complete writing of custom function signature, ignoring parameters:Method Return Type Method Name (Type list of parameters...) -
    <function-signature>String getDictList(java.lang.String)</function-signature>

//Use chestnuts

JSTL Tag Library

There are five different tag libraries, the core tag library format tag library sql tag library xml tag library function tag library must be introduced before using these libraries <%@ tabglib%>
jstljar download address: Official download address:http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/

Import Library

You need to import jstl.jar and standard.jar before importing the relative jar package: jstl1.2
If you have jstl1.2 or more, you do not need to reference the stardard.jar Library
And add the following configuration to the web.xml file


jsp imports five label library instances

Core Label Library

<c:out>Outputting an expression value to a jsp page is equivalent to <%=%>
<c:set>Set the property value within the specified range or for the specified object
<c:remove>Deletes a specified number of variables from a specified jsp scope
<c:catch>An exception to the catch program is equivalent to a cry...catch
<c:import>Import static and dynamic files in the inbound
<c:redirect>Redirect the request request request
<c:url>Construct a URL using the correct URL override rules
<c:param>Provides parameter information for other tags, often used in conjunction with other tags
<c:if>meets the criteria as if
<c:select>, <c:when>, <c:otherwise> switch statement
<c:forEach> forEach loop
<c:forTokens>and forEach are just about as simple as their item value can only be a string delims attribute to specify the delimiter

//set a property
<c:set scope="request" var="name" value="Oh my God"></c:set>    //Modify parameters within a specified scope
<c:set   property="username" target="${requestScope.stu}"  value="Rich"></c:set>  //Modify the parameter property="variable name" terget="object to modify" value="value to modify"

<c:remove var="stu" scope="request"></c:remove> //Delete values in specified fields

<c:if test="${stu.age>=18}" scope="request" var="flag"> //flag stores the result of test judgment var variable name scope specifies the storage domain
  <h2>Rich adult</h2>
<c:if test="${stu.age<18}">
<h2>Rich Minors</h2>

    <c:when test="${stu.age>18}">      //Otherwise must be placed at the last time and otherwise must be wrapped by choose
    <h2>Rich adult</h2>
    <c:when test="${stu.age == 18 }">
    <h2>Richness Nobody can stop him except the Constitution</h2>
    <h2>Rich Primary School</h2>

<c:forEach begin="1" end="3"  items="<%=list%>" var="i"   varStatus="status">   // begin Specifies Start end Specifies end items Specifies Collection  
    ${pageScope.i}                                                              //Details of the value status parameter for var each iteration
                                                                                //Actually i exists in the page field

<c:forTokens items="google,runoob,taobao" delims="," var="name">  //items specifies a convenient string var specifies the variable delims specifies the separator
   <c:out value="${name}"/><p>

<c:redirect url="http://Www.runoob.com "/> //Forward"

"<c:url value="http://Www.runoob.com'/>'//This is not known to you either

Function Label Library

fn:contains(""") determines whether the first string contains the second string containing a return True case-sensitive
fn:containsIgnoreCase(""") determines if the first string contains the second return boolean case-insensitive
fn:endsWith(""") determines whether a string begins with the specified string
fn:startsWith("") determines whether the specified string begins with the specified string
fn:indexOf(""") returns the following table of the specified string
fn:replace(""""") Replaces the second parameter contained in the first parameter with the third parameter and does not replace if it does not.
Fn:substring (', int, int) intercept string from the specified table below to the end

Custom Label Library

You need a class that implements the SimpleTag interface or inherits SimpleSupport s. You also need to give the tid file (actually an xml)
Label's parameters require set ting methods within the implementation class to receive
Profile Template

<taglib xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
  <tlib-version>1.0</tlib-version><!-- Good label version-->
  <short-name>dd</short-name><!-- Label library short name also calls the prefix before -->
  <uri>http://Www.ziding.cn/tag2.0</uri><!--URI of import label library -->
   <tag>  <!--Represents an independent custom tag -->
   <name>max</name>              <!-- Label Name -->        
   <tag-class>tag.MaxTig</tag-class> <!-- Implementation Class of Label -->
   <body-content>empty</body-content><!-- Is the content of the label body an empty label 
    It can also be set to
    scriptless:Not transferable jsp Expression, e1 And other normal
    scriptless Transferable jsp Or, you can pass in jsp Expression.
    tagdependent:What is incoming is what- >
  <attribute>    <!-- Label Properties-->
       <name>sum1</name>    <!-- Property Name-->
       <required>true</required>  <!-- Is it necessary-->
       <rtexprvalue>true</rtexprvalue> <!-- Whether to get dynamically at this point el->


Implementation class case

public class MaxTig implements SimpleTag {
     private String sum1;
     private String sum2;
     public String getSum1() {
           return sum1;
     public void setSum1(String sum1) { //Accept tag attributes
           this.sum1 = sum1;
     public String getSum2() {
           return sum2;
     public void setSum2(String sum2) {
           this.sum2 = sum2;
     public void doTag() throws JspException, IOException {  //This is a real logical call
           JspWriter wirter = this.jspContext.getOut();
            wirter.write(Math.max(Integer.parseInt(sum1),  Integer.parseInt(sum2))+"");
     public JspTag getParent() {   //Automatically gets the parent class
           // TODO Auto-generated method stub
           return null;
     public void setJspBody(JspFragment arg0) { //Get his tag body
           // TODO Auto-generated method stub
     private JspContext jspContext;  //Get the context object
     public void setJspContext(JspContext arg0) {
           this.jspContext = arg0;

Topics: JSP