05.Struts2中的标签库标签

05.Struts2中的标签库标签

1、Struts2的标签库标签

1.1通用标签

if elseif else:逻辑判断
iterator:在页面上进行迭代
property:获取值栈中的内容
action:请求一个Action
param:请求Action时通过setAttribute携带参数
debug:页面上查看值栈信息
set:向某个作用域中存入元素
url:创建一个URL字符串
sort:对数组或者集合进行排序
comparator:排序器
source:被排序的数据的来源
date:格式化时间日期
name:被格式化的时间日期对象
format:时间日期格式
var:格式化之后的字符串存放在Context区域的key

1.2表单标签

s:form:表单
表单元素
s:textfield:input type=“text”
s:hidden:input type=“hidden”
s:radio
list:*‘qn’:‘群众’,‘gqty’:‘共青团员’,‘少先队员’:‘少先队员’,‘*员’:‘共产员’,‘其 他党派’:‘其他党派’
如果该标签中使用的属性需要使用OGNL表达式从值栈中获取则需要注意属性的类型,如果该属性 属于原本的表单标签,则需要%{OGNL},否则会被当做普通文本

2、OGNL中静态属性与方法的访问

​ @全类名@属性名/方法名
​ *静态属性可以直接访问,如果是静态方法则需要开启配置

3、声明式异常处理

<!-- 配置全局返回页面(错误处理页) -->
<global-results>
    <result name="errorPage">
        /errorInfo.jsp
    </result>
</global-results>
<!-- 错误处理映射集合 -->
<global-exception-mappings>
    <!-- 
    错误处理映射
     result:触发异常后,跳转到那个地方,引用全局返回页
     exception:处理异常的类型
    -->
    <exception-mapping result="errorPage" exception="Exception"></exception-mapping>
</global-exception-mappings>

4、案例:

导入相应的包

配置Filter文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>struts2Test06</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
	<filter>
		<filter-name>dispatcherFilter</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>dispatcherFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app>

struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <!--允许使用后缀访问页面-->
	<constant name="struts.action.extension" value="do,test,action,,"></constant>
    <!--允许页面使用debug标签-->
	<constant name="struts.devMode" value="true"></constant>
	<!-- 允许静态方法调用 -->
	<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
	<package name="user" extends="struts-default" namespace="/user">
		<!-- 配置全局返回页面(错误处理页) -->
		<global-results>
			<result name="errorPage">
				/errorInfo.jsp
			</result>
		</global-results>
		<!-- 错误处理映射集合 -->
		<global-exception-mappings>
			<!-- 
				错误处理映射
					result:触发异常后,跳转到那个地方,引用全局返回页
					exception:处理异常的类型
			 -->
			<exception-mapping result="errorPage" exception="Exception"></exception-mapping>
		</global-exception-mappings>
		
		<action name="toPage" class="com.zb.action.ToErrorAction" method="testError">
			<result>
				/index.jsp
			</result>
		</action>
		
		<action name="userPage" class="com.zb.action.UserAction" method="selectUserInfo">
			<result>
				/index.jsp
			</result>
		</action>
	</package>	
</struts>

jsp页面

page01.jsp

<%@page import="com.opensymphony.xwork2.ActionContext"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    import="java.util.*"
    %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!-- 
		通用标签
			if elseif else:逻辑判断
			iterator:在页面上进行迭代
			property:获取值栈中的内容
			action:请求一个Action
			param:请求Action时通过setAttribute携带参数
			debug:页面上查看值栈信息
			set:向某个作用域中存入元素
			url:创建一个URL字符串
			sort:对数组或者集合进行排序
			comparator:排序器
				source:被排序的数据的来源
			date:格式化时间日期
				name:被格式化的时间日期对象
				format:时间日期格式
				var:格式化之后的字符串存放在Context区域的key
		表单标签
			
	 -->
	 
	 <s:url value="user/userPage" var="myUrl"></s:url>
	 <s:property value="myUrl"/>
	 
	 <%
	 	List<Integer> numberList = new ArrayList<Integer>();
	 	Random rd = new Random();
	 	for(int i=0;i<20;i++){
		 	numberList.add(rd.nextInt(1000));
	 	}
	 	out.print(numberList+"<hr/>");
	 
	 	request.setAttribute("numberList", numberList);
	 	
	 	Comparator c = new Comparator(){
	 		@Override
	 		public int compare(Object o1, Object o2) {
	 			Integer num1 = (Integer)o1;
	 			Integer num2 = (Integer)o2;
	 			if(num1<num2){
		 			return 0;
	 			}
	 			return -1;
	 		}
	 	};
	 	
	 	ActionContext.getContext().getValueStack().getContext().put("comp", c);
	 	
	 	//numberList.sort(c);
	 	//out.print(numberList+"<hr/>");
	 %>
	 
	 <s:sort comparator="#comp" source="#request.numberList">
	 	<s:iterator var="n">
	 		<s:property value="n"/><br/>
	 	</s:iterator>
	 </s:sort>
	 
	<%
		ActionContext.getContext().getValueStack().getContext().put("now", new Date());
	%>	 
	<s:date name="#now" format="yyyy年MM月dd日 HH时mm分ss秒" var="localDate"/>
	 <s:property value="#localDate"/>
	 
	 <s:debug></s:debug>
