赞
踩
入职以来(来京六整月),一直在学习JavaWeb的知识,分享下最近几个月(断断续续)用jsp+servlet+jdbc实现的一个demo,这个demo借鉴了网上很多前辈的经验,希望自己能够不断进步。
效果图如下:
1、首先介绍下开发所需要工具 ,以及相应的开发环境:
eclipse+tomcat+mysql+jdk;
2、创建数据库userdemo,然后创建userdemo及userinfo表
3、接下来在eclipse中搭建web工程,相应目录如下图所示,并导入相应的包(需要mysql连接jdbc的jar包,以及jstl的jar包)
4、对应jsp页面的代码
(1)登陆界面logon.jsp:
- <%@ page import="java.sql.*" 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" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv ="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>用户登陆界面</title>
-
- <style type="text/css">
- body {
- background-attachment: fixed;
- background-repeat: no-repeat;
- background-size: 100% 100%;
- color: #000;
- font-family: "微软雅黑";
- font-size: 1.6em;
- }
- #div1 {
- text-align: center;
- width: 200px;
- height: 200px;
- }
- #span {
- font-size: 9px;
- }
- </style>
-
- <script>
- function myFunction(){
- var x = document.getElementById("psw").value;
- if(x==""||isNaN(x)){
- alert("密码不能为空!");
- return;
- }
- var y = document.getElementById("usn").value;
- if(y==""){
- alert("用户名不能为空!");
- return;
- }
- document.getElementById("form1").submit();
- }
- </script>
- </head>
-
- <body>
-
- <div id="div1">
- <form id="form1" action="logon" method="post">
- <p>
- <label for="username">用户名</label>
- <input id="usn" type="text" name="username">
- </p>
- <p>
- <label for="password">密码</label>
- <input id="psw" type="password" name="password">
- </p>
- <input type="button" onclick="myFunction()" value="登陆" >
- </form>
- </div>
-
- </body>
- </html>
(2)主界面home.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=ISO-8859-1">
- <title>人员信息</title>
- </head>
- <!-- frame对应的导航框架 -->
- <frameset rows="93%,*" >
- <frameset cols="20%, *" noresize="noresize" >
- <frame src="left.jsp" frameborder="1" name="leftFrame" />
- <frame src="userlistright" frameborder="1" name="rightFrame" />
- </frameset>
- <frame src="footer.jsp" frameborder="1" name="footerFrame"/>
- </frameset>
- </html>
(3)左侧部分left.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部分 -->
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>人员信息</title>
- <style type="text/css">
- a:link,a:visited {
- text-decoration: none; /*超链接无下划线*/
- }
- a:hover{
- text-decoration:underline; /*鼠标放上去有下划线*/
- }
- li{
- list-style: none; /*去除li前面的小黑点*/
- }
- </style>
- </head>
- <!--js:对应跳转部分 -->
- <script type="text/javascript">
- function add(){
- window.parent.rightFrame.location.href='addright.jsp'
- }
- function userList(){
- window.parent.rightFrame.location.href='userlistright'
- }
- </script>
- <body>
- <div>
- <h3 style="margin-center">人员信息</h3>
- <ul>
- <li>
- <a href="#" onclick="add()">新增</a>
- </li>
- <li>
- <a href="#" onclick="userList()">人员列表</a>
- </li>
- </ul>
- </div>
- </body>
- </html>
(4)右侧部分(人员列表)userlistright
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%@ page import="dao.UserInfoDaoMrg" %>
- <%@ page import="entity.UserInfo" %>
- <%@ page import="java.util.*" %>
- <%@ page import="bean.Page" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <!-- head部分 -->
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>人员列表</title>
- <style type="text/css">
- a:link,a:visited {
- text-decoration: none; /*超链接无下划线*/
- }
- a:hover{
- text-decoration:underline; /*鼠标放上去有下划线*/
- }
- td{
- text-align:center;
- }
-
- </style>
- </head>
-
- <!--js:对应跳转部分 -->
- <script>
- function refreshList(){
- window.parent.rightFrame.location.href='userlistright' //servlet
- }
-
- function add(){
- window.parent.rightFrame.location.href='addright.jsp' //
- }
-
- function delFun(){
- window.parent.rightFrame.location.href='userlistright' //
- }
-
- function editFun(){
- window.parent.rightFrame.location.href='addright.jsp' //
- }
-
- </script>
- <body>
- <div style="margin-top:10px; margin-bottom:10px;">
- <button id="refreshbutton" style="width:80px;height:40px;margin-left:10px" type="button" onclick="refreshList()">刷新界面</button>
- <button id="addbutton" style="width:80px;height:40px;" type="button" onclick="add()">新增</button>
- </div>
-
- <div>
- <table id="user_list" border="1" cellspacing="0" cellpadding="0" style="border:1px solid gray; border-radius:4px">
- <thead>
- <tr>
- <th style="width:100px;text-align:center">工号</th>
- <th style="width:80px;text-align:center">姓名</th>
- <th style="width:120px;text-align:center">技术水平</th>
- <th style="width:120px;text-align:center">所在部门</th>
- <th style="width:160px;text-align:center">角色</th>
- <th style="width:180px;text-align:center">操作</th>
- </tr>
- </thead>
-
- <tbody>
- <%
- List<UserInfo> list = (List<UserInfo>)request.getAttribute("list");
- for(UserInfo user : list){
- %>
- <tr>
- <td style="width:100px;text-align:center"><%=user.getJobNumber()%></td>
- <td style="width:80px;text-align:center"><%=user.getName()%></td>
- <td style="width:120px;text-align:center"><%=user.getLevel()%></td>
- <td style="width:120px;text-align:center"><%=user.getDepartment()%></td>
- <td style="width:160px;text-align:center"><%=user.getRole()%></td>
- <td><a href="deleteUserServlet?id=<%=user.getId()%>" onclick="return confirm('是否确认删除<%=user.getName()%>信息?')">删除</a>
- <a href="selectUserServlet?id=<%=user.getId()%>">修改</a></td>
- </tr>
- <%
- }
- %>
-
- </tbody>
- </table>
- </div>
-
- <div style="width:800px">
- <c:choose>
- <c:when test="${page.pageNum<=1}">
- <a href="userlistright?pageNum = 1 ">前一页</a>
- </c:when>
- <c:otherwise>
- <a href="userlistright?pageNum=${page.pageNum-1}">前一页</a>
- </c:otherwise>
- </c:choose>
-
- <c:forEach var="i" begin="1" end="${page.pageTotal}" step="1">
- <a href="userlistright?pageNum=${i}">${i}</a>
- </c:forEach>
-
- <c:choose>
- <c:when test="${page.pageNum >= page.pageTotal}%>">
- <a href="userlistright?pageNum=${page.pageTotal}">后一页</a>
- </c:when>
- <c:otherwise>
- <a href="userlistright?pageNum=${page.pageNum + 1}">后一页</a>
- </c:otherwise>
- </c:choose>
- <span style="margin-left:10px">一共${page.pageTotal}页</span>
- </div>
- </body>
- </html>
(5)footer.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">
- <div class="footer">
- <div class="container_1">
- <p>
- Designed by <a href="http://www.baidu.com" target="_blank">百度</a>
- </p>
- </div>
- </div>
(6)增加人员界面addright.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>
- </head>
- <script>
- function confirmFun(){
- var x1 = document.getElementById("name").value;
- var x2 = document.getElementById("jobNumber").value;
- var x3 = document.getElementById("level").value;
- var x4 = document.getElementById("department").value;
- var x5 = document.getElementById("role").value;
- if(x1==""||isNaN(x1)||x2==""||isNaN(x2)||x3==""||isNaN(x3)||x4==""||isNaN(x4)
- ||x5==""||isNaN(x5)){
- alert("添加信息不完整");
- return;
- }
- document.getElementById("form").submit();
- }
-
- function resetFun(){
- var spans = document.getElementsByTagName("input");
- for(var j=0;j<spans.length;j++){
- var span = spans[j]; // input标签的数组
- document.getElementById(span.id).value ="";//
- console.info(span.id);
- }
- }
- </script>
-
- <body>
- <h3>新增页面</h3>
- <form id="form" action="addright" method="post">
- 工号:<input id="jobNumber" name="jobNumber"><br>
- 姓名:<input id="name" name="name"><br>
- 技术水平:<input id="level" name="level"><br>
- 所在部门:<input id="department" name="department"><br>
- 角色:<input id="role" name="role"><br>
- <input type="button" value="确定" onclick="confirmFun()"> <input type="reset" value="重置" onclick="resetFun()">
- </form>
- </body>
-
- </html>
(7)编辑人员信息界面updateuser.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ page import="entity.UserInfo" %>
- <%@ page import="dao.UserInfoDaoMrg" %>
-
- <!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>
- </head>
- <script>
- function confirmFun(){
- var x1 = document.getElementById("name").value;
- var x2 = document.getElementById("jobNumber").value;
- var x3 = document.getElementById("level").value;
- var x4 = document.getElementById("department").value;
- var x5 = document.getElementById("role").value;
-
- if(x1==""||isNaN(x1)||x2==""||isNaN(x2)||x3==""||isNaN(x3)||x4==""||isNaN(x4)
- ||x5==""||isNaN(x5)){
- alert("添加信息不完整");
- return;
- }
- document.getElementById("updform").submit();
- }
-
- function resetFun(){
- var spans = document.getElementsByTagName("input");
- for(var i=0;j<spans.length;i++){
- var span = spans[i]; // input标签的数组
- document.getElementById(span.id).value ="";//
- console.info(span.id);
- }
- }
- </script>
- <body>
- <h3>修改页面</h3>
- <%
- UserInfo user = (UserInfo)request.getAttribute("user");
- %>
- <form id="updform" action="updateuser" method="post">
- <input type="hidden" name="id" value="<%=user.getId()%>">
- 工号:<input name="jobNumber" value="<%=user.getJobNumber()%>"><br>
- 姓名:<input name="name" value="<%=user.getName()%>"> <br>
- 技术水平:<input name="level" value="<%=user.getLevel()%>"><br>
- 所在部门:<input name="department" value="<%=user.getDepartment()%>"><br>
- 角色:<input name="role" value="<%=user.getRole()%>"><br>
- <input type="submit" value="确定" onclick="confirmFun()"> <input type="reset" value="重置" onclick="resetFun()">
- </form>
- </body>
- </html>
5、配置web.xml文件的信息如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
- <display-name>webexample</display-name>
- <welcome-file-list>
- <welcome-file>/logon.jsp</welcome-file>
- </welcome-file-list>
-
- <servlet>
- <servlet-name>s1</servlet-name>
- <servlet-class>servlet.ActionServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>s1</servlet-name>
- <url-pattern>/logon</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>s2</servlet-name>
- <jsp-file>/home.jsp</jsp-file>
- </servlet>
- <servlet-mapping>
- <servlet-name>s2</servlet-name>
- <url-pattern>/home</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>s3</servlet-name>
- <servlet-class>servlet.UserListServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>s3</servlet-name>
- <url-pattern>/userlistright</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>s4</servlet-name>
- <servlet-class>servlet.AddUserServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>s4</servlet-name>
- <url-pattern>/addright</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>s5</servlet-name>
- <servlet-class>servlet.UpdateUserServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>s5</servlet-name>
- <url-pattern>/updateuser</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>s6</servlet-name>
- <servlet-class>servlet.DeleteUserServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>s6</servlet-name>
- <url-pattern>/deleteUserServlet</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>s7</servlet-name>
- <servlet-class>servlet.SelectUserServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>s7</servlet-name>
- <url-pattern>/selectUserServlet</url-pattern>
- </servlet-mapping>
-
- </web-app>
6、对应的Java代码如下:
(1)util包下的DBUtil.java
- package util;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
-
- import org.junit.Test;
-
- /**
- * JDBC工具类:
- * 提供了获得连接,关闭连接的相关的方法
- * @author Administrator
- *
- */
- public class DBUtil {
- static Connection conn = null;
- static Statement stmt = null;
-
- //建立连接
- public static Connection getConnection() throws Exception{
- try {
- Class.forName("com.mysql.jdbc.Driver");
- System.out.println("成功加载驱动程序");
- conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdemo", "root", "root");
- System.out.println("数据库连接成功");
- } catch (Exception e) {
- System.out.println("未连接成功");
- e.printStackTrace();
- }
- return conn;
- }
- }
(2)entity包下的User.java、UserInfo.java
(2.1) User.java类
- package entity;
-
- /**
- * 实体类
- * @author Administrator
- * 对应登陆界面
- */
-
- public class User {
- private int id;
- private String username;
- private String pwd;
- private String name;
- private String gender;
-
- 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 getPwd() {
- return pwd;
- }
-
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getGender() {
- return gender;
- }
-
- public void setGender(String gender) {
- this.gender = gender;
- }
-
- @Override
- public String toString() {
- return "User [id=" + id + ", username=" + username + ", pwd=" + pwd
- + ", name=" + name + ", gender=" + gender + "]";
- }
- }
(2.2)UserInfo.java类
- package entity;
-
- /**
- * @author
- * 人员信息的实体类
- * 对应人员信息界面
- */
- public class UserInfo {
- private Integer id;
- private String jobNumber;
- private String name;
- private String level;
- private String department;
- private String role;
-
- //初始化
- public UserInfo(Integer id ,String jobNumber,String name, String level, String department, String role) {
- this.id = id;
- this.jobNumber = jobNumber;
- this.name = name;
- this.level = level;
- this.department = department;
- this.role = role;
- }
-
- //初始化
- public UserInfo(String jobNumber,String name, String level, String department, String role) {
- this.jobNumber = jobNumber;
- this.name = name;
- this.level = level;
- this.department = department;
- this.role = role;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
- public String getJobNumber() {
- return jobNumber;
- }
- public void setJobNumber(String jobNumber) {
- this.jobNumber = jobNumber;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getLevel() {
- return level;
- }
- public void setLevel(String level) {
- this.level = level;
- }
- public String getDepartment() {
- return department;
- }
- public void setDepartment(String department) {
- this.department = department;
- }
- public String getRole() {
- return role;
- }
- public void setRole(String role) {
- this.role = role;
- }
-
- @Override
- public String toString() {
- return "UserInfo [id=" + id + ", jobNumber=" + jobNumber + ", name="
- + name + ", level=" + level + ", department=" + department
- + ", role=" + role + "]";
- }
- }
(3)dao包下的UserDao.java、UserInfoDaoMrg.java
(3.1) UserDao.java类
- package dao;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
-
- import util.DBUtil;
- import entity.User;
-
- /**
- * @author
- * 对应登陆界面
- */
- public class UserDao {
-
- public User findByUsername(String username){
- User user = null;
- Connection conn = null;
-
- //获取连接
- try {
- conn = DBUtil.getConnection();
- //预处理语句
- PreparedStatement prep = conn.prepareStatement("select * from userdemo where username=?");//username
- prep.setString(1, username);//查询sql语句中第一个“?”的位置
- //遍历数据库
- ResultSet rst = prep.executeQuery();//rst.next()指针游标,输出之后其值会发生变化
- if(rst.next()){
- System.out.println(rst.getInt("id"));
- user = new User();
- user.setId(rst.getInt("id"));//id
- user.setUsername(username);//username
- user.setPwd(rst.getString("pwd"));//pwd
- user.setName(rst.getString("name"));//name
- user.setGender(rst.getString("gender"));//gender
- }
- } catch (Exception e) {
- e.printStackTrace();//抛出异常
- System.out.println("查询失败");
- // DBUtil.close(conn);
- }
- return user;
- }
- }
(3.2)UserInfoDaoMrg.java 类
- package dao;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.util.*;
-
- import bean.Page;
- import util.DBUtil;
- import entity.User;
- import entity.UserInfo;
-
- /**
- * @author
- * 负责访问数据库
- */
- public class UserInfoDaoMrg {
-
- List<UserInfo> userList = new ArrayList<>();
- UserInfo user = null;
-
- //查找所有员工
- public List<UserInfo> getUserInfo(){
- try {
- //获取连接
- Connection conn = DBUtil.getConnection();
- //预处理语句
- PreparedStatement prep = conn.prepareStatement("select * from userinfo");
- //遍历数据库
- ResultSet rst = prep.executeQuery();
- while(rst.next()){
- int id = rst.getInt("id");
- System.out.println("-----" + id);
- String jobNumber = rst.getString("jobNumber");
- String name = rst.getString("name");
- String technicalLevel = rst.getString("level");
- String department = rst.getString("department");
- String role = rst.getString("role");
- user = new UserInfo(id, jobNumber, name, technicalLevel, department, role);
- userList.add(user);
- }
- prep.close();
- conn.close();
- } catch (Exception e) {
- e.printStackTrace();//抛出异常
- System.out.println("查询失败");
- }
- return userList;
- }
-
- //添加
- public void addUserInfo(String jobNumber, String name, String technicalLevel, String department, String role) {
- try {
- //获取连接
- Connection conn = DBUtil.getConnection();
- //预处理语句
- String sql = "insert into userinfo (jobNumber,name,level,department,role) values (?, ?, ?, ?, ?)";
- PreparedStatement prep = conn.prepareStatement(sql);
- prep.setString(1, jobNumber);
- prep.setString(2, name);
- prep.setString(3, technicalLevel);
- prep.setString(4, department);
- prep.setString(5, role);
- prep.executeUpdate();
- prep.close();
- conn.close();
- } catch (Exception e) {
- e.printStackTrace();//抛出异常 (检查出现的问题)
- System.out.println("增加失败");
- }
- }
-
-
- //加载员工信息,用于更新界面
- public UserInfo selectUserInfo(int id){
- UserInfo user = null;
- Connection con = null;
- PreparedStatement prep = null;
- ResultSet rst = null;
- try {
- con=DBUtil.getConnection();
- String sql = "select * from userinfo where id =?";
- prep = con.prepareStatement(sql);
- prep.setInt(1, id);
- rst = prep.executeQuery();
- while(rst.next()){
- String jobNumber = rst.getString("jobNumber");
- String name = rst.getString("name");
- String technicalLevel = rst.getString("level");
- String department = rst.getString("department");
- String role = rst.getString("role");
- user = new UserInfo(id, jobNumber, name, technicalLevel, department, role);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return user;
- }
-
- //更新数据库
- public void updateUserInfo(Integer id, String jobNumber, String name, String level,String department, String role) {
- try {
- //获取连接
- Connection conn = DBUtil.getConnection();
- String sql = "update userinfo set jobnumber= ?, name = ?, level= ?, department= ?, role= ? where id= ?";
- //预处理语句
- PreparedStatement prep = conn.prepareStatement(sql);
- prep.setString(1, jobNumber);
- prep.setString(2, name);
- prep.setString(3, level);
- prep.setString(4, department);
- prep.setString(5, role);
- prep.setInt(6, id);
-
- //更新数据库
- prep.executeUpdate();
- prep.close();
- conn.close();
-
- } catch (Exception e) {
- e.printStackTrace();//抛出异常
- System.out.println("更新失败");
- }
- }
-
- //删除数据库
- public void deleteUserInfo(Integer id) {
- try {
- //获取连接
- Connection conn = DBUtil.getConnection();
- //预处理语句
- PreparedStatement prep = conn.prepareStatement("delete from userinfo where id=?");
- prep.setInt(1, id);
- prep.executeUpdate();
- prep.close();
- conn.close();
- } catch (Exception e) {
- e.printStackTrace();//抛出异常 //by tongshi
- System.out.println("删除失败");
- }
- }
-
- //分页查找
- public List<UserInfo> findByPageNum(Page page){
- int begin = (page.getPageNum()-1)*page.getPageSize();//分页算法:确定起始页第一条记录,pageSize = 6 PageNum: 页码数
- System.out.println(page.getPageNum());
- System.out.println(page.getPageSize());
- System.out.println(page.getPageTotal());
- try {
- //获取连接
- Connection conn = DBUtil.getConnection();
- //预处理语句
- String sql = "select * from userinfo limit ?,?";
- PreparedStatement prep = conn.prepareStatement(sql);
- prep.setInt(1, begin);
- prep.setInt(2, page.getPageSize());
-
- //遍历数据库
- ResultSet rst = prep.executeQuery();
- while(rst.next()){
- int id = rst.getInt("id");
- String jobNumber = rst.getString("jobNumber");
- String name = rst.getString("name");
- String technicalLevel = rst.getString("level");
- String department = rst.getString("department");
- String role = rst.getString("role");
- user = new UserInfo(id, jobNumber, name, technicalLevel, department, role);
- userList.add(user);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return userList;
- }
-
- //获取总记录数量
- public int getRecordsNum(){
- Connection con = null;
- PreparedStatement ps=null;
- ResultSet rs = null;
- int recordsNum = 0;
- try {
- con = DBUtil.getConnection();
- String sql = "select count(*) count from userinfo"; //获得表中记录数
- ps = con.prepareStatement(sql);
- rs = ps.executeQuery();
- while(rs.next()){
- recordsNum = rs.getInt("count");
- }
- } catch (Exception e) {
-
- e.printStackTrace();
- }
- return recordsNum;
- }
- }
(4)bean包下的Page.java
- package bean;
-
- import dao.UserInfoDaoMrg;
-
- public class Page {
- private int pageNum;//页码数
- private int pageSize = 6;//每页显示数量,默认为3
- private int pageTotal;//总页数
- private int recordsNum;//总记录数
-
- UserInfoDaoMrg userDaoInfo = new UserInfoDaoMrg();
-
- public int getPageNum() {
- return pageNum;
- }
-
- public void setPageNum(int pageNum) {
- this.pageNum = pageNum;
- }
-
- public int getPageSize() {
- return pageSize;
- }
-
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
-
- public int getRecordsNum() {
- return recordsNum;
- }
-
- public void setRecordsNum(int recordsNum) {
- this.recordsNum = recordsNum;
- }
-
- public void setPageTotal(int pageTotal) {
- this.pageTotal = pageTotal;
- }
-
- public int getPageTotal(){
- recordsNum = userDaoInfo.getRecordsNum();
- int mod = recordsNum % pageSize;
- if(mod == 0){
- pageTotal=recordsNum/pageSize;
- }else{
- pageTotal=recordsNum/pageSize+1;
- }
- return pageTotal;
- }
- }
(5)servlet包下的ActionServlet.java、AddUserServlet.java、DeleteUserServlet.java、SelectUserServlet.java、UpdateUserServlet.java、UserListServlet.java
(5.1)ActionServlet.java类:
- package 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 javax.servlet.http.HttpSession;
-
- import dao.UserDao;
- import entity.User;
-
- public class ActionServlet extends HttpServlet {
- private static final long serialVersionUID = 3624434001049002202L;
-
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
-
- PrintWriter out = response.getWriter();//输出在控制台
-
- //分享请求资源路径
- String uri = request.getRequestURI();
- String action = uri.substring(uri.lastIndexOf("/"));//截取子字符串
- System.out.println("URI为:" + action);
-
- if("/logon".equals(action)){
- //读取用户名和密码
- String userName = request.getParameter("username");//username为jsp中字段,即是:接收到前台传来的数据
- String password = request.getParameter("password");//password为jsp中字段
-
- //根据用户名和密码查询数据库中是否有这个用户
- UserDao ud = new UserDao();
- try {
- User user = ud.findByUsername(userName);
- if(user != null && password.equals(user.getPwd())){
- //创建Session对象保存User对象
- HttpSession session = request.getSession();
- session.setAttribute("user", userName);
-
- //登陆成功跳转指定页面
- request.getRequestDispatcher("home").forward(request,response);
- }else{
- out.print("用户名或者密码为空");
- request.getRequestDispatcher("/webdexample").forward(request,response);
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new ServletException(e);
- }
- }
- out.close();
- }
-
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
(5.2)AddUserServlet.java类
- package 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.sun.xml.internal.bind.v2.model.core.ID;
-
- import dao.UserInfoDaoMrg;
- import entity.UserInfo;
-
- /**
- * @author
- * 对应“增加”部分的按钮
- */
- public class AddUserServlet extends HttpServlet{
-
- private static final long serialVersionUID = 1L;
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
-
- //获得form表单属性
- String jobNumber = request.getParameter("jobNumber");
- String name = request.getParameter("name");
- String level = request.getParameter("level");
- String department = request.getParameter("department");
- String role = request.getParameter("role");
-
- //servlet
- request.setAttribute("jobNumber", jobNumber);
- request.setAttribute("name", name);
- request.setAttribute("technicalLevel", level);
- request.setAttribute("department", department);
- request.setAttribute("role", role);
-
- //更新数据库
- UserInfoDaoMrg ud = new UserInfoDaoMrg();
- ud.addUserInfo(jobNumber, name, level, department, role);
- request.getRequestDispatcher("userlistright").forward(request,response);// 对应servlet
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
(5.3)DeleteUserServlet.java类
- package 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 util.DBUtil;
- import dao.UserInfoDaoMrg;
- import entity.UserInfo;
-
- public class DeleteUserServlet extends HttpServlet{
-
- private static final long serialVersionUID = 1L;
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");//response解决乱码问题
- System.out.println("进入deleteservlet");
- int id = Integer.parseInt(request.getParameter("id"));//从table(前端)中得到的id
- UserInfoDaoMrg ud = new UserInfoDaoMrg();
- ud.deleteUserInfo(id);
- request.getRequestDispatcher("userlistright").forward(request,response);
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
(5.4)SelectUserServlet.java类
- package 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 dao.UserInfoDaoMrg;
- import entity.UserInfo;
-
- public class SelectUserServlet extends HttpServlet{
- private static final long serialVersionUID = 1L;
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
-
- int id = Integer.parseInt(request.getParameter("id"));//从table(前端)中得到的id
- System.out.println("-----------" + id);
-
- UserInfoDaoMrg ud = new UserInfoDaoMrg();
- UserInfo user = ud.selectUserInfo(id);
- request.setAttribute("user", user);
- request.getRequestDispatcher("updateuser.jsp").forward(request,response);
- }
-
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
(5.5)UpdateUserServlet.java类
- package 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.sun.xml.internal.bind.v2.model.core.ID;
-
- import dao.UserInfoDaoMrg;
- import entity.UserInfo;
-
- public class UpdateUserServlet extends HttpServlet{
-
- private static final long serialVersionUID = 1L;
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
-
- UserInfoDaoMrg ud = new UserInfoDaoMrg();
- Integer id = Integer.parseInt(request.getParameter("id"));
- String name = request.getParameter("name");
- String jobNumber = request.getParameter("jobNumber");
- String technicalLevel = request.getParameter("level");
- String department = request.getParameter("department");
- String role = request.getParameter("role");
-
- //更新数据库
- ud.updateUserInfo(id, jobNumber, name, technicalLevel, department, role);
- request.getRequestDispatcher("userlistright").forward(request,response);
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
(5.6) UserListServlet.java类
- package 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 bean.Page;
- import dao.UserInfoDaoMrg;
- import entity.UserInfo;
-
- public class UserListServlet extends HttpServlet{
-
- private static final long serialVersionUID = 1L;
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
-
- //分页显示对应的代码
- Page page = new Page();
- String pageNum = request.getParameter("pageNum");
- if(pageNum == null){
- page.setPageNum(1);
- }else{
- page.setPageNum(Integer.parseInt(pageNum));
- }
-
- UserInfoDaoMrg ud = new UserInfoDaoMrg();
-
- List<UserInfo> listUser = ud.findByPageNum(page);
- request.setAttribute("list", listUser);//对应列表
- request.setAttribute("page", page);//对应分页
- request.getRequestDispatcher("userlistright.jsp").forward(request,response); //"userlistright.jsp" by workmate
-
- // //不分页显示对应的代码
- // UserInfoDaoMrg ud = new UserInfoDaoMrg();
- // List<UserInfo> userList = ud.getUserInfo();
- // request.setAttribute("list", userList);
- // request.getRequestDispatcher("userlistright.jsp").forward(request,response); //"userlistright.jsp" by workmate
- }
-
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。