Java Web Review Article 10 JSTL and Java Web Article 10 jstl

Source: Internet
Author: User

Java Web Review Article 10 JSTL and Java Web Article 10 jstl

JSTL (JSP Standard Tag Library) JSP Standard Tag Library. It aims to simplify JSP development. Without JSTL, We need to write a large number of custom tags during development, which will undoubtedly increase the development difficulty, with JSTL, we do not need to write common labels (unless special), which will improve our development efficiency. Here I will mainly explain http://java.sun.com/jsp/jstl/coretag library.

1: Common labels

Common JSTL labels include <c: out>, <c: set>, <c: remove>, and <c: catch>.

1.1: <c: out>

First, to use the content of the JSTL tag library, we first introduce the jar package in the maven project.

<dependency>            <groupId>javax.servlet</groupId>            <artifactId>jstl</artifactId>            <version>1.2</version></dependency>

If we declare the jsp directive element <% @ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>, if we can proceed with our development. Out is undoubtedly the meaning of output, so the main function of <c: out> is to output our variable value, which has the same function as the script element <% = %>.

<C: out> there are three attribute values: value, escapeXml, and default. Value is the value to be output. The default value of escapeXml is true for conversion <and <. default is the default value. Let's write a <c: out>.

   <%      int i=1+1;      request.setAttribute("i", i);    %><c:out value="${i}"></c:out>