</body>
</html>

page02.jsp

<%@page import="com.opensymphony.xwork2.ActionContext"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	.c1{
		border:2px solid red;
	}
</style>
</head>
<body>
	 <%
		request.setAttribute("defaultName", "蓝朋友");
	 %>
<!-- 
		通用标签
			if elseif else:逻辑判断
			iterator:在页面上进行迭代
			property:获取值栈中的内容
			action:请求一个Action
				param:请求Action时通过setAttribute携带参数
			debug:页面上查看值栈信息
			set:向某个作用域中存入元素
			
			url:创建一个URL字符串
			sort:对数组或者集合进行排序
				comparator:排序器
				source:被排序的数据的来源
			date:格式化时间日期
				name:被格式化的时间日期对象
				format:时间日期格式
				var:格式化之后的字符串存放在Context区域的key
		表单标签
			s:form:表单
			表单元素
				s:textfield:input type="text"
				s:hidden:input type="hidden"
				s:radio
					list:*'qn':'群众','gqty':'共青团员','少先队员':'少先队员','*员':'*员','其他党派':'其他党派' 
	 		如果该标签中使用的属性需要使用OGNL表达式从值栈中获取
	 			则需要注意属性的类型,如果该属性属于原本的表单标签,则需要%{OGNL},否则会被当做普通文本
	 -->
	 
	 <form>
	 	<input type="text" name="name">
	 	<input type="hidden" name="hid" value="haha"><br/>
	 	<label>
	 	<input type="radio" name="sex" value="女">女
	 	</label>
	 	<label>
	 	<input type="radio" name="sex" value="男">男
	 	</label>
	 </form>
	 

	 <s:debug></s:debug>
	 <s:form>
	 	<s:textfield class="c1" label="姓名" value="%{#request.defaultName}"></s:textfield>
		<s:hidden name="idh" value="123456"></s:hidden>
		<s:radio list="#{'qn':'群众','gqty':'共青团员','少先队员':'少先队员','*员':'*员','其他党派':'其他党派' }" name="zzmm" label="政治面貌"></s:radio>
		<s:checkboxlist list="#{'gf':'干饭','ps':'爬山','gg':'逛该' }" name="hobs" label="爱好"></s:checkboxlist>
		<s:file name="tx" label="头像"></s:file>
		<s:submit label="提交" value="登录"></s:submit>
	 </s:form>
</body>
</html>

page03.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	out.print(Math.PI);
%>
<br/>
<s:property value="@java.lang.Math@PI"/><br/>
<s:property value="@java.lang.Math@pow(3,3)"/><br/>
<hr/>
<s:property value="@com.zb.common.StaticSource@name"/><br/>
<s:property value="@com.zb.common.StaticSource@age"/><br/>
<s:property value="@com.zb.common.StaticSource@getNowDate()"/><br/>
</body>
</html>

page04.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <!--异常类处理-->
<%
	int num = 20/0;
%>

</body>
</html>

index.jsp

<%@page import="com.opensymphony.xwork2.ActionContext"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	request:<%=request.hashCode() %><br/>
	ActionContext:<%=ActionContext.getContext().hashCode() %><br/>
	ValueStack:<%=ActionContext.getContext().getValueStack().hashCode() %><br/>
	<s:action name="userPage" namespace="/user">
		<s:param name="pageNo">3</s:param>
	</s:action>
	<h1>首页!</h1>
	<s:iterator value="#request.uis" var="ui">
		<s:property value="#ui"/><br/>
	</s:iterator>
	
	<!-- 
		通用标签
			if elseif else:逻辑判断
			iterator:在页面上进行迭代
			property:获取值栈中的内容
			action:请求一个Action
			param:请求Action时通过setAttribute携带参数
			debug:页面上查看值栈信息
			set:向某个作用域中存入元素
	 -->
	
	<s:set var="myName" scope="request" value="#ui.userName"></s:set>
	
	<s:debug></s:debug>
</body>
</html>

errorInfo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>程序里面出错啦!</h1>
<s:debug></s:debug>
<s:property value="[0].exception"/>
</body>
</html>

action类

package com.zb.action;

import java.sql.SQLException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.util.ValueStack;
import com.zb.dao.UserDao;
import com.zb.entity.UserInfo;

public class UserAction implements Preparable,ModelDriven<UserInfo> {

