在DAO中写了一个查询数据库的代码,不知道是否正确!各位大侠帮忙看看代码,还有,不知道在JSP页面中如何将查询的结果显示出来!
package com.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.bean.addUserBean;
import com.bean.UserBean;
import com.JDBC.GetConnection;
public class DAO {
/**
* 连接数据库
*
*/
private Connection conn;
private PreparedStatement pstat;
String sql = "";
public List getInfo(UserBean user)
{
List users = new ArrayList();; //存放一个用户的所有信息
conn= GetConnection.getConnection();
try
{
String sql = "select * from Data where D_name = ?";
pstat = conn.prepareStatement(sql);
pstat.setString(1, user.getName());
ResultSet rs = pstat.executeQuery();
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String use = rs.getString(3);
String sex = rs.getString(4);
String age = rs.getString(5);
String phone = rs.getString(6);
String qq = rs.getString(7);
String school = rs.getString(8);
String specialty = rs.getString(9);
String address = rs.getString(10);
UserBean user0 = new UserBean(); // 封装每条用户信息
user0.setId(id);
user0.setName(name);
user0.setUse(use);
user0.setSex(sex);
user0.setAge(age);
user0.setPhone(phone);
user0.setQq(qq);
user0.setSchool(school);
user0.setSpecialty(specialty);
user0.setAddress(address);
users.add(user0);
}
rs.close();
pstat.close();
conn.close();
}
catch
(SQLException e)
{
e.printStackTrace();
}
return users;
}
}
------解决方案--------------------
Iterator it=users.iterator();
UserBean user;
while(it.hasNext())
{
user=it.next();
//处理这个对象...
}
------解决方案--------------------
<%@ taglib uri="/struts-tags" prefix="s"%>
<s:iterator value="list">
<s:property value="name"/>
<s:iterator/>
------解决方案--------------------
用jstl ,
<c:forEach var="item" test="${list}" > //${list} list放在request或session里
${item.xxx} //item就遍历出来的,list的对象
</c:forEacn>
------解决方案--------------------
- HTML code
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@page import="org.apache.taglibs.standard.tag.common.core.ForEachSupport"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ page isELIgnored="false" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> </head> <body> <% //在此定义一个List并调用后台方法! List list = DAO.getInfo(); //之后将查出来的数据存入一个地方,session,request,page都行,这里我就存request request.setAttribute("list",list); %> <!-- 之后取出来,可以用struts2标签,也能用JSTL和EL表达式,看你这样子应该是后者! 最上面加上这一行,否则你就用不了JSTL <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 再加上这行,让EL表达式不需要任何载体,不记得是写false,还是true了,你试下!<%@ page isELIgnored="false" %> --> <!-- 下面是用JSTL输出你查出来的LIST --> <!-- 我就当集合中的对象中有AA这个属性,把它输出 --> <c:forEach items="${requestScope.list}" var="list"> ${list.aa} </c:forEach> <!-- 或者下面这样输出也行 --> <% for(int i = 0 ; i < list.size() ; i++){ %> <lable><%=list.get(i).aa %></lable> <% } %> </body></html>什么都好说,给分就好!