jstl标签库的配置

jstl标签库的配置
* 将jstl.jar和standard.jar拷贝到WEB-INF/lib下(如果使用el表达式,不用拷贝这两个jar)

注意:jstl必须在能够支持j2ee1.4/servlet2.4/jsp2.0版本上的容器才能运行,这个环境
     是目前较为常用的环境

    
标签库的使用
* 采用taglib指令引入
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%> 
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>


自定义函数库:
1、定义类和方法(方法必须是public static)
2、编写自定义tld文件,并且将此文件放到WEB-INF或WEB-INF任意子目录下
3、在jsp中采用taglib指令引入自定义函数库
4、采用 前缀+冒号+函数名 调用即可

Use.java


package com.bjsxt.struts;

public class User {
	
	private String username1;
	
	private int age;
	
	private Group group;

	public String getUsername() {
		return username1;
	}

	public void setUsername(String username) {
		this.username1 = username;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Group getGroup() {
		return group;
	}

	public void setGroup(Group group) {
		this.group = group;
	}
	
	
}



Group.java


package com.bjsxt.struts;

public class Group {
	
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


JstlElAction.java


package com.bjsxt.struts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * 测试EL表达式
 * @author Administrator
 *
 */
public class JstlElAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//普通字符串
		request.setAttribute("hello", "hello world");
		
		//结构
		Group group = new Group();
		group.setName("尚学堂");
		
		User user = new User();
		user.setUsername("张三");
		user.setAge(18);
		user.setGroup(group);
		
		request.setAttribute("user", user);
		
		//map
		Map mapValue  = new HashMap();
		mapValue.put("key1", "value1");
		mapValue.put("key2", "value2");
		
		request.setAttribute("mapvalue", mapValue);
		
		//字符串数组
		String[] strArray = new String[]{"a", "b", "c"};
		request.setAttribute("strarray", strArray);
		
		User[] users = new User[10];
		for (int i=0; i<10; i++) {
			User u = new User();
			u.setUsername("U_" + i);
			users[i] = u;
		}
		request.setAttribute("users", users);
		
		List userList = new ArrayList();
		for (int i=0; i<10; i++) {
			User uu = new User();
			uu.setUsername("UU_" + i);
			userList.add(uu);
		}
		request.setAttribute("userlist", userList);
		
		//empty
		request.setAttribute("value1", null);
		request.setAttribute("value2", "");
		request.setAttribute("value3", new ArrayList());
		request.setAttribute("value4", "123456");
		return mapping.findForward("success");
	}

	
}


jstl_el.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!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=GB18030">
<title>测试EL表达式</title>
</head>
<body>
	<h1>测试EL表达式</h1><br>
	<hr>
	<li>普通字符串</li><br>
	hello(jsp脚本):<%=request.getAttribute("hello") %><br>
	hello(el表达式,el表达式的使用方法$和{}):${hello }<br>
	hello(el表达式,el的隐含对象pageScope,requestScope,sessionScope,applicationScope,<br> 如果未指定scope,它的搜索顺序为pageScope~applicationScope):${requestScope.hello }<br>
	hello(el表达式,scope=session):${sessionScope.hello }<br>
	<p>
	<li>结构,采用.进行导航,也称存取器</li><br>
	姓名:${user.username }<br>
	年龄:${user.age }<br>
	所属组:${user.group.name }<br>
	<p>
	<li>输出map,采用.进行导航,也称存取器</li><br>
	mapvalue.key1:${mapvalue.key1 }<br>
	mapvalue.key2:${mapvalue.key2 }<br>
	<p>
	<li>输出数组,采用[]和下标</li><br>
	strarray[2]:${strarray[1] }<br>
	<p>
	<li>输出对象数组,采用[]和下标</li><br>
	userarray[3].username:${users[2].username }<br>
	<p>
	<li>输出list,采用[]和下标</li><br>
	userlist[5].username:${userlist[4].username }<br>
	<p>
	<li>el表达式对运算符的支持</li><br>
	1+2=${1+2 }<br>
	10/5=${10/5 }<br>
	10 div 5=${10 div 5 }<br>
	10%3=${10 % 3 }<br>
	10 mod 3=${10 mod 3 }<br>
	<!--
		 ==/eq
		 !=/ne 
		 </lt
		 >/gt
		 <=/le
		 >=/ge
		 &&/and
		 ||/or
		 !/not
		 //div
		 %/mod
	 -->  
	 <li>测试empty</li><br>
	 value1:${empty value1 }<br>
	 value2:${empty value2 }<br>
	 value3:${empty value3 }<br>
	 value4:${empty value4 }<br>
	 value4:${!empty value4 }<br>
