使用Servlet、JSP与JDBC实现数据库操纵——JDBC连接MySQL实例:
- 将MySQL数据库驱动的包(我的驱动mysql-connector-java-5.1.34-bin.jar,需单独下载)放在WEB-INF->lib目录下
- 修改Tomcat解压目录下的conf下的server.xml,配置当前应用上下文
- 创建新数据库mydb(MySql中自带一个名为test的数据库,因此不能用test这个名字)
- 创建数据库表users,字段为:id(primary key),username,password,truename,birthday,registerdate,sex,interest,remark
准备工作:cmd->net start,查看如果MySql没有启动网络服务的话,手动启动它。
命令行下:
- mysql -uroot -proot
- create database mydb;
- use mydb;
- show tables;
使用Navicat创建表
navicat使用攻略: 点击[连接],填写一个合适的连接名,然后切换到[高级]选项卡,在[使用高级连接]前打钩,选择一个非系统数据库,填写用户名和密码即可。
利用这个可视化的工具,可以方便的更改表结构和表数据 点击[查询]->[创建查询]可以执行SQL语句。
更改字体大小: 工具->选项中可更改字体属性。
步入主题:新建一个表,命名为users,字段为:id(primary key),username,password,truename,birthday,registerdate,sex,interest,remark,设置相应的类型,id为int,设为主键不能为空(not null),设置为自动增加,username、password、truename均为varchar(20),这里一定不要忘记指定长度,否则用JDBC往数据库中添加信息抛异常,直接在数据库中插入记录则报错不能完成,birthday、registerdate均为datetime,sex为tinyint,interest为varchar(20),remark为text或者mediumtext。
查看表讯息中的DDL如下:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `hh` varchar(0) DEFAULT NULL, `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, `truename` varchar(20) DEFAULT NULL, `birthday` datetime DEFAULT NULL, `registerdate` datetime DEFAULT NULL, `sex` tinyint(4) DEFAULT NULL, `interest` varchar(20) DEFAULT NULL, `remark` mediumtext, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
创建相关的类文件:
com.test.bean包下面新建类:Users.java
com.test.db包下新建类:UsersDB.java
web目录下新建页面:register.jsp
com.test.servlet包下面新建Servlet:ProcessUsersServlet
com.test.filter下新建过滤器:UserFilter.java(web.xml中配置)
web目录下创建页面:listAllUsers.jsp;listSingleUser.jsp
用户信息修改留给大家去完成
com.test.bean包下的Users.java:
package com.test.bean; import java.sql.Date; public class Users { private int id; private String username; private String password; private String truename; private Date birthday; private Date registerdate; private String sex; private String interest; private String remark; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTruename() { return truename; } public void setTruename(String truename) { this.truename = truename; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Date getRegisterdate() { return registerdate; } public void setRegisterdate(Date registerdate) { this.registerdate = registerdate; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getInterest() { return interest; } public void setInterest(String interest) { this.interest = interest; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
com.test.db包下的UserDB.java(关键,数据库操纵):
package com.test.db; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Properties; import com.test.bean.Users; /** * @author user * * TODO 该类完成与users表相关的数据库操作的所有方法 */ public class UsersDB { private String resource = "users.properties"; private Properties props = null; // 得到数据库连接 private Connection getConnection() { try { props = new Properties(); InputStream in = getClass().getResourceAsStream(resource); props.load(in); String drivers = props.getProperty("jdbc.drivers"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); Class.forName(drivers);//加载数据库驱动 return DriverManager.getConnection(url, username, password); } catch (Exception ex) { ex.printStackTrace(); System.out.println("连接数据库异常发生 : " + ex.getMessage()); } return null; } // 插入一笔记录 public void save(Users bean) { try { Connection con = this.getConnection(); String sql = "insert into users(username,password,truename,birthday,registerdate,sex,interest,remark) values(?,?,?,?,?,?,?,?)"; PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, bean.getUsername()); ps.setString(2, bean.getPassword()); ps.setString(3, bean.getTruename()); ps.setDate(4, bean.getBirthday()); ps.setDate(5, bean.getRegisterdate()); ps.setString(6, bean.getSex()); ps.setString(7, bean.getInterest()); ps.setString(8, bean.getRemark()); ps.executeUpdate(); //完成真正的数据库插入 con.close(); } catch (Exception ex) { System.out.println("增加记录异常发生:" + ex.getMessage() + "\n"); // 调试用,我自己添加的 ex.printStackTrace(); } } // 更新一笔记录 public void update(Users bean) { try { Connection con = this.getConnection(); String sql = "update users set password=?,truename=?,birthday=?,sex=?,interest=?,remark=? where id=?"; PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, bean.getPassword()); ps.setString(2, bean.getTruename()); ps.setDate(3, bean.getBirthday()); ps.setString(4, bean.getSex()); ps.setString(5, bean.getInterest()); ps.setString(6, bean.getRemark()); ps.setInt(7, bean.getId()); ps.executeUpdate();//真正完成数据的更新 con.close(); } catch (Exception ex) { System.out.println("修改记录异常发生:" + ex.getMessage()); } } // 删除一笔记录 public void remove(int id) { try { Connection con = this.getConnection(); String sql = "delete from users where id=?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, id); ps.executeUpdate(); //完成真正的删除 con.close(); } catch (Exception ex) { System.out.println("删除记录异常发生:" + ex.getMessage()); } } // 查询一笔记录 public Users restore(int id) { Users bean = null; try { Connection con = this.getConnection(); String sql = "select * from users where id=?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { bean = new Users(); bean.setId(rs.getInt("id")); bean.setUsername(rs.getString("username")); bean.setPassword(rs.getString("password")); bean.setTruename(rs.getString("truename")); bean.setBirthday(rs.getDate("birthday")); bean.setRegisterdate(rs.getDate("registerdate")); bean.setSex(rs.getString("sex")); bean.setInterest(rs.getString("interest")); bean.setRemark(rs.getString("remark")); } con.close(); } catch (Exception ex) { System.out.println("查询记录异常发生:" + ex.getMessage()); } return bean; } // 查询所有记录 public ArrayList getAllUsers() { ArrayList arrayList = new ArrayList(); Users bean = null; try { Connection con = this.getConnection(); String sql = "select * from users"; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { bean = new Users(); bean.setId(rs.getInt("id")); bean.setUsername(rs.getString("username")); bean.setPassword(rs.getString("password")); bean.setTruename(rs.getString("truename")); bean.setBirthday(rs.getDate("birthday")); bean.setRegisterdate(rs.getDate("registerdate")); bean.setSex(rs.getString("sex")); bean.setInterest(rs.getString("interest")); bean.setRemark(rs.getString("remark")); arrayList.add(bean); } con.close(); } catch (Exception ex) { System.out.println("查询所有记录异常发生:" + ex.getMessage()); } return arrayList; } }
web目录下的register.jsp:
<%@ page language="java" pageEncoding="GB2312" %> <!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <title>用户注册</title> <script language="javascript"> function validate() { with(document.form1) { if(username.value.length < 1) { alert("用户名不能为空"); return false; } if(password.value.length < 1) { alert("密码不能为空"); return false; } if(password_again.value.length < 1) { alert("重复密码不能为空"); return false; } if(username.value.length < 4) { alert("用户名长度过短"); return false; } if(username.value.length > 10) { alert("用户名长度过长"); return false; } if(password.value.length < 4) { alert("密码长度过短"); return false; } if(password.value.length> 10 ) { alert("密码长度过长"); return false; } if(password.value != password_again.value) { alert("密码输入不一致"); return false; } if(truename.value.length < 1) { alert("真实姓名不能为空"); return false; } if(birthday.value.length < 1) { alert("生日不能为空"); return false; } if(!sex[0].checked && !sex[1].checked) { alert("性别必须选择"); return false; } var n = 0; for( i = 0 ; i < 4 ; i++) { if(interest[i].checked) { n++; } } if(n < 1) { alert("兴趣至少需要选择一个"); return false; } if(n > 3) { alert("兴趣最多选择三个"); return false; } if(remark.value.length < 1) { alert("说明必须填写"); return false; } } return true; } </script> </head> <body bgcolor="#FFFFFF"> <form action="/test/ProcessUsersServlet" method="post" name="form1" onSubmit="return validate();"> 用户名:<input type="text" name="username" size="20"><br> 密 码:<input type="password" name="password" size="20"><br> 重复输入密码:<input type="password" name="password_again" size="20"><br> 真实姓名:<input type="text" name="truename" size="20"><br> 出生日期:<input type="text" name="birthday" size="20"><br> 性别:男<input type="radio" name="sex" value="0"> 女<input type="radio" name="sex" value="1"><br> 兴趣: 足球<input type="checkbox" name="interest" value="0"> 篮球<input type="checkbox" name="interest" value="1"> 排球<input type="checkbox" name="interest" value="2"> 羽毛球<input type="checkbox" name="interest" value="3"> <br> 说明:<textarea name="remark" rows="15" cols="20"></textarea><br> <input type="submit" value="点击确认"> <input type="reset" value="重 置"> <input type="hidden" name="type" value="save"> </form> </body> </html>
com.test.servlet包下的ProcessUsersServlet:
package com.test.servlet; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.test.bean.Users; import com.test.db.UsersDB; public class ProcessUsersServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Method stub generated by Lomboz process(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Method stub generated by Lomboz process(request, response); } protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String type = request.getParameter("type"); if ("save".equals(type)) { String username = request.getParameter("username"); String password = request.getParameter("password"); String truename = request.getParameter("truename"); String birthday = request.getParameter("birthday"); String sex = request.getParameter("sex"); String[] interest = request.getParameterValues("interest"); String remark = request.getParameter("remark"); java.sql.Date birthdayToDate = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { java.util.Date date = sdf.parse(birthday); birthdayToDate = new java.sql.Date(date.getTime()); } catch (ParseException e) { e.printStackTrace(); } String interestToString = null; StringBuffer sb = new StringBuffer(); for (int i = 0; i < interest.length; i++) { sb.append(interest[i]); } interestToString = sb.toString(); Users bean = new Users(); bean.setUsername(username); bean.setPassword(password); bean.setTruename(truename); bean.setInterest(interestToString); bean.setSex(sex); bean.setBirthday(birthdayToDate); bean.setRegisterdate(new java.sql.Date(new java.util.Date() .getTime())); bean.setRemark(remark); UsersDB userDB = new UsersDB(); userDB.save(bean); ArrayList arrayList = userDB.getAllUsers(); request.setAttribute("all", arrayList); request.getRequestDispatcher("/listAllUsers.jsp").forward( request, response); } if ("remove".equals(type)) { String id = request.getParameter("id"); UsersDB userDB = new UsersDB(); userDB.remove(Integer.parseInt(id)); ArrayList arrayList = userDB.getAllUsers(); request.setAttribute("all", arrayList); request.getRequestDispatcher("/listAllUsers.jsp").forward( request, response); } } }
com.test.filter下的过滤器:UserFilter.java
package com.test.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; /** * @author user * * TODO 要更改此生成的类型注释的模板,请转至 窗口 - 首选项 - Java - 代码样式 - 代码模板 */ public class UsersFilter implements Filter { public void init(FilterConfig config) throws ServletException { // TODO Method stub generated by Lomboz } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Method stub generated by Lomboz ((HttpServletRequest) request).setCharacterEncoding("gb2312"); chain.doFilter(request, response); } public void destroy() { // TODO Method stub generated by Lomboz } public FilterConfig getFilterConfig() { // TODO Method stub generated by Lomboz return null; } public void setFilterConfig(FilterConfig config) { // TODO Method stub generated by Lomboz } }
web.xml中配置过滤器:
<filter> <filter-name>usersFilter</filter-name> <filter-class>com.test.filter.UsersFilter</filter-class> </filter> <filter-mapping> <filter-name>usersFilter</filter-name> <url-pattern>/ProcessUsersServlet</url-pattern> </filter-mapping>
listAllUsers.jsp:
<%@ page language="java" pageEncoding="GB2312" %> <%@ page import="java.util.*,com.test.bean.*"%> <!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"> <%ArrayList arrayList = (ArrayList)request.getAttribute("all"); Users bean = null; %> <html> <head> <title>Lomboz JSP</title> </head> <body bgcolor="#FFFFFF"> <table width="50%" align="center" border="1"> <tr> <td>用户名</td> <td>删除</td> </tr> <%for(int i = 0;i < arrayList.size(); i++) { bean = (Users)arrayList.get(i); %> <tr> <td><a href="listSingleUser.jsp?id=<%= bean.getId()%>"><%= bean.getUsername()%></a></td> <td><a href="/test/ProcessUsersServlet?type=remove&id=<%= bean.getId()%>" onClick="javascript:return confirm(‘您确实要删除该记录么?‘)">删除</a></td> </tr> <%}%> </table> </body> </html>
listSingleUser.jsp:
<%@ page language="java" pageEncoding="GB2312" %> <%@ page import="java.util.*,com.test.bean.*,com.test.db.*"%> <%String id = request.getParameter("id"); UsersDB usersDB = new UsersDB(); Users bean = usersDB.restore(Integer.parseInt(id)); %> <!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <title>Lomboz JSP</title> </head> <body bgcolor="#FFFFFF"> <table width="100%" align="center" align="center"> <tr bgcolor="gray"> <td>用户名</td> <td>密码</td> <td>真实姓名</td> <td>生日</td> <td>注册时间</td> <td>性别</td> <td>爱好</td> <td>说明</td> </tr> <tr> <td><%= bean.getUsername()%></td> <td><%= bean.getPassword()%></td> <td><%= bean.getTruename()%></td> <td><%= bean.getBirthday()%></td> <td><%= bean.getRegisterdate()%></td> <td><%= "0".equals(bean.getSex()) ? "男" : "女"%></td> <td> <%String interest = bean.getInterest();%> <%= interest.indexOf("0") != -1 ? "足球" : ""%> <%= interest.indexOf("1") != -1 ? "篮球" : ""%> <%= interest.indexOf("2") != -1 ? "排球" : ""%> <%= interest.indexOf("3") != -1 ? "羽毛球" : ""%> </td> <td><%= bean.getRemark()%></td> </tr> </table> </body> </html>
启动Tomcat服务器,浏览器中键入:http://localhost:8080/test/register.jsp,出现页面:
下面是分别注册两次后的页面,默认列出所有用户:
点击lisi,出现页面: