1.新建配置jdbc数据源,具体过程省略
2.建立实体表
CREATE TABLE USER(
ID VARCHAR(20) PRIMARY KEY,
NAME VARCHAR(40),
PASSWORD VARCHAR(30),
AGE INT
)ENGINE=MYISAM DEFAULT CHARSET=utf8;
INSERT INTO USER(ID,NAME,PASSWORD,AGE) VALUES('1111','李伟','123456',20),
('1112','王伟','123456',20),
('1113','张伟','123456',20),
('1114','赵伟','123456',20)
3.新建web应用,并打包
3.1 新建数据库连接工具类JDBCUtils,通过配置数据源获取连接
package com.landingbj.common;
/**
* 数据库连接工具类
* @author landingbj
*
*/
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;// 结果集对象
/**
* 获得连接对象
*
* @return 连接对象
* @throws ClassNotFoundException
* @throws SQLException
*/
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;
}
/**
* 关闭三剑客
*
* @throws SQLException
*/
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();
}
}
/**
* 执行更新
*
* @param sql
* 传入的预设的 sql语句
* @param params
* 问号参数列表
* @return 影响行数
*/
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;
}
/**
* 执行查询
*
* @param sql
* 传入的预设的 sql语句
* @param params
* 问号参数列表
* @return 查询后的结果
*/
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;
}
}
3.2 新建User实体类
package com.landingbj.entity;
/**
*
* @author landingbj 用户实体类
*
*/
public class User {
private String id;
private String name;
private String password;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3.3 新建userDao类,获取所有用户
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.common.JDBCUtils;
import com.landingbj.entity.User;
public class UserDao {
JDBCUtils jdbcUtils = new JDBCUtils();
private static final String[] SQL_QUERY_FIELDS = {"ID","AGE","PASSWORD","NAME"};
private static final String SQL_QUERY = "select "+StringUtils.join(SQL_QUERY_FIELDS, ",")+" from user;";
/***
*
* @return 所有用户对象
*/
public List<User> queryAllUsers(){
ArrayList<User> users = new ArrayList<User>();
List<Map<String, Object>> result = jdbcUtils.execQuery(SQL_QUERY, null);
for(int i=0;i<result.size();i++){
User user = new User();
Map<String,Object> map = result.get(i);
user.setId(map.get(SQL_QUERY_FIELDS[0]).toString());
user.setAge(Integer.parseInt(map.get(SQL_QUERY_FIELDS[1]).toString()));
user.setPassword(map.get(SQL_QUERY_FIELDS[2]).toString());
user.setName(map.get(SQL_QUERY_FIELDS[3]).toString());
users.add(user);
}
return users;
}
}
3.4 新建UserService
package com.landingbj.service;
import java.util.List;
import com.landingbj.dao.UserDao;
import com.landingbj.entity.User;
/***
*
* @author landingbj
*
*/
public class UserService {
public UserService(){
}
static UserDao userDao = new UserDao();
public List<User> getAllUsers(){
return userDao.queryAllUsers();
}
}
3.5 新建UserServlet
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.User;
import com.landingbj.service.UserService;
public class UserServlet extends HttpServlet {
private UserService userService;
/**
*
*/
private static final long serialVersionUID = 1L;
public UserServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
UserService userService = new UserService();
List<User> users = userService.getAllUsers();
request.setAttribute("users", users);
request.getRequestDispatcher("/userlist.jsp").forward(request, response);
}
public void init() throws ServletException {
userService = new UserService();
}
}
3.6 新建userlist.jsp简单展示user表数据
<%@ 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>userlist</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>
<th>密码</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.password}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
4.部署war包到weblogic服务器上
6.打开页面测试