当前位置:网站首页>Custom JSTL tag of JSP
Custom JSTL tag of JSP
2022-07-23 16:25:00 【xiongᥫᩣ】
Catalog
Two , What is? JSTL(JSTL Tag library )
2、 Write tag library description file (tld)
3、 stay JSP Use custom labels on ( test )
One , What is? JSP
- JSP( Full name JavaServer Pages),JSP take Java Code and specific changes are embedded in static pages , The implementation takes the static page as the template , Part of it is generated dynamically .JSP At run time, files are converted by their compiler to more primitive Servlet Code .JSP The compiler can put JSP The file is compiled with Java It's written in code Servlet, And then by Java Compiler to compile binary machine code that can be executed quickly , It can also be directly compiled into binary code .
- Simply speaking :JSP It's a template engine , It simplifies development , Encapsulates the servlet Respond to html Cumbersome code of labels .JSP Technology to Java Language as a scripting language , For users HTTP Request for services , And can communicate with others on the server Java Programs work together to address complex business requirements .
JSP It's a special kind of servlet.
Two , What is? JSTL(JSTL Tag library )
JSTL The full name is Java Server Pages Standard Tag Library , namely JSP Standard label library . It involves developing JSP A set of standard tags that are often used on a page , These tags provide a way to avoid embedding Java Code can develop complex JSP Page approach .JSTL The tag library contains a variety of tags , Such as general label , Condition judgment tag and iteration tag .
The concept of labels
- It's markup language (Mark Language), It is a language for annotating text , The computer can be operated easily . A lot to do with “ML” The ending language is markup language , such as :HTML,XML,XHTML,VML wait
- Markup language is the same as other languages , You also need the environment in which they run , such as HTML Runtime browser ,XML We also need our own parsing and running environment
Label type
- UI label , Output page elements
- Control tags , Such as if label ,foreach Labels etc.
- Data labels , Used to enter data into a page
The basic structure
- < The start tag > Tagging body </ End tag >
Empty label ( Tags without tag body )
- < The start tag Property name =" Property value "/></ End tag >
- <br/><br/>
- < The start tag Property name =" Property value "/>
jstl Concept of tag library
It's a JSP Label set , It encapsulates the JSP Common core functionality for applications , be based on JSP The label can be understood as , yes JSP It should be a way of encapsulating common functions
3、 ... and , How to use JSTL
How to use JSTL label ? Used in development JSTL The tag library needs to perform the following two steps .
(1) To quote in a project JSTL Of the two jar File and tag library descriptor file ( extension .tld).
Just like using JDBC Connect to the database , Use JSTL The defined label library must also import two in the project jar file :jstl.jar and standard.jar. besides , Tag class library descriptor files are also required , These resources can be downloaded online .
stay MyEclipse Integrated in JSTL, Therefore, this step can be realized by tools .
(2) In need of use JSTL Of JSP Page usage taglib Instruction to import label library description file . for example , To use JSTL Core tag library , Need to be in JSP Add the following at the top of the page taglib command .
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>taglib Command passed uti Attribute refers to the configuration file of a tag library ,JSP Page through prefix Property to access a tag function in the tag library , Grammar is like <C: Tag name >
After completing the above two steps , You can use it JSTL Easy to develop JSP page , Without embedding Java Code. .
Four , Why use JSTL
We use EL expression User name information is easily output , Thus, it simplifies JSP The complexity of page development . But because of EL Expressions cannot achieve logical control , Loop traversal and other functions , If you're developing JSP When you encounter such a demand on the page , In addition to writing Java Script , How else can we solve ? The answer is to use JSTL label .
JSTL The life cycle of labels