If we run it, we can see the results we want. Some people say that if we want to use the label body, it is actually very simple. Set the value to null. Let's look at the source code.

 public int doStartTag() throws JspException {      needBody = false;            // reset state related to 'default'      this.bodyContent = null;  // clean-up body (just in case container is pooling tag handlers)            try {    // print value if available; otherwise, try 'default'    if (value != null) {            out(pageContext, escapeXml, value);        return SKIP_BODY;    } else {        // if we don't have a 'default' attribute, just go to the body        if (def == null) {        needBody = true;        return EVAL_BODY_BUFFERED;        }

In some source code, we can see that as long as the Default and value values are null, the internal values of the label body can be displayed. <c: out value = '<% = null %>'> no </c: out>.

1.2: <c: set>

The main purpose is to set the value of the range variable or the attribute of the JavaBean. I will not show the source code here. If you are interested, you can check the source code on your own. Focus on explanations

<C: set> there are five attributes: value, var, scope, target, and property. value is the calculated expression and the name of the var Calculation result, scope is the default page of JSP. target sets the JavaBean object of the attribute, and the last one sets the attribute of the object. The example below makes everyone clearer

Now, if I want to set a value with num = 1 + 1 and save it in the Session, <c: set> is <c: set var = "num" value = "$ {1 + 1}" scope = "session"> </c: set> then we can reference this value.

<C: out value = "$ {num}"> </c: out>. If it is a JavaBean object, we need to use the target attribute. As follows:

<% UserBean userBean = new UserBean (); pageContext. setAttribute ("userBean", userBean); %> <c: set target = "$ {userBean}" property = "age" value = "18"> </c: set> <c: set target = "$ {userBean}" property = "userName"> Michael </c: set> <c: out value = "$ {userBean. age} "> </c: out> <c: out value =" $ {userBean. userName} "> </c: out>
1.3: <c: remove/>

This mainly removes the range variable, which has two attributes: var and scope. Var: name of the variable to be removed. scope is the jsp range and the default value is page.

To remove the above userBean, <c: remove var = "userBean" scope = "session"/> means to remove an attribute named userBean in the Session.

1.4: <c: catch>

This indicates an exception is caught, and a var attribute indicates that the exception is assigned to var. The Code is as follows:

<c:catch var="exception">    <%    String userName="zhangsan";    %>    </c:catch>
<c:out value="${exception}"></c:out>
2: Condition tag

Condition labels include <c: if>, <c: choose>, <c: when>, and <c: otherwise>

2.1: <c: if>

This obviously means implementing the if statement function in java. There are three attributes: test, var, and scope. Test indicates the test condition analogy (1> 0). var indicates the name exported from the test result, and scope indicates the range. The default value is page. Example:

<c:if test="${1<2}" var="testName" scope="application"></c:if><c:out value="${testName}"></c:out>

Therefore, we can use <c: if> as a judgment statement during development and use it elsewhere.

2.2: <c: choose>, <c: when>, <c: otherwise>

This is equivalent to Switch, case, Default. I mentioned it in my custom tag. Among them, <c: when> has an attribute that test is the result of judgment. A simple example is as follows:

<C: choose> <c: when test = '$ {user }== "zhangsan"'> <c: out value = "James"> </c: out> </c: when> <c: when test = '$ {user} = "lisi"'> Li Si </c: when> <c: otherwise> no matching </c: otherwise>
</C: choose>
3: iteration tag

There are two iteration labels: <c: forEach> and <c: forTokens>

3.1: <c: forEach>

This is mainly for iterative display of Multiple object sets. It has six attributes: var, items, varStatus, begin, end, and step. Var indicates the iteration object, items indicates the collection object to be iterated, and varStatus indicates the status of the current iteration object, begin indicates the START (first iteration by default) of the set of objects to be iterated, and end indicates the end of the set of objects to be iterated (all iterations are completed by default ), the default step of step iteration is 1.

For example

ArrayList al = new ArrayList();        UserBean user1 = new UserBean("zhangsan", 25, "7808@outlook.com");        UserBean user2 = new UserBean("lisi", 15, "16455@qq.com");        UserBean user3 = new UserBean("wangwu", 35, "7808@outlook.com");        al.add(user1);        al.add(user2);        al.add(user3);<c:forEach var="userBean" items="<%=al%>" varStatus="status">            <tr>                <td><c:out value="${userBean.age}"></c:out></td>                <td>${userBean.userName}</td>                <td>${status.count}</td>                <td>${status.index}</td>                <td>${status.first}</td>                <td>${status.last}</td>            </tr>        </c:forEach>

Let's take a look at the results.

From the results, we can see that the role of varStatus is mainly to judge a state of the current iteration object, compared with statu. last to determine whether it is the last object.

3.2: <c: forTokens>

This tag is mainly for strings. It is similar to String userNames = "li; zhang; zhao". At this time, this tag can be output iteratively. This attribute is the same as the preceding tag, but a delims Delimiter is added to it.

String str = "Zhang San, Li Si, Wang Wu,"; <c: forTokens items = "<% = str %>" delims = ", "var =" name "> <td> <c: out value =" $ {name} "> </c: out> </td> </c: forTokens>
4: URL-related tags

Url tags include <c: import>, <c: url>, <c: redirect>, and <c: param>

4.1: <c: param>

Is a parameter added as a URL request, mainly used with <c: url>, <c: redirect>, etc.

4.2: <c: url>

You can use <c: url> to define a URL link for reference in another url. There are four attributes: value, var, context, and scope. Value is the url to be processed, var is the name of the url range variable to be imported, and context is the name of the specified context. scope is the default page of the JSP range. For example

Let me first define a url <c: url value = "http://www.cnblogs.com/cate/java/" var = "myurl" scope = "session"> </url>, then I can directly reference <a href = '<c: out value = "$ {myurl}"> </c: out>'> blog Park </a>, what if I want to add Request Parameters? I need to change the above url

<c:url value="http://www.cnblogs.com/cate/java/" var="myurl" scope="session">    <c:param name="userName" value="zhangsan"></c:param>    <c:param name="password" value="123456"></c:param>
</c:url>

Run the command to check whether the request parameters are added.

4.3: <c: redirect>

This indicates redirection. There are two attributes. One is the url indicating the address to which the url is directed, and the other is the content indicating the context path. This is very simple, written as follows

<C: redirect url = "$ {myurl}"> </c: redirect> the request parameters can also be added.

<C: redirect url = "$ {myurl}">
<C: param name = "userName" value = "zhangsan"> </c: param>
</C: redirect>

4.4: <c: import>

This indicates the resource to be imported. It can be a photo or a website. (You can import resources of this application or other websites)

 

Related Article

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.