当前位置:网站首页>JSP custom tag (the custom way of foreach tag and select tag)
JSP custom tag (the custom way of foreach tag and select tag)
2022-07-21 19:23:00 【Champion_ me】
The content of this article is mainly to use customization JSP Labels are more skilled
One 、 Customize foreach label
The first step is to create a label processing class
ForeachTag.java
package com.zking.mymvc.tag;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import javax.servlet.jsp.tagext.BodyTagSupport;
/** * Helper , Tag handling class * @author zjjt * */
public class ForeachTag extends BodyTagSupport {
// I want to make a legal label processing class for him , Then we must extends BodyTagSupport
// Store data source
private List<?> items;// because foreach Labels need to be cycled , So you need a cyclic result set
// The objects obtained in each cycle are put into pageContext in , And var The value of the property is key Preservation
// Example : Label on page var Property specified as item, Then the objects taken out in each cycle (obj) This will be done as follows :
//pageContext.setAttribute("item", obj);
// You can use EL Expression gets the attribute in the object , Such as : ${item.name}
private String var;
// need get( Don't write ) and set Method
public void setItems(List<?> items) {
this.items = items;
}
public void setVar(String var) {
this.var = var;
}
@Override
public int doStartTag() {
// The next step is judgment
if(Objects.isNull(this.items)||this.items.size()<=0) {
// It is empty or the set is empty
return SKIP_BODY;// There is no data to process , Just skip
}
Iterator<?> it = this.items.iterator();// iterator
Object next = it.next();// Got an object
this.pageContext.setAttribute(var, next);// Get page object , Put objects in pageContext Scope ( Another page is available )
this.pageContext.setAttribute("iterator", it);// Put the iterator in pageContext
return EVAL_BODY_INCLUDE;// Return to this to continue processing the label body , call doAfterBody
}
@Override
public int doAfterBody() {
// What we need to do is to judge whether this method has value , If there is value, continue to return the call
Iterator<?> it = (Iterator<?>)this.pageContext.getAttribute("iterator");// This is the iterator obtained
if(it.hasNext()) {
// If you find that there is still value in it
this.pageContext.setAttribute(var, it.next());
return EVAL_BODY_AGAIN;
}
return SKIP_BODY;
}
}
The second step is to establish a test data auxiliary class
Book.java
package com.zking.mymvc.model;
public class Book {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + "]";
}
}
TestData.java
package com.zking.mymvc.model;
import java.util.ArrayList;
import java.util.List;
public class TestData {
public static List<Book> getBooks(){
List<Book> books = new ArrayList<>();
Book b1 = new Book();
b1.setId(1);
b1.setName(" Water margin ");
Book b2 = new Book();
b2.setId(2);
b2.setName(" A dream of red mansions ");
Book b3 = new Book();
b3.setId(3);
b3.setName(" Journey to the west ");
books.add(b1);
books.add(b2);
books.add(b3);
return books;
}
}
The third step is to write in the tag description library foreach
<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>
We will test it at the end
The next step is to customize select label
Two 、 Customize select label
It's the same , The first step is to establish a label processor
SelectTag.java
package com.zking.mymvc.tag;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.beanutils.BeanUtils;
import com.mysql.jdbc.StringUtils;
public class SelectTag extends BodyTagSupport {
// The attributes defined below are select The properties of the tag
private String id;
private String name;
private List<?> items;
private String cssClass;
private String cssStyle;
private String value;
private String text;
private String selectValue;
// Below is set Method ,get The method is not written
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;
}
public void setValue(String value) {
this.value = value;
}
public void setText(String text) {
this.text = text;
}
public void setSelectValue(String selectValue) {
this.selectValue = selectValue;
}
// Override the doStartTag Method
@Override
public int doStartTag() {
JspWriter out = this.pageContext.getOut();
try {
String html = getSelectHtml();
out.print(html);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SKIP_BODY;
}
private String getSelectHtml() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
StringBuilder sb = new StringBuilder();// Is to put index.jsp That page is dead select Put the label here
// This piece of construction page needs select Elements , After the construction is completed, it will be doStartTag() Write this output method this.pageContext.getOut();
// The main function of this block is to write dead on the page select Elements , Generate by string splicing , And then through this.pageContext.getOut() Throw it on the page
// Functions that can also be done , Is whether the tag has a default value , With default values, we can directly make the default values into the display status
sb.append("<select id='"+id+"' name='"+name+"'");
// then cssClass It's optional , Then we have to judge
if(StringUtils.isNullOrEmpty(this.cssClass)) {
// If this.cssClass Not empty words , We are going to add (append It means adding ),class=null
sb.append("class='"+this.cssClass+"'");
}
if(StringUtils.isNullOrEmpty(this.cssStyle)) {
sb.append("style='"+this.cssStyle+"'");
}
sb.append(">");
// Next is to generate circularly select Labeled option Elements
for(Object option:this.items) {
String val = BeanUtils.getProperty(option, this.value);
String txt = BeanUtils.getProperty(option, this.text);
// Will give me a result set , Get what the role is value and text
// And then concatenate the string
if(val.equals(this.selectValue)) {
// Write default
sb.append("<option value='"+val+"' selected>" + txt + "</option>");
} else {
//
sb.append("<option value='"+val+"' >" + txt + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
}
The third step is to write in the tag description library select
<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>
Another is to test whether the label is available
<%@page import="com.zking.mymvc.model.*,java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- The first step is to introduce the tag library -->
<%@taglib prefix="z" uri="/zking" %><!-- Notice the uri With the tag library uri equally -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- foreach -->
<%
// Get test data
List<Book> books = TestData.getBooks();
// Put in request In the object
request.setAttribute("books", books);
%>
<z:foreach items="${books}" var="book">
${
book.id} -- ${
book.name} <br>
</z:foreach>
<!-- By the following select The label looks like , We can know which properties we need to define in the helper class -->
<!-- <select id="test" name="test" class="" style="width:100px">
<option value="1"> Paid </option>
<option value="1" selected > Shipped </option>
<option value="1"> Signed for </option>
</select> -->
<select id="test" name="test" class="" style="width:100px;">
<option value=0> Paid </option>
<option value= selected> Shipped </option>
<option value=2> Signed for </option>
</select>
<z:select id="test"
name="test" items="${books}" value="id"
text="name" selectValue="3"/>
</body>
</html>
边栏推荐
- [qt primer] Application of window classes
- Don't want to wake up because it's delicious
- How easyexcel exports files in a project
- FTP服务配置
- Configuration du Service FTP
- Distributed High concurrency & high availability
- QT(37)-mosquitto-MQTT客户端
- Distributed Common architectures and service splitting
- The first lesson of programmers is "Hello word". Do you know the first lesson of network engineering?
- C# 数字信号处理工具包 DSP-Core 重采样(Resample)输出点数是多少
猜你喜欢
寻找单身狗--重复两次数字中寻找单个数字
C语言进阶(十四) - 文件管理
分布式.高可用 高可扩展 指标
05 regular expression syntax
Top 10 NFTs at present
分布式.常用架构和服务拆分
Use the mogdb operator to deploy the mogdb cluster (mogdb stack) on kubernetes
Distributed High concurrency & high availability
SAP IDOC教程:定义,结构,类型,格式和表格-019
How to realize copyright protection of Digital Collections
随机推荐
Filter listener
SAP IDOC教程:定义,结构,类型,格式和表格-019
过滤器 监听器
出现“TypeError: ‘str‘ object does not support item assignment”的原因
分布式.高可用 高可扩展 指标
The first lesson of programmers is "Hello word". Do you know the first lesson of network engineering?
What is gamefi?
Software testing interview question: what is the difference between quotation and pointer?
[performance optimization] MySQL common slow query analysis tools
【LeetCode】1260. 二维网格迁移
How easyexcel exports files in a project
Arduino I2C for TCA9548A应答扫描程序
QT(37)-mosquitto-MQTT客户端
Jujube technology CEO's monthly DDC briefing (phase III) -- Introduction to new functions of DDC network and review of essence of Wenchang chain upgrade plan
Mapbox GL development tutorial (13): loading 3D surface layers (white mold)
使用MogDB Operator在Kubernetes上部署MogDB集群(MogDB Stack)
06 提取数据的json字符串
Pytoch environment construction
中国五氯化磷市场调研与投资预测报告(2022版)
分布式.高性能