J2EE基础:jsp标签02

一.j:foreach标签

 forEach助手类:

package com.jiangwenjuan.tag;

import java.util.Iterator;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * <c:forEach items="${clas12}" var="c">
 * 	分析会有两个属性:
 * 	items:list<object>
 * 	var:String
 * 	分析线路返回值:
 * 	第二条:eval_body_include
 * 	第三条:eval_body_again
 * @author 蒋文娟
 *
 * @date 2022年6月20日 下午11:02:18
 */
public class ForeachTag extends BodyTagSupport{
	
	private String var;
	private List<Object> items;
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
	public List<Object> getItems() {
		return items;
	}
	public void setItems(List<Object> items) {
		this.items = items;
	}
	
	@Override
	public int doStartTag() throws JspException {
		//拿到这个迭代器
		Iterator<Object> it = items.iterator();
//		<option value=" where cid='${c.cid}'">${c.cname}</option>
//		var = c,it.next()是集合中的某一个对象
//		pageContext.setAttribute("c", items.get(0));
		//翻译过来就是上面这行代码
		pageContext.setAttribute("var", it.next());
		pageContext.setAttribute("it", it);//为了保留迭代时指针现有位置
		return EVAL_BODY_INCLUDE;
	}
	
	
	//要不要循环,看这个集合有没有数据
	@Override
	public int doAfterBody() throws JspException {
		//拿到之前保留的迭代器
		Iterator<Object>  it = (Iterator<Object>) pageContext.getAttribute("it");
		//如果说它有下一个
		if(it.hasNext()) {//就进入循环
			pageContext.setAttribute("var", it.next());
			pageContext.setAttribute("it", it);//为了保留迭代时指针现有位置
			return EVAL_BODY_AGAIN;
		}
		else {//说明没有下一个
			return EVAL_PAGE;
		}
	}
}

在jiangwenjuan.tld文件中添加一个foreach循环

 <tag>
    <name>for</name>
    <tag-class>com.jiangwenjuan.tag.ForeachTag</tag-class>
    <body-content>JSP</body-content>
    <attribute> 
        <name>items</name>
       <required>true</required> 
       <rtexprvalue>true</rtexprvalue> 
    </attribute>
    <attribute> 
        <name>var</name>
       <required>true</required> 
       <rtexprvalue>false</rtexprvalue> 
    </attribute>
  </tag>

为了测试我们创建一个老师类

package com.jiangwenjuan.entity;

public class Teacher {
	
	private String tid;
	private String tname;
	public String getTid() {
		return tid;
	}
	public void setTid(String tid) {
		this.tid = tid;
	}
	public String getTname() {
		return tname;
	}
	public void setTname(String tname) {
		this.tname = tname;
	}
	
	public Teacher() {
		// TODO Auto-generated constructor stub
	}
	public Teacher(String tid, String tname) {
		super();
		this.tid = tid;
		this.tname = tname;
	}

}

 测试一下:

<%@page import="java.util.ArrayList"%>
<%@page import="com.jiangwenjuan.entity.Teacher"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!-- 引入标签库 -->
    <%@taglib uri="http://jsp.veryedu.cn" prefix="j" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<%
		List<Teacher> list = new ArrayList<>();
		list.add(new Teacher("t001","zs"));
		list.add(new Teacher("t002","李四"));
		list.add(new Teacher("t003","老六"));
		request.setAttribute("list", list);
	%>
	
	<j:for items="${list }" var="t">
		${t.tid }:${t.tname }
	</j:for>

</body>
</html>

 最终结果:

 

二.j:select标签

 1.怎样省略遍历的过程

<j:select></select>

selectTag助手类代码块:

package com.jiangwenjuan.tag;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.persistence.PersistenceUnits;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.beanutils.PropertyUtils;