Custom tag
1、 Custom label class
- out The tag class ( Inherit BodyTagSupport)
/**
* out Function of label : towards JSP Write data in the page
*/
public class OutTag extends BodyTagSupport{
private String val;
private String defaultVal;
public void setVal(String val) {
this.val = val;
}
// Method to set the default value when it is empty
public void setDefaultVal(String defaultVal) {
this.defaultVal = defaultVal;
}
// How to start labels ( What actions need to be added to the customized label , Rewrite the methods in the corresponding life cycle )
@Override
public int doStartTag() throws JspException {
//this.pageContext: Get through the current class pageContext object
//pageContext One of the objects is getOut Write the way
JspWriter out = this.pageContext.getOut();
try {
if(val==null&&val.equals("")) {
out.println(this.defaultVal);
} else {
out.println(this.val);
}
} catch (Exception e) {
e.printStackTrace();
}
// Skip the label body ,out What is defined is an empty tag
return SKIP_BODY;
}
}/**
* out Function of label : towards JSP Write data in the page
*/
public class OutTag extends BodyTagSupport{
private String val;
private String defaultVal;
public void setVal(String val) {
this.val = val;
}
// Method to set the default value when it is empty
public void setDefaultVal(String defaultVal) {
this.defaultVal = defaultVal;
}
// How to start labels ( What actions need to be added to the customized label , Rewrite the methods in the corresponding life cycle )
@Override
public int doStartTag() throws JspException {
//this.pageContext: Get through the current class pageContext object
//pageContext One of the objects is getOut Write the way
JspWriter out = this.pageContext.getOut();
try {
if(val==null&&val.equals("")) {
out.println(this.defaultVal);
} else {
out.println(this.val);
}
} catch (Exception e) {
e.printStackTrace();
}
// Skip the label body ,out What is defined is an empty tag
return SKIP_BODY;
}
}- if The tag class ( Inherit BodyTagSupport)
@SuppressWarnings("serial")
public class IfTag extends BodyTagSupport{
private boolean test;
public boolean isTest() {
return test;
}
public void setTest(boolean test) {
this.test = test;
}
@Override
public int doStartTag() {
if(this.isTest()) {
// When judging the label body
return EVAL_BODY_INCLUDE;
}
return SKIP_BODY;
}
}- foreach The tag class
public class ForeachTag extends BodyTagSupport {
private List<?> items;
private String var;
public void setItems(List<?> items) {
this.items = items;
}
public void setVar(String var) {
this.var = var;
}
@Override
public int doStartTag() {
if(Objects.isNull(this.items) || this.items.size() <= 0) {
return SKIP_BODY;
}
Iterator<?> it = this.items.iterator();
Object next = it.next();
this.pageContext.setAttribute(var, next);
this.pageContext.setAttribute("iterator", it);
return EVAL_BODY_INCLUDE;
}
@Override
public int doAfterBody() {
Iterator<?> it= (Iterator<?>)this.pageContext.getAttribute("iterator");
if(it.hasNext()) {
this.pageContext.setAttribute(var, it.next());
return EVAL_BODY_AGAIN;
}
return SKIP_BODY;
}
}- select The tag class
public class SelectTag extends BodyTagSupport {
private String id;
private String name;
private List<?> items;
private String cssClass;
private String cssStyle;
private String value;
private String text;
private String selectValue;
public void setText(String text) {
this.text = text;
}
public void setValue(String value) {
this.value = value;
}
public void setSelectValue(String selectValue) {
this.selectValue = selectValue;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setItems(List<?> items) {
this.items = items;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
public void setCssStyle(String cssStyle) {
this.cssStyle = cssStyle;
}
@Override
public int doStartTag() {
JspWriter out = this.pageContext.getOut();
try {
String html = getSelectHtml();
out.print(html);
} catch (Exception e) {
e.printStackTrace();
}
return SKIP_BODY;
}
// By injecting attribute values , To construct the select String of element
private String getSelectHtml() throws Exception {
StringBuilder sb = new StringBuilder();
// What is needed to construct the page select Elements
sb.append("<select id='"+id+ "' name='"+name+"'");
if(!StringUtils.isNullOrEmpty(this.cssClass)) {
sb.append(" class='"+this.cssClass+"'");
}
if(!StringUtils.isNullOrEmpty(this.cssStyle)) {
sb.append(" style='"+this.cssStyle+"'");
}
sb.append(">");
// Cycle generation options
for(Object option: this.items) {
String val = BeanUtils.getProperty(option, this.value);
String txt = BeanUtils.getProperty(option, this.text);
//value="id" text="name"
if(val.equals(this.selectValue)) {
sb.append("<option value='"+val+"' selected>" + txt + "</option>");
} else {
sb.append("<option value='"+val+"' >" + txt + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
}2、 Write tag library description file (tld)
Edit the label you defined with the corresponding format specification in tld In file
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<!-- Tag library descriptor -->
<taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>Simple Tags</short-name>
<uri>/zking</uri>
<tag>
<name>out</name>
<tag-class>com.myjstl.OutTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>val</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>out label val attribute , For output val Value </description>
</attribute>
<attribute>
<name>defaultVal</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description> Used to define default values </description>
</attribute>
</tag>
<tag>
<name>if</name>
<tag-class>com.myjstl.IfTag</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>test</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>if label </description>
</attribute>
</tag>
<tag>
<name>foreach</name>
<tag-class>com.zking.mymvc.tag.ForeachTag</tag-class>
<body-content>jsp</body-content>
<description>foreach label </description>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
<tag>
<name>select</name>
<tag-class>com.zking.mymvc.tag.SelectTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>id</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>cssClass</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>cssStyle</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>text</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>selectValue</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>Detailed explanation
- <tag></tag>: Put all the format specifications of a custom label inside
- <name>out</name>: Represents a custom tag name
- <tag-class>com.zking.mymvc.tag.OutTag</tag-class>: Represents the full class name of the custom label class in the first step ( Here is how to find the custom tag class through the reflection mechanism )
- <body-content>empty</body-content>: Represents no label body , fill jsp It means that there is
<attribute>: Represents the attribute specification in the custom tag class <name>val</name>: Custom attribute name
<required>true</required>: The attributes that must be written out in the custom tag
<rtexprvalue>true</rtexprvalue>: Whether attribute values can be used EL expression
<description>out label val attribute , For output val Value </description>: Description of custom attributes
</attribute>
3、 stay JSP Use custom labels on ( test )
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="z" uri="/zking" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setAttribute("name", null);
%>
<!-- out label -->
<z:out val="${name}" defaultVal=" You entered null keyword "/>
<z:if test="${100 == 100}">
test if(100 == 100)
</z:if>
<z:if test="${100 != 200}">
test if(100 != 200)
</z:if>
</body>
</html>summary
That's all for today's sharing , Wonderful next issue continues !
边栏推荐
- Mysql—六大日志
- 【2022新生学习】第二周要点
- "1+1 > 10": potential combination of no code / low code and RPA Technology
- Redis installation
- Unity Metaverse(一)、Ready Player Me & Blender 自定义你的Avatar虚拟人
- Basic concept and deployment of kubernetes
- V自P建N_部署使用
- 死锁、饥饿、死循环之间的区别
- How beautiful can VIM be configured?
- [suctf 2018]multisql (MySQL precompiled)
猜你喜欢
![[suctf 2018]multisql (MySQL precompiled)](/img/ae/501b7f9c6d8259c3c799e4ff0b568b.png)
[suctf 2018]multisql (MySQL precompiled)

SharedPreferences data storage

Governance and network security of modern commercial codeless development platform

云原生(十一) | Kubernetes篇之Kubernetes原理与安装

数字化转型时代的企业数据新基建 | 爱分析报告

JSP之自定义jstl标签

Flutter 组件的生命周期、State 管理及局部重绘 | 开发者说·DTalk

问题随记 —— 无法打开包括文件: “dirent.h”: No such file or directory
![[cloud native] continuous integration and deployment (Jenkins)](/img/3a/2cd6f0c768bd920b3de6d4f5b13cd5.png)
[cloud native] continuous integration and deployment (Jenkins)

MySQL string sorted by numeric value
随机推荐
pgsql误删除pg_wal文件后,服务启动失败
为什么使用opengaussjdbc的时候老是出现FATAL?(标签-数据库|关键词-user)
Translucenttb recommendations
Another award | opensca was selected as the "top ten open source software products in the world" at the China Software Expo
Will the redis delete key command cause blocking?
忘记oracle密码,如何解决
Niuke-top101-bm35
封面 - 电脑知识指南
vulnstack红日-4
AWS Part 1
Differences between LRU and LFU elimination strategies in redis
It's too hard! Tencent T4 boss was still staying up late at 4 a.m. and was actually sorting out the distributed transaction notes
Unity Metaverse(一)、Ready Player Me & Blender 自定义你的Avatar虚拟人
Thermal resistance temperature acquisition based on USB data acquisition card (DAQ) and IO module "suggestions collection"
High cost performance, high anti-interference touch IC that meets a variety of keys: vk3606d, vk3610i, vk3618i have high power voltage rejection ratio
es6把多个class方法合并在一起
再获殊荣 | OpenSCA获选中国软博会“全球十大开源软件产品”
V自P建N_部署使用
[suctf 2018]multisql (MySQL precompiled)
24 道几乎必问的 JVM 面试题,我只会 7 道,你能答出几道?