</body>
</html>



JstlCoreAction.java


package com.bjsxt.struts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * 测试jstl核心库
 * @author Administrator
 *
 */
public class JstlCoreAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//普通属性
		request.setAttribute("hello", "Hello World");
	
		//测试条件控制标签
		request.setAttribute("v1", 1);
		request.setAttribute("v2", 2);
		request.setAttribute("v3", new ArrayList());
		request.setAttribute("v4", "test");
		
		//html文本
		request.setAttribute("bj", "<font color='red'>北京欢迎您</font>");
		
		
		//测试c:forEach
		Group group = new Group();
		group.setName("尚学堂");
		
		List userList = new ArrayList();
		for (int i=0; i<10; i++) {
			User user = new User();
			user.setUsername("user_" + i);
			user.setAge(18+i);
			user.setGroup(group);
			userList.add(user);
		}
		
		request.setAttribute("userlist", userList);
		
		//测试循环输出map
		Map map = new HashMap();
		map.put("k1", "v1");
		map.put("k2", "v2");
		request.setAttribute("mapvalue", map);
		
		//测试c:forTokens
		request.setAttribute("strTokens", "1,2,3,4,5,6");
		return mapping.findForward("success");
	}

}



jstl_core.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>    
<!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=GB18030">
<title>测试jstl核心库</title>
</head>
<body>
	<h1>测试jstl核心库</h1>
	<hr>
	<li>测试c:out</li><br>
	hello(default):<c:out value="${hello}"/><br>
	hello(el表达式):${hello }<br>
	hello(default="123"):<c:out value="${abc}" default="123"/><br>
	hello(default="123"):<c:out value="${abc}">123</c:out><br>
	bj(defalut):<c:out value="${bj}"/><br>
	bj(escapeXml="true"):<c:out value="${bj}" escapeXml="true"/><br>
	bj(escapeXml="false"):<c:out value="${bj}" escapeXml="false"/><br>
	bj(el表达式):${bj }<br>
	<p>
	<li>测试c:set和c:remove</li><br>
	<c:set value="123" var="temp"/>
	temp:${temp }<br>
	<c:remove var="temp"/>
	temp:${temp }<br>
	<p>
	<li>测试条件控制标签c:if</li><br>
	<c:if test="${v1 lt v2}" var="v">
		v1小于v2<br>v=${v }<br>
	</c:if>
	<c:if test="${empty v3}">
		v3为空<br>
	</c:if>
	<c:if test="${empty v4}">
		v4为空<br>
	</c:if>
	<p>
	<li>测试条件控制标签c:choose,c:when,c:otherwise</li><br>
	<c:choose>
		<c:when test="${v1 lt v2}">
			v1小于v2<br>
		</c:when>
		<c:otherwise>
			v1大于v2<br>
		</c:otherwise>
	</c:choose>
	<c:choose>
		<c:when test="${empty v4}">
			v4为空<br>
		</c:when>
		<c:otherwise>
			v4不为空<br>
		</c:otherwise>
	</c:choose>
	<p>
	<li>测试循环控制标签c:forEach</li><br>
	<table border="1">
		<tr>
			<td>姓名</td>
			<td>年龄</td>
			<td>所属组</td>
		</tr>
		<c:choose>
			<c:when test="${empty userlist}">
				<tr>
					<td colspan="3">没有符合条件的数据!</td>
				</tr>
			</c:when>
			<c:otherwise>
				<c:forEach items="${userlist}" var="u">
					<tr>
						<td>${u.username }</td>
						<td>${u.age }</td>
						<td>${u.group.name }</td>
					</tr>
				</c:forEach>
			</c:otherwise>
		</c:choose>
	</table>	
	<p>	
	<li>测试循环控制标签c:forEach,varstatus</li><br>
	<table border="1">
		<tr>
			<td>姓名</td>
			<td>年龄</td>
			<td>所属组</td>
		</tr>
		<c:choose>
			<c:when test="${empty userlist}">
				<tr>
					<td colspan="3">没有符合条件的数据!</td>
				</tr>
			</c:when>
			<c:otherwise>
				<c:forEach items="${userlist}" var="user" varStatus="vs">
					<c:choose>
						<c:when test="${vs.count % 2 == 0}">
							<tr bgcolor="red">
						</c:when>
						<c:otherwise>
							<tr>
						</c:otherwise>
					</c:choose>
					     <tr>
								<td>
									<c:out value="${user.username}"/>
								</td>
								<td>
									<c:out value="${user.age}"/>
								</td>
								<td>
									<c:out value="${user.group.name}"/>
								</td>
							</tr>					
				</c:forEach>
			</c:otherwise>
		</c:choose>
	</table>
	<p>
	<li>测试循环控制标签c:forEach,begin,end,step</li><br>
	<table border="1">
		<tr>
			<td>姓名</td>
			<td>年龄</td>
			<td>所属组</td>
		</tr>
		<c:choose>
			<c:when test="${empty userlist}">
				<tr>
					<td colspan="3">没有符合条件的数据!</td>
				</tr>
			</c:when>
			<c:otherwise>
				<c:forEach items="${userlist}" var="user" begin="2" end="8" step="2">
					<tr>
						<td>${user.username}</td>
						<td>${user.age}</td>
						<td>${user.group.name }</td>
					</tr>
				</c:forEach>
			</c:otherwise>
		</c:choose>
	</table>	
	<p>
	<li>测试循环控制标签c:forEach,普通循环</li><br>
	<c:forEach begin="1" end="10">
		a<br>
	</c:forEach>
	<p>
	<li>测试循环控制标签c:forEach,输出map</li><br>
	<c:forEach  items="${mapvalue}" var="v">
		${v.key }=${v.value }<br>
	</c:forEach>
	<p>
	<li>测试循环控制标签c:forTokens</li><br>
	<c:forTokens items="${strTokens}" delims="," var="v">
		${v }<br>
	</c:forTokens>
	<p>
	<li>测试c:catch</li><br>
	<%
		try {
			Integer.parseInt("asdfsdf");
		}catch(Exception e) {
			out.println(e.getMessage());
		}	
	%>
	<p>
	<c:catch var="exinfo">
		<%
			Integer.parseInt("asdfsdf");
		%>
	</c:catch>
	${exinfo }<br>
	<p>
	<li>测试c:import</li><br>
	<c:import url="http://localhost:8080/struts_login"/>
	<p>
	<li>测试c:url和c:param</li><br>
	<c:url value="http://localhost:8080/drp/sysmgr/user_add.jsp" var="v">
		<c:param name="username" value="Jack"/>
		<c:param name="age" value="20"/>
	</c:url>
	${v }<br>
	<li>测试:redirect</li><br>
	<c:redirect context="/struts_login" url="/index.jsp"/>
