JDBC+Servlet实现CRUD操作(实例)


相信使惯了MyEclipse的童鞋,突然在eclipse下做类似JDBC+SERVLET,STRUTS,HIBERNATE,SSH项目肯定遇到很多问题(同感的赞一个),话不多说,直接开始实战演练:

数据库表:TB(BID,BNAME,BSEX,BAGE)

1.在eclipse中新建项目(Dynamic Web Project)名字就叫JDBCDemo;
2.创建package,com.entity;com.util;com.servlet;
3.在com.entity下创建class,我这里只是简单展示一下数据库中表TB的数据以及CRUD操作;

TB.java:
package com.entity;

public class TB {
private int bid;
private String bname;
private String bsex;
private int bage;
public TB() {
}
public TB(int bid, String bname, String bsex, int bage) {
super();
this.bid = bid;
this.bname = bname;
this.bsex = bsex;
this.bage = bage;
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public String getBsex() {
return bsex;
}
public void setBsex(String bsex) {
this.bsex = bsex;
}
public int getBage() {
return bage;
}
public void setBage(int bage) {
this.bage = bage;
}

}
4.实体类准备好了以后,关键的一步来鸟,那就是BaseDao,跟着我一起来写吧:
(各位童鞋,这里别忘了你使啥数据库就将对应的jar包放到WEB-INF/lib下)
BaseDao.java:

package com.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BaseDao {

//声明连接数据库的四个常量(驱动、连接地址、用户名、密码)
private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
private static final String USER = "gejun";
private static final String PWD = "gejun";
/**
* 获取数据库连接对象
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName(DRIVER);
return DriverManager.getConnection(URL, USER, PWD);
}
/**
* 释放数据库资源
* @param conn
* @param sta
* @param res
*/
public void closeAll(Connection conn,Statement sta,ResultSet res){
try {
if(res!=null)
res.close();
if(sta!=null)
sta.close();
if(conn!=null&&!conn.isClosed())
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 增、删、改通用方法
* @param sql
* @param args
* @return
*/
public int executeSql(String sql,String[] args){
Connection conn = null;
PreparedStatement ps = null;
int result = 0;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
if(args!=null&&args.length>0){
for (int i = 0; i < args.length; i++) {
ps.setString(i+1, args[i]);
}
}
result = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally{
closeAll(conn, ps, null);
}
return result;
}
}

5.写完了BaseDao,接下来就应该是具体的实体类对应的DAO了;

TBDao:

package com.util;

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

import com.entity.TB;

public class TBDao extends BaseDao {

/**
* 添加
* @param tb
* @return
*/
public int add(TB tb){
String sql = "INSERT INTO TB VALUES(?,?,?,?)";
String bid = Integer.toString(tb.getBid());
String bage = Integer.toString(tb.getBage());
String[] args = {bid,tb.getBname(),tb.getBsex(),bage};
return executeSql(sql, args);
}
/**
* 删除
* @param id
* @return
*/
public int delete(int id){
String sql = "DELETE TB WHERE BID=?";
String bid = Integer.toString(id);
String[] args = {bid};
return executeSql(sql,args);
}
/**
* 更新
* @param tb
* @return
*/
public int update(TB tb){
String sql = "UPDATE TB SET BNAME=?,BSEX=?,BAGE=? WHERE BID=?";
String bid = Integer.toString(tb.getBid());
String bage = Integer.toString(tb.getBage());
String[] args = {tb.getBname(),tb.getBsex(),bage,bid};
return executeSql(sql,args);
}
/**
* 根据id查询
* @param id
* @return
*/
public List<TB> findById(int id){
Connection conn = null;
PreparedStatement ps = null;
ResultSet res = null;
String sql = "SELECT * FROM TB WHERE ID=?";
List<TB> tbs = new ArrayList<TB>();
TB tb = null;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
res = ps.executeQuery();
if(res.next()){
tb = new TB(res.getInt("bid"),res.getString("bname"),res.getString("bsex"),res.getInt("bage"));
tbs.add(tb);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
closeAll(conn, ps, res);
}
return tbs;
}
/**
* 查询所有
* @return
*/
public List<TB> findAll(){
Connection conn = null;
PreparedStatement ps = null;
ResultSet res = null;
String sql = "SELECT * FROM TB";
List<TB> tbs = new ArrayList<TB>();
TB tb = null;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
res = ps.executeQuery();
while(res.next()){
tb = new TB(res.getInt("bid"),res.getString("bname"),res.getString("bsex"),res.getInt("bage"));
tbs.add(tb);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
closeAll(conn, ps, res);
}
return tbs;
}
}

6.dao基本上完成了,下面就是开始准备servlet了;
eclipse中创建servlet时会遇到这样的问题:创建好servlet后,类中有错The import javax.servlet connot be resolved.
解决方案:
项目上右键:Properties-->java build path-->add library-->Server Runtime-->Apacth Tomcat X.X(如果没有安装tomcat,你懂的)-->ok
看看,servlet是不是没错了 ,那就开始编写servlet吧!

DoFindAllServlet.java:
package com.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entity.TB;
import com.util.TBDao;

/**
* Servlet implementation class for Servlet: DoFindAllServlet
*
*/
public class DoFindAllServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
  
    /* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public DoFindAllServlet() {
super();
}  

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;utf-8");
request.setCharacterEncoding("utf-8");
doPost(request, response);


/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;utf-8");//响应形式、字符集
request.setCharacterEncoding("utf-8");//请求的字符集
TBDao tbd = new TBDao();
List<TB> tbs = tbd.findAll();
request.setAttribute("tbs", tbs);
request.getRequestDispatcher("index.jsp").forward(request, response);
}        
}
建好了这个查询所有的servlet后,你是不是期待着看下效果呢,莫急,页面得准备下:
个人的思路是访问项目时写了个1.jsp做过度作用,在WebRoot下新建1.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<script type="text/javascript">
	function redirect(){
		location.href="DoFindAllServlet";
	}
	window.onload=redirect;
</script>
</head>
<body>
正在加载数据......
</body>
</html>


写完跳转的jsp,别忘了把web.xml中的欢迎页设置成1.jsp;接下来就来完成展示信息页面index.jsp:
页面采用了jstl的标签库,如果页面报错时,请检查WEB/INF下是否有jstl.jar,和standard.jar,这两个jar包可以在tomcat中的example下lib目录中找到,一定要是配套的,不然报错。
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Insert title here</title>
</head>
<body>
<center>
<h4>JDBC+SERVLET实例</h4>
<table border="1px solid pink">
	<tr>
		<td>编号</td>
		<td>姓名</td>
		<td>性别</td>
		<td>年龄</td>
		<td>操作</td>
	</tr>
	<c:forEach items="${requestScope.tbs}" var="tb">
		<tr>
			<td>${tb.bid }</td>
			<td>${tb.bname }</td>
			<td>${tb.bsex }</td>
			<td>${tb.bage }</td>
			<td><a>修改</a> <a>删除</a></td>
		</tr>
	</c:forEach>
</table>
</center>
</body>
</html>

通过以上步骤,启动tomcat服务器,浏览器输入:http://localhost:8080/JDBCDemo,回车效果图如下:
JDBC+Servlet实现CRUD操作(实例)_第1张图片
到此,基本上收工,至于其它的功能诸如:在页面上查询、修改、删除功能在此就不一一展示了。

长时间没这么从头到尾写代码了,感觉还有点小收获。如果写的有什么不周到的地方,望提出您宝贵的意见!!!

你可能感兴趣的:(eclipse,html,servlet,jdbc)