-
使用Jsp Servlet Tomcat 实现对sqlServer数据库中人员信息的管理:(MVC架构)
-
准备相应的数据库
-
链接数据库
-
实现对数据库中人员信息的增删改查
页面总体效果如下所示:
点击删除之后会删除掉选中的这一行只显示剩下几行内容,点击添加用户之后会跳转到一个新的页面需要你填入新增的人员信息点击添加即可,点击更新之后同样会跳转到一个新的页面这个页面会显示原来的信息。你只需要把要修改的信息修改完成点击确认就可以更新成功了。
效果展示一 :
效果展示二:
点击添加用户后跳转到如下图显示的添加人员信息页面
效果展示三:
点击孙悟空后面的更新之后跳转到如下图显示的更新页面,修改原有信息点击确认即可
- 准备设计数据库
1.1建立一个名为UserManager的数据库.
1.2在数据库里建立一个名为users的表并添加几条数据.
- 实现对数据库人员信息的增删改查:(使用MVC三层架构)
项目列表展示
2.1 在bean包中新建User.Java类(人员类)
package com.hnpi.bean;public class User {private Integer id;private String name;private String sex;private Integer age;private String phone;private String address;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public User() {super();// TODO Auto-generated constructor stub}}
2.2 在Service包里新建一个UserService.java接口
package com.hnpi.service;import java.util.List;import com.hnpi.bean.User;public interface UserSevice {List<User> list();boolean delUser(Integer id);boolean delUser(User user);boolean addUser(User add);boolean updateUser(User update);}
2.3 在Service包里的Impl包里新建一个UserServiceImpl.java实现类(注意新建的时候一定要实现UserService.java的接口)
package com.hnpi.service.impl;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.hnpi.bean.User;
import com.hnpi.service.UserSevice;
import com.hnpi.util.DBUtil;public class UserServiceImpl implements UserSevice {//查询public List<User> list() {List<User> users = new ArrayList<User>();// TODO 从数据库中获取数据,然后组装成List<User> 然后返回Connection conn = DBUtil.getConn();String sql = "select * from users";PreparedStatement ps = null;ResultSet rs = null;try {ps = conn.prepareStatement(sql);rs = ps.executeQuery();while (rs.next()) {User user = new User();user.setId(rs.getInt(1));user.setName(rs.getString(2));user.setSex(rs.getString(3));user.setAge(rs.getInt(4));user.setPhone(rs.getString(5));user.setAddress(rs.getString(6));users.add(user);}} catch (Exception e) {e.printStackTrace();} finally {DBUtil.closeConn(conn, ps, null);}return users;}//删除public boolean delUser(Integer id) {Connection conn = DBUtil.getConn();String sql = "delete from users where id = ?";PreparedStatement ps = null;int count = 0;try {ps = conn.prepareStatement(sql);ps.setInt(1, id);count = ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {DBUtil.closeConn(conn, ps, null);}if (count > 0)return true;elsereturn false;}//删除public boolean delUser(User user) {Connection conn = DBUtil.getConn();String sql = "delete from users where id = ?";PreparedStatement ps = null;int count = 0;try {ps = conn.prepareStatement(sql);ps.setInt(1, user.getId());count = ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {DBUtil.closeConn(conn, ps, null);}if (count > 0)return true;elsereturn false;}//添加public boolean addUser(User add) {Connection conn = DBUtil.getConn();String sql="insert into users(name,sex,age,phone,address)values(?,?,?,?,?)";PreparedStatement ps = null;int count = 0;try {ps = conn.prepareStatement(sql);ps.setString(1, add.getName());ps.setString(2, add.getSex());ps.setInt(3, add.getAge());ps.setString(4, add.getPhone());ps.setString(5, add.getAddress());count = ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {DBUtil.closeConn(conn, ps, null);}if (count > 0)return true;elsereturn false;}//更新public boolean updateUser(User update) {Connection conn = DBUtil.getConn();String sql="update users set name=?,sex=?,age=?,phone=?,address=? where id=?";PreparedStatement ps = null;int count = 0;try {ps = conn.prepareStatement(sql);ps.setInt(6, update.getId());ps.setString(1, update.getName());ps.setString(2, update.getSex());ps.setInt(3, update.getAge());ps.setString(4, update.getPhone());ps.setString(5, update.getAddress());count = ps.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {DBUtil.closeConn(conn, ps, null);}if (count > 0)return true;elsereturn false;}}
2.4 创建四个Servlet分别实现对人员的增改删查
2.4.1 UserListServlet.java 查询
package com.hnpi.servlet;import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import com.hnpi.bean.User;
import com.hnpi.service.UserSevice;
import com.hnpi.service.impl.UserServiceImpl;
import com.hnpi.util.DBUtil;public class UserListServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 从数据库中获取数据 并且显示在userList.jsp中UserSevice userSevice = new UserServiceImpl();List<User> users = userSevice.list();HttpSession session = request.getSession();session.setAttribute("userList", users);request.getRequestDispatcher("userList.jsp").forward(request, response);}}
2.4.2 UserAddServlet.java 增加
package com.hnpi.servlet;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.hnpi.bean.User;
import com.hnpi.service.UserSevice;
import com.hnpi.service.impl.UserServiceImpl;public class UserAddServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//获取内容String name = request.getParameter("name");String sex = request.getParameter("sex");String age = request.getParameter("age");String phone = request.getParameter("phone");String address = request.getParameter("address");UserSevice userSevice = new UserServiceImpl();User add = new User();add.setName(name);add.setSex(sex);add.setAge(Integer.parseInt(age));add.setPhone(phone);add.setAddress(address);if (userSevice.addUser(add)) {// 成功!response.sendRedirect("userList");} else {// 失败!response.sendRedirect("userList");}}}
2.4.3 UserDelServlet.java 删除
package com.hnpi.servlet;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.hnpi.bean.User;
import com.hnpi.service.UserSevice;
import com.hnpi.service.impl.UserServiceImpl;public class UserDelServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 删除// 1:获取所要删除的idString idStr = request.getParameter("id");// 2:根据id删除数据UserSevice userSevice = new UserServiceImpl();User user = new User();user.setId(Integer.parseInt(idStr));if (userSevice.delUser(user)) {// 成功!response.sendRedirect("userList");} else {// 失败!response.sendRedirect("userList");}}}
2.4.4 UserUpdateServlet.java 更新
package com.hnpi.servlet;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.hnpi.bean.User;
import com.hnpi.service.UserSevice;
import com.hnpi.service.impl.UserServiceImpl;public class UserUpdateServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");String id = request.getParameter("id");String name = request.getParameter("name");String sex = request.getParameter("sex");String age = request.getParameter("age");String phone = request.getParameter("phone");String address = request.getParameter("address");UserSevice userSevice = new UserServiceImpl();User update = new User();update.setId(Integer.parseInt(id));update.setName(name);update.setSex(sex);update.setAge(Integer.parseInt(age));update.setPhone(phone);update.setAddress(address);if (userSevice.updateUser(update)) {// 成功!response.sendRedirect("userList");} else {// 失败!response.sendRedirect("userList");}}}
2.5 在util包里新建一个DBUtil.java类(这个类十分重要,实现对数据库的链接)
package com.hnpi.util;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class DBUtil {public static Connection getConn() {String url = "jdbc:sqlserver://localhost:1433;databaseName=UserManager";String user = "sa";String pwd = "1";Connection conn = null;try {Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");conn = DriverManager.getConnection(url, user, pwd);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}public static void closeConn(Connection conn, PreparedStatement ps,ResultSet rs) {try {if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}try {if (ps != null) {ps.close();}} catch (SQLException e) {e.printStackTrace();}try {if (rs != null) {rs.close();}} catch (SQLException e) {e.printStackTrace();}}}
2.6 JSP页面一共需要三个(查询,增加,更新)
2.6.1 userList.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%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>My JSP 'index.jsp' starting page</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><c:forEach items="${sessionScope.userList}" var="user"varStatus="status">${user.name} ${user.sex} ${user.age} ${user.phone} ${user.address}<a href="userDel?id=${user.id}">删除</a><a href="updateUser.jsp?id=${user.id}">更新</a><br /></c:forEach><hr><a href="addUser.jsp">添加用户</a></body>
</html>
2.6.2 addUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>My JSP 'addUser.jsp' starting page</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><form action="addUser" method="post"><tr>姓名:<input type="text" name="name"/></tr><br><br><tr>性别:<input type="text" name="sex"/></tr><br><br><tr>年龄:<input type="text" name="age"/></tr><br><br><tr>电话:<input type="text" name="phone"/></tr><br><br><tr>地址:<input type="text" name="address"/></tr><br><br><tr><input type="submit" value="添加"/></tr></form></body>
</html>
2.6.3 updateUser.jsp(更新:先查找原来的人员数据放入更新页面的相应输入框内,对输入框的内容进行修改,直接点击确认即可更新完成)
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="com.hnpi.util.DBUtil"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>My JSP 'updateUser.jsp' starting page</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><%String id = request.getParameter("id");Connection conn = DBUtil.getConn();String sql = "select * from users where id = ?";session.setAttribute("id", id);PreparedStatement ps = null;ResultSet rs = null;try {ps = conn.prepareStatement(sql);ps.setString(1, id);rs = ps.executeQuery();while (rs.next()) {String name=rs.getString("name");String sex = rs.getString("sex");int age = rs.getInt("age");String phone = rs.getString("phone");String address = rs.getString("address");%>此用户信息为:<br><br><form action="update" method="post"><table><tr><td><input type="text" name="id" value=<%=id%>></td></tr><tr><td><input type="text" name="name" value=<%=name%>></td></tr><tr><td><input type="text" name="sex" value=<%=sex%>></td></tr><tr><td><input type="text" name="age" value=<%=age%>></td></tr><tr><td><input type="text" name="phone" value=<%=phone%>></td></tr><tr><td><input type="text" name="address" value=<%=address%>></td></tr><tr><td><input type="submit" value="确认"></td><td><input type="reset" value="取消"></td></tr></table></form><% }} catch (Exception e) {e.printStackTrace();} finally {DBUtil.closeConn(conn, ps, null);}%></body>
</html>
请大家注意一定要使用相应的架包 否则是无论如何都无法运行成功的
以上代码实现了对sqlServer数据库人员信息的增改删查等功能,希望能对大家有所帮助