</body>
</html>



JstlFmtAction.java


package com.bjsxt.struts;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * 测试jstl格式化库
 * @author Administrator
 *
 */
public class JstlFmtAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		request.setAttribute("today", new Date());
		
		request.setAttribute("n", 123456.123);
		
		request.setAttribute("p", 0.12345);
		return mapping.findForward("success");
	}
	
	
}


jstl_fmt.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>    
<!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=GB18030">
<title>测试jstl格式化库</title>
</head>
<body>
	<h1>1983测试jstl格式化库</h1>
	<hr>
	<li>测试日期的格式化</li><br>
	today(default):<fmt:formatDate value="${today}"/><br>
	today(type="date"):<fmt:formatDate value="${today}" type="date"/><br>
	today(type="time"):<fmt:formatDate value="${today}" type="time"/><br>
	today(type="both"):<fmt:formatDate value="${today}" type="both"/><br>
	today(dateStyle="short"):<fmt:formatDate value="${today}" dateStyle="short"/><br>
	today(dateStyle="medium"):<fmt:formatDate value="${today}" dateStyle="medium"/><br>
	today(dateStyle="long"):<fmt:formatDate value="${today}" dateStyle="long"/><br>
	today(dateStyle="full"):<fmt:formatDate value="${today}" dateStyle="full"/><br>
	today(pattern="yyyy/MM/dd HH:mm:ss"):<fmt:formatDate value="${today}" pattern="yyyy/MM/dd HH:mm:ss"/><br>
	today(pattern="yyyy/MM/dd HH:mm:ss"):<fmt:formatDate value="${today}" pattern="yyyy/MM/dd HH:mm:ss" var="d"/><br>
	${d }<br>
	<p>
	<li>测试数字的格式化</li><br>
	n(default):<fmt:formatNumber value="${n}"/><br>
	n(pattern="###,###.##"):<fmt:formatNumber value="${n}" pattern="###,###.##"/><br>
	n(pattern="###,###.0000"):<fmt:formatNumber value="${n}" pattern="###,###.0000"/><br>
	n(groupingUsed="false"):<fmt:formatNumber value="${n}" groupingUsed="false"/><br>
	n(minIntegerDigits="10"):<fmt:formatNumber value="${n}" minIntegerDigits="10"/><br>
	n(type="currency"):<fmt:formatNumber value="${n}" type="currency"/><br>
	n(type="currency"):<fmt:formatNumber value="${n}" type="currency" currencySymbol="$"/><br>
	n(type="percent"):<fmt:formatNumber value="${p}" type="percent" maxFractionDigits="2" minFractionDigits="2"/><br>