	public String selectUserInfo() throws SQLException {
		ActionContext ac = ActionContext.getContext();

		System.out.println("Action:!!!!!");
		
		System.out.println("request:"+ServletActionContext.getRequest().hashCode());
		
		UserDao ud = new UserDao();

		List<UserInfo> listUserInfo = ud.selectUserInfoByPager(pageNo);

		//root context
		//获得Action容器
		
		System.out.println("ActionContext:"+ac.hashCode());
		
		//获得值栈
		ValueStack vs = ac.getValueStack();

		System.out.println("ValueStack:"+vs.hashCode());
		
		//向值栈的Context区域存入学生信息集合
		//vs.getContext().put("uis", listUserInfo);

		Map<String,Object> request = (Map<String,Object>)ac.get("request");
		
		request.put("uis", listUserInfo);
		
		return "success";
	}

	private Integer pageNo=1;

	public Integer getPageNo() {
		return pageNo;
	}

	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}

	@Override
	public void prepare() throws Exception {
		
	}

	@Override
	public UserInfo getModel() {
		return new UserInfo();
	}
}
package com.zb.action;

public class ToErrorAction {
	public String testError() {
		
		int num = 10/0;
		
		return "success";
	}
}

common数据库工具类

package com.zb.common;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtil {
	private static ComboPooledDataSource dataSource;
	
	static {
		dataSource = new ComboPooledDataSource();
		
		try {
			dataSource.setDriverClass("com.mysql.jdbc.Driver");
			dataSource.setJdbcUrl("jdbc:mysql:///user_db?characterEncoding=UTF-8");
			dataSource.setUser("root");
			dataSource.setPassword("123456");
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		
	}
	
	public static Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void disConnect(Connection conn) {
		try {
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
package com.zb.common;

import java.util.Date;

public class StaticSource {
	public static String name = "吕朋友";
	public static String age = "68";
	
	public static String getNowDate() {
		return new Date().toLocaleString();
	}
	
}

dao类

package com.zb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zb.common.DBUtil;
import com.zb.entity.UserInfo;

/**
 * 用户信息DAO类
 * @author Java53
 *
 */
public class UserDao {

	/**
	 * 分页查询用户信息
	 * @param pageNo 页码
	 * @return 用户信息集合
	 * @throws SQLException
	 */
	public List<UserInfo> selectUserInfoByPager(int pageNo) throws SQLException {
		Connection conn = DBUtil.getConnection();
		PreparedStatement pst = conn.prepareStatement(" SELECT * FROM user_info LIMIT " + ((pageNo - 1) * 3) + ",3 ");
		ResultSet res = pst.executeQuery();
		List<UserInfo> listUserInfo = new ArrayList<UserInfo>();
		while (res.next()) {
			UserInfo userInfo = new UserInfo(
					res.getInt(1), 
					res.getString(2), 
					res.getInt(3), 
					res.getString(4),
					res.getString(5), 
					res.getString(6), 
					res.getDate(7));
			listUserInfo.add(userInfo);
		}

		return listUserInfo;
	}
}

entity类(实体类)

package com.zb.entity;

import java.util.Date;

/**
 * 用户信息实体类
 * @author Java53
 *
 */
public class UserInfo {
	private Integer id;
	private String userName;
	private Integer userAge;
	private String userSex;
	private String userEmail;
	private String userAddress;
	private Date registerTime;

	public UserInfo() {
		super();
	}

	public UserInfo(Integer id, String userName, Integer userAge, String userSex, String userEmail, String userAddress,
			Date registerTime) {
		super();
		this.id = id;
		this.userName = userName;
		this.userAge = userAge;
		this.userSex = userSex;
		this.userEmail = userEmail;
		this.userAddress = userAddress;
		this.registerTime = registerTime;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Integer getUserAge() {
		return userAge;
	}

	public void setUserAge(Integer userAge) {
		this.userAge = userAge;
	}

	public String getUserSex() {
		return userSex;
	}

	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}

	public String getUserEmail() {
		return userEmail;
	}

	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}

	public String getUserAddress() {
		return userAddress;
	}

	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}

	public Date getRegisterTime() {
		return registerTime;
	}

	public void setRegisterTime(Date registerTime) {
		this.registerTime = registerTime;
	}

	@Override
	public String toString() {
		return "UserInfo [id=" + id + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex
				+ ", userEmail=" + userEmail + ", userAddress=" + userAddress + ", registerTime=" + registerTime + "]";
	}

}

mysort(排序)

package com.zb.mysort;

import java.util.Arrays;
import java.util.List;

public class TestMain01 {
	public static void main(String[] args) {
		
		Integer[] nums = {45,4686,4564,6,874,531,341,5341,35,41,35,41};
		List<Integer> listNumber = Arrays.asList(nums);
		
		System.out.println(listNumber);
		
		listNumber.sort((Integer o1, Integer o2)-> {
				if(o1>o2) {
					return 0;
				}
					return -1;
				}
		);
		
		System.out.println(listNumber);
	}
}
上一篇:【Struts2】Struts2框架访问Servlet API


下一篇:【漏洞预警】国家信息安全漏洞共享平台曝光Apache Struts2存在远程代码执行漏洞