1.新建配置jdbc数据源,具体过程省略
2.新建实体表
CREATE
TABLE
students
(
stuId int
PRIMARY
KEY
,
NAME
VARCHAR
(20),
age VARCHAR
(20),
)ENGINE=MYISAM
DEFAULT
CHARSET=utf8;
INSERT
INTO
students
(stuId,name
,age
)
VALUES
(
1
,
'张三'
,'18'),
(
2
,
'李四'
,'20'),
(
3
,
'王五'
,'19')
3.新建项目
(1)新建数据库连接工具类JDBCUtils,通过配置数据源获取连接
package com.landingbj.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
public class JDBCUtils {
// 三剑客
Connection con = null;// 连接对象
PreparedStatement pstmt = null;// 语句对象
ResultSet rs = null;// 结果集对象
public Connection getConnection() throws ClassNotFoundException,
SQLException {
try {
InitialContext cxt = new InitialContext();
DataSource ds = (DataSource) cxt.lookup("test");
con = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
}
return con;
}
public void close(ResultSet rs, PreparedStatement pstmt, Connection con) {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public int execUpdate(String sql, Object[] params) {
try {
this.getConnection();// 获得连接对象
this.pstmt = this.con.prepareStatement(sql);// 获得预设语句对象
if (params != null) {
// 设置参数列表
for (int i = 0; i < params.length; i++) {
// 因为问号参数的索引是从1开始,所以是i+1,将所有值都转为字符串形式,好让setObject成功运行
this.pstmt.setObject(i + 1, params[i] + "");
}
}
return this.pstmt.executeUpdate(); // 执行更新,并返回影响行数
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
this.close(this.rs, this.pstmt, this.con);
}
return 0;
}
public List<Map<String, Object>> execQuery(String sql, Object[] params) {
try {
this.getConnection();// 获得连接对象
this.pstmt = this.con.prepareStatement(sql);// 获得预设语句对象
if (params != null) {
// 设置参数列表
for (int i = 0; i < params.length; i++) {
// 因为问号参数的索引是从1开始,所以是i+1,将所有值都转为字符串形式,好让setObject成功运行
this.pstmt.setObject(i + 1, params[i] + "");
}
}
// 执行查询
ResultSet rs = pstmt.executeQuery();
List<Map<String, Object>> al = new ArrayList<Map<String, Object>>();
// 获得结果集元数据(元数据就是描述数据的数据,比如把表的列类型列名等作为数据)
ResultSetMetaData rsmd = rs.getMetaData();
// 获得列的总数
int columnCount = rsmd.getColumnCount();
// 遍历结果集
while (rs.next()) {
Map<String, Object> hm = new HashMap<String, Object>();
for (int i = 0; i < columnCount; i++) {
// 根据列索引取得每一列的列名,索引从1开始
String columnName = StringUtils.upperCase(rsmd
.getColumnName(i + 1));
// 根据列名获得列值
Object columnValue = rs.getObject(columnName);
// 将列名作为key,列值作为值,放入 hm中,每个 hm相当于一条记录
hm.put(columnName, columnValue);
}
// 将每个 hm添加到al中, al相当于是整个表,每个 hm是里面的一条记录
al.add(hm);
}
return al;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
this.close(this.rs, this.pstmt, this.con);
}
return null;
}
}
(2)students实体类
package com.landingbj.entity;
public class Students {
private int stuId;
private String name;
private String age;
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
(3)新建StudentServlet
package com.landingbj.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.landingbj.entity.Students;
import com.landingbj.service.StudentService;
public class StudentServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public StudentServlet() {
super();
}
public void destroy(){
super.destroy();
}
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
StudentService studentService = new StudentService();
List<Students> students = studentService.getAllStudents();
System.out.println(students);
req.setAttribute("students", students);
req.getRequestDispatcher("/studentslist.jsp").forward(req, res);
}
}
(4)新建StudentService
package com.landingbj.service;
import java.util.List;
import com.landingbj.dao.StudentDao;
import com.landingbj.entity.Students;
public class StudentService {
public StudentService(){
}
static StudentDao stuDao = new StudentDao();
public List<Students> getAllStudents(){
return stuDao.queryStudents();
}
}
(5)新建StudentDao类
package com.landingbj.dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.landingbj.entity.Students;
import com.landingbj.util.JDBCUtils;
public class StudentDao {
JDBCUtils jdbcUtils = new JDBCUtils();
private static final String[] SQL_QUERY_FIELDS = {"STUID","NAME","AGE"};
private static final String SQL_QUERY = "select "+StringUtils.join(SQL_QUERY_FIELDS,",")+" from students;";
public List<Students> queryStudents() {
System.out.println("+++++++++++++++");
ArrayList<Students> students = new ArrayList<Students>();
List<Map<String, Object>> result = jdbcUtils.execQuery(SQL_QUERY, null);
System.out.println(result);
for(int i=0;i<result.size();i++){
Students student = new Students();
Map<String,Object> map = result.get(i);
student.setStuId((Integer) map.get(SQL_QUERY_FIELDS[0]));
student.setName(map.get(SQL_QUERY_FIELDS[1]).toString());
student.setAge(map.get(SQL_QUERY_FIELDS[2]).toString());
students.add(student);
}
return students;
}
}
(6)JSP页面以及web.xml
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>studentslist</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<table>
<tr>
<th>id</th>
<th>姓名</th>
<th>年龄</th>
</tr>
<c:forEach items="${students}" var="students">
<tr>
<td>${students.stuId}</td>
<td>${students.name}</td>
<td>${students.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>com.landingbj.servlet.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/studentServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>studentslist.jsp</welcome-file>
</welcome-file-list>
</web-app>
该贴被jun.wu编辑于2017-4-21 11:50:17