</body>
</html>




JstlFnAction.java


package com.bjsxt.struts;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * 测试jstl函数库
 * @author Administrator
 *
 */
public class JstlFnAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setAttribute("hello", "hello world");
		
		List list = new ArrayList();
		list.add("t1");
		list.add("t2");
		
		request.setAttribute("list", list);
		
		request.setAttribute("name", "Tom");
		return mapping.findForward("success");
	}

}


MyFunctions.java


package com.bjsxt.struts;

public class MyFunctions {
	
	/**
	 * 方法必须是public static
	 * @param name
	 * @return
	 */
	public static String sayHello(String name) {
		return "Hello " + name;
	}
}



MyFunctions.tld

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
    
  <description>my functions library</description>
  <display-name>my functions</display-name>
  <tlib-version>1.0</tlib-version>
  <short-name>my</short-name>
  <uri>http://www.bjsxt.com/functions</uri>
  
  <function>
    <name>sayHello</name>
    <function-class>com.bjsxt.struts.MyFunctions</function-class>
    <function-signature>java.lang.String sayHello(java.lang.String)</function-signature>
  </function>
  
</taglib>



struts-config.xml


<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>

	<action-mappings>
		<action path="/jstlel"
				type="com.bjsxt.struts.JstlElAction"
		>
			<forward name="success" path="/jstl_el.jsp"/>
		</action>
		
		<action path="/jstlcore"
				type="com.bjsxt.struts.JstlCoreAction"
		>
			<forward name="success" path="/jstl_core.jsp"/>
		</action>
		
		<action path="/jstlfmt"
				type="com.bjsxt.struts.JstlFmtAction"
		>
			<forward name="success" path="/jstl_fmt.jsp"/>
		</action>
		
		<action path="/jstlfn"
				type="com.bjsxt.struts.JstlFnAction"
		>
			<forward name="success" path="/jstl_fn.jsp"/>
		</action>
		
	</action-mappings>
</struts-config>


Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- Standard Action Servlet Configuration (with debugging) -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>


  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>  
</web-app>



jstl_fn.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>   
<%@ taglib prefix="my" uri="http://www.bjsxt.com/functions"%> 
<!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=GB18030">
<title>测试jstl函数库</title>
</head>
<body>
	<h1>测试jstl函数库</h1>
	<hr>
	hello.length=(jsp脚本):<%=((String)request.getAttribute("hello")).length() %><br>
	hello.length(jstl函数库,函数调用必须在el表达式中 前缀+冒号+函数名):${fn:length(hello) }<br>
	list.length:${fn:length(list) }<br>
	<p>
	<li>测试自定义函数库</li><br>
	${my:sayHello(name) }<br>
</body>
</html>



你可能感兴趣的:(java,apache,C++,jsp,struts)