当前位置:网站首页>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 !
边栏推荐
- 软件详细设计模板
- 将.calss文件转为.jar-idea篇
- MySQL - master-slave replication
- After effects tutorial, how to create animation in after effects?
- Using mobile phones too much may lose your job
- High cost performance, high anti-interference touch IC that meets a variety of keys: vk3606d, vk3610i, vk3618i have high power voltage rejection ratio
- Reproduce various counter attack methods
- From the big guy baptism! 2022 headline first hand play MySQL advanced notes, and it is expected to penetrate P7
- W3C introduces decentralized identifier as web standard
- Flutter | firstWhere 报错问题
猜你喜欢

Day14 function module

JSP之自定义jstl标签

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

High cost performance, high anti-interference touch IC that meets a variety of keys: vk3606d, vk3610i, vk3618i have high power voltage rejection ratio

Three handling strategies of deadlock

FPGA HLS multiplier (pipeline vs. ordinary simulation)
![[cloud native] continuous integration and deployment (Jenkins)](/img/3a/2cd6f0c768bd920b3de6d4f5b13cd5.png)
[cloud native] continuous integration and deployment (Jenkins)

js过滤/替换敏感字符

【2022新生学习】第二周要点

激光共聚焦如何选择荧光染料
随机推荐
JS filter / replace sensitive characters
Why is apple x charging slowly_ IPhone 12 supports 15W MagSafe wireless charging. What will happen to iPhone charging in the future_ Charger
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
Don't want dto set. Dto can be written like this
苹果x充电慢是什么原因_iPhone 12支持15W MagSafe无线充电,未来苹果手机的充电会发生什么?_充电器…
黑马程序员-接口测试-四天学习接口测试-第三天-postman高级用法,newman例集导出导入,常用断言,断言json数据,工作原理,全局,环境变量,时间戳,请求前置脚本,关联,批量执行测试用例
[in simple terms] from self information to entropy, from relative entropy to cross entropy, nn Crossentropyloss, cross entropy loss function and softmax, multi label classification
满足多种按键的高性价比、高抗干扰触摸IC:VK3606D、VK3610I、VK3618I 具有高电源电压抑制比
软件详细设计模板
WSAStartup函数的用途
Another award | opensca was selected as the "top ten open source software products in the world" at the China Software Expo
Jianzhi offer II 115. reconstruction sequence: topological sorting construction problem
Do you know why PCBA circuit board is warped?
1060 Are They Equal
Bean validation specification ----03
Who is responsible for the problems of virtual anchor and idol endorsement products? Lawyer analysis
Redis' expiration strategy and memory elimination mechanism. Why didn't you release memory when the key expired
ICML 2022 | 稀疏双下降:网络剪枝也能加剧模型过拟合?
Governance and network security of modern commercial codeless development platform
Flutter | 指定页面回传值的类型