Java-struts2 之值栈问题
这里是根据一个小项目,将数据库的值查出来,然后在页面前台进行遍历的方法
放入值的几种方式:
Struts2的三种存值取值的方式
值栈:
栈上下文:
ActionContext:
package com.sun.action; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.*; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.mysql.jdbc.Connection; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.sun.model.User; public class UserListAction extends ActionSupport{ static PreparedStatement ps = null; static ResultSet rs; public String execute()throws Exception{ Connection con = null; //创建用于连接数据库的Connection对象 List<User> users = new ArrayList<User>(); try { Class.forName("com.mysql.jdbc.Driver");// 加载Mysql数据驱动 con = (Connection) DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/test", "root", "123456");// 创建数据连接 //System.out.println("数据库连接成功"); String sql = "select * from user";// 删除数据的sql语句 ps = (PreparedStatement) con.prepareStatement(sql); rs = ps.executeQuery(); User c = null; while(rs.next()){ c = new User(); c.setAge(rs.getInt("age")); c.setId(rs.getInt("id")); c.setName(rs.getString("name")); c.setSex(rs.getString("sex")); //System.out.println(rs.getString("name")); users.add(c); } con.close(); //关闭数据库连接 } catch (Exception e) { System.out.println("数据库连接失败" + e.getMessage()); } HttpServletRequest request = ServletActionContext.getRequest(); // request.setAttribute("users", users) ; // ActionContext.getContext().put("users", users); ActionContext.getContext().getValueStack().push(users); ActionContext.getContext().getValueStack().push(users); return "list_ok"; } }
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!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>显示用户的列表</title> </head> <body> <table> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> <%-- HttpServletRequest request = ServletActionContext.getRequest(); // request.setAttribute("users", users) ; <s:iterator value="#request.users" > <tr> <td><s:property value="id" /></td> <td><s:property value="name" /></td> <td><s:property value="age" /></td> <td><s:property value="sex" /></td> </tr> </s:iterator> --%> <%-- ActionContext.getContext().put("users", users); <s:iterator value="#users" var="u"> <tr> <td><s:property value="#u.id" /></td> <td><s:property value="#u.name" /></td> <td><s:property value="#u.age" /></td> <td><s:property value="#u.sex" /></td> </tr> </s:iterator> --%> <%-- ActionContext.getContext().getValueStack().push(users); <s:iterator > <tr> <td><s:property value="id" /></td> <td><s:property value="name" /></td> <td><s:property value="age" /></td> <td><s:property value="sex" /></td> </tr> </s:iterator> --%> </table> </body> </html>