/**
 * 1.省略遍历的过程
 * 	<j:select></select>
 * 	2.当做数据回显时,无需增加if判断,无需增加新的代码
 * 	
 * <option value=" where cid='${c.cid}'">${c.cname}</option>
 * 	分析:
 * 		1.后台要遍历->数据源->items
 * 		2.需要一个对象的属性代表下拉框对应的展示内容->textVal
 * 		3.需要一个对象的属性代表下拉框对应的value值->textKey
 * 		4.默认的头部选项展示内容->headerTextVal
 * 		5.默认的头部选项值->headerTextKey
 * 		6.数据库中存储的值,为了方便做数据回显->selectedVal
 * 		7.id
 * 		8.name
 * 		9.CSSStyle...
 * @author 蒋文娟
 *
 * @date 2022年6月21日 上午8:27:47
 */
public class SelectTag extends BodyTagSupport{
	private List<Object> items;
	private String textVal;//teacher的name
	private String textKey;
	private String headerTextVal;
	private String headerTextKey;
	private String selectedVal;
	private String id;
	private String name;
	

	@Override
	public int doStartTag() throws JspException {
		//拿到io流
		JspWriter out = pageContext.getOut();
		try {
			out.print(toHTML());
		} catch (IOException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	
	


	private String toHTML() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		StringBuffer sb = new StringBuffer();
		//拼接
		sb.append("<select id='"+id+"' name='"+name+"'>");
		if(headerTextVal != null && !"".equals(headerTextVal)) {
			sb.append("<option value='"+headerTextKey+"'>"+headerTextVal+"</option>");
		}
		for (Object obj : items) {
//			<j:select textVal="name" items="${list }" textKey="tid"></j:select>
			Field textKeyFiled = obj.getClass().getDeclaredField(textKey);//拿到属性值
			textKeyFiled.setAccessible(true);//打开访问权限
			Object value = textKeyFiled.get(obj);//真正下拉框展示的值
													//这里就相当于上面三行代码,就进一步优化了
			sb.append("<option value='"+value+"'>"+PropertyUtils.getProperty(obj, textVal)+"</option>");
			
		}
		sb.append("</select>");
		return sb.toString();
	}




	public List<Object> getItems() {
		return items;
	}
	public void setItems(List<Object> items) {
		this.items = items;
	}
	public String getTextVal() {
		return textVal;
	}
	public void setTextVal(String textVal) {
		this.textVal = textVal;
	}
	public String getTextKey() {
		return textKey;
	}
	public void setTextKey(String textKey) {
		this.textKey = textKey;
	}
	public String getHeaderTextVal() {
		return headerTextVal;
	}
	public void setHeaderTextVal(String headerTextVal) {
		this.headerTextVal = headerTextVal;
	}
	public String getHeaderTextKey() {
		return headerTextKey;
	}
	public void setHeaderTextKey(String headerTextKey) {
		this.headerTextKey = headerTextKey;
	}
	public String getSelectedVal() {
		return selectedVal;
	}
	public void setSelectedVal(String selectedVal) {
		this.selectedVal = selectedVal;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	

}

在原来这段代码块中我们默认了:

private String toHTML() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		StringBuffer sb = new StringBuffer();
		//拼接
		sb.append("<select id='"+id+"' name='"+name+"'>");
		if(headerTextVal != null && !"".equals(headerTextVal)) {
			sb.append("<option value='"+headerTextKey+"'>"+headerTextVal+"</option>");
		}
		for (Object obj : items) {
//			<j:select textVal="name" items="${list }" textKey="tid"></j:select>
			Field textKeyFiled = obj.getClass().getDeclaredField(textKey);//拿到属性值
			textKeyFiled.setAccessible(true);//打开访问权限
			Object value = textKeyFiled.get(obj);//真正下拉框展示的值
											    //这里我们就默认为lisi了
			sb.append("<option value='"+value+"'>lisi</option>");
			
		}
		sb.append("</select>");
		return sb.toString();
	}

 

里面的这段代码:是为了简便上面三行代码的

 

										//这里就相当于上面三行代码,就进一步优化了
			sb.append("<option value='"+value+"'>"+PropertyUtils.getProperty(obj, textVal)+"</option>");
			

 进一步优化了: 

 

在jiangwenjuan.tld里面去加一段select代码块:

<tag>
    <name>select</name>
    <tag-class>com.jiangwenjuan.tag.SelectTag</tag-class>
    <body-content>JSP</body-content>
    <attribute> 
        <name>items</name>
   <!-- 该属性是否必填 -->
       <required>true</required> 
    <!-- 该属性是否支持表达式 -->
       <rtexprvalue>true</rtexprvalue> 
    </attribute>
    <attribute> 
        <name>textVal</name>
       <required>true</required> 
       <rtexprvalue>false</rtexprvalue> 
    </attribute>
    <attribute> 
        <name>textKey</name>
       <required>true</required> 
       <rtexprvalue>false</rtexprvalue> 
    </attribute>
    <attribute> 
        <name>headerTextVal</name>
       <required>false</required> 
       <rtexprvalue>false</rtexprvalue> 
    </attribute>
    <attribute> 
        <name>headerTextKey</name>
       <required>false</required> 
       <rtexprvalue>false</rtexprvalue> 
    </attribute>
    <attribute> 
        <name>selectedVal</name>
       <required>false</required> 
       <rtexprvalue>true</rtexprvalue> 
    </attribute>
    <attribute> 
        <name>id</name>
       <required>false</required> 
       <rtexprvalue>false</rtexprvalue> 
    </attribute>
    <attribute> 
        <name>name</name>
       <required>false</required> 
       <rtexprvalue>false</rtexprvalue> 
    </attribute>
  </tag>

在去测试一下:这是之前的

<select>
		<option value="1">zhangsan</option>
		<option value="2">lisi</option>
</select>

看一下我们简略了之后是是怎么样的 我们还添加了一个,这样就可以弄样式。

<style type="text/css">
	#mySel{
		color: red;
	}
</style>
	<%
		List<Teacher> list = new ArrayList<>();
		list.add(new Teacher("t001","zs"));
		list.add(new Teacher("t002","李四"));
		list.add(new Teacher("t003","老六"));
		request.setAttribute("list", list);
	%>
	
	
	<select>
		<option value="1">zhangsan</option>
		<option value="2">lisi</option>
	</select>
									<!-- -1就是请选择的意思  -->
	<j:select id="mySel" headerTextKey="-1" headerTextVal="==请选择==" textVal="tname" items="${list }" textKey="tid"></j:select>
	
	

最终运行结果:

2.当做数据回显时,无需增加if判断,无需增加新的代码

在selectTag助手类里面加了 toHTML()方法里面加从第二个if哪里。

private String toHTML() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		StringBuffer sb = new StringBuffer();
		//拼接
		sb.append("<select id='"+id+"' name='"+name+"'>");
		if(headerTextVal != null && !"".equals(headerTextVal)) {
			sb.append("<option value='"+headerTextKey+"'>"+headerTextVal+"</option>");
		}
		for (Object obj : items) {
//			<j:select textVal="name" items="${list }" textKey="tid"></j:select>
			Field textKeyFiled = obj.getClass().getDeclaredField(textKey);//拿到属性值
			textKeyFiled.setAccessible(true);//打开访问权限
			Object value = textKeyFiled.get(obj);//真正下拉框展示的值
			
			//当selectedval不等于空的时候,也不等于空字符串,并且它还要等价于下面的哪个value
			if(selectedVal != null &&!"".equals(selectedVal) && selectedVal.equals(value)) {//匹配上了
				sb.append("<option selected value='"+value+"'>"+PropertyUtils.getProperty(obj, textVal)+"</option>");
			}
			else {//这是还没有做匹配的
				//这里就相当于上面三行代码,就进一步优化了
				sb.append("<option value='"+value+"'>"+PropertyUtils.getProperty(obj, textVal)+"</option>");
			}
			
		}
		sb.append("</select>");
		return sb.toString();
	}

 

目前还没有效果,现在我们没有还没有写selectedval,现在我们去写一下. 

    <%
		List<Teacher> list = new ArrayList<>();
		list.add(new Teacher("t001","zs"));
		list.add(new Teacher("t002","李四"));
		list.add(new Teacher("t003","老六"));
		request.setAttribute("list", list);
	%>

<j:select selectedVal="t002" id="mySel" headerTextKey="-1" headerTextVal="==请选择==" textVal="tname" items="${list }" textKey="tid"></j:select>
	

然后我们应该现在回显的李四,因为我们填的是t002,最终效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值