jdbc_servlet基础增删改分页2(userinfo表的)

时间:2023-03-09 15:07:40
jdbc_servlet基础增删改分页2(userinfo表的)

1.创建如下文件目录

jdbc_servlet基础增删改分页2(userinfo表的)

2.导入MyBatis的jar文件

jdbc_servlet基础增删改分页2(userinfo表的)

3.创建实体类

package com.entity;

public class Userinfo {
private Integer uid;
private String uname;
private String password;
private Integer age; public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Userinfo() {
super();
}
public Userinfo(String uname, String password) {
super();
this.uname = uname;
this.password = password;
}
public Userinfo(Integer uid, String uname, String password, Integer age) {
super();
this.uid = uid;
this.uname = uname;
this.password = password;
this.age = age;
}
@Override
public String toString() {
return "Userinfo [uid=" + uid + ", uname=" + uname + ", password="
+ password + ", age=" + age + "]";
} }

4.创建分页page类

package com.entity;

public class Page {
private Integer pageNo;
private Integer pageSize;
private Integer pageCount;
private Integer totalpage;
private Integer stratrow;
private Integer endrow; public Integer getStratrow() {
return stratrow;
}
public void setStratrow(Integer stratrow) {
this.stratrow = stratrow;
}
public Integer getEndrow() {
return endrow;
}
public void setEndrow(Integer endrow) {
this.endrow = endrow;
}
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageCount() {
return pageCount;
}
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
public Integer getTotalpage() {
return totalpage;
}
public void setTotalpage(Integer totalpage) {
this.totalpage = totalpage;
}
public Page(Integer pageNo, Integer pageSize, Integer pageCount,
Integer totalpage) {
super();
this.pageNo = pageNo;
this.pageSize = pageSize;
this.pageCount = pageCount;
this.totalpage = totalpage;
} public Page(Integer pageNo, Integer pageSize, Integer pageCount) {
super();
this.pageNo = pageNo;
this.pageSize = pageSize;
this.pageCount = pageCount;
this.totalpage=pageCount%pageSize==?pageCount/pageSize:pageCount/pageSize+;
this.stratrow=(pageNo-)*pageSize;
this.endrow=pageNo*pageSize; }
public Page() {
super();
} }

5.创建Basedao

package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 定义Basedao
* @author sam
*
*/
public class Basedao {
//1.定义连接数据库的信息
private static String DRIVER="oracle.jdbc.driver.OracleDriver";
private static String URL="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
private static String username="holly";
private static String password="tiger"; //2.定义链接对象
public Connection conn=null; //3.定义从数据库中操作的执行对象
public PreparedStatement ptsm=null; //4.定义查询结果的返回对象
public ResultSet rs=null; //5.静态代码块链接数据库驱动
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("数据库异常");
e.printStackTrace();
}
} //6.定义链接数据库的方法
public Connection getConnection(){
try {
//驱动管理对象去加载数据库地址,用户名,密码链接数据库
conn=DriverManager.getConnection(URL, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("连接数据库异常");
e.printStackTrace();
}
return conn;
} //7.定义销毁对象的方法
public void closeAll(Connection conn,PreparedStatement ptsm,ResultSet rs){
try {
if (rs!=null) {
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (ptsm!=null) {
ptsm.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} //8.定义执行查询的方法
public ResultSet executeQuery(String sql,Object[] param){
conn=this.getConnection();
try {
//从建立的链接中获取执行查询的对象,请获取sql语句
ptsm=conn.prepareStatement(sql);
//将sql对象补充完整
if (param!=null) {
for (int i = ; i < param.length; i++) {
ptsm.setObject(i+, param[i]);
}
}
//获取查询结果
rs=ptsm.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
} //9.定义增删改的方法
public int executeUpdate(String sql,Object[] param){
int num=;
conn=this.getConnection();
try {
//从建立的链接中获取执行查询的对象,请获取sql语句
ptsm=conn.prepareStatement(sql);
//将sql对象补充完整
if (param!=null) {
for (int i = ; i < param.length; i++) {
ptsm.setObject(i+, param[i]);
}
}
//获取查询结果 num=ptsm.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.closeAll(conn, ptsm, rs);
}
return num;
}
}

6.数据层操作层接口

package com.dao;

import java.util.List;

import com.entity.Page;
import com.entity.Userinfo;
/**
* 数据层操作层接口
* @author Administrator
*
*/
public interface UserinfoDao { List<Userinfo> findAll(); Userinfo getByID(Integer ID); Userinfo getByNameByPWD(Userinfo userinfo); int insert(Userinfo userinfo); int delete(Integer ID); int update(Userinfo userinfo); int totalCount(); List<Userinfo> pagefind(Page page); }

7.数据操作层的实现类

package com.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import com.dao.Basedao;
import com.dao.UserinfoDao;
import com.entity.Page;
import com.entity.Userinfo;
/**
* 数据操作层的实现类
* 继承basedao实现数据访问接口
*
* rs解析中的字段必须与数据库保持一致
* @author Administrator
*
*/
public class UserinfoDaoImpl extends Basedao implements UserinfoDao{ /**
* 查询所有
*/
public List<Userinfo> findAll() {
// TODO Auto-generated method stub
String sql="select * from userinfo";
rs=this.executeQuery(sql, null);
List<Userinfo> list=new ArrayList<Userinfo>();
try {
while (rs.next()) {
Userinfo userinfo=new Userinfo(rs.getInt("id"),
rs.getString("uname"),
rs.getString("password"),
rs.getInt("age"));
list.add(userinfo);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("查询所有解析异常");
e.printStackTrace();
}finally{
this.closeAll(conn, ptsm, rs);
}
return list;
} /**
* 根据ID查询
*/
public Userinfo getByID(Integer ID) {
// TODO Auto-generated method stub
String sql="select * from userinfo where id=?";
Object[] param={ID};
this.executeQuery(sql, param);
Userinfo userinfo=null;
try {
if (rs.next()) {
userinfo=new Userinfo(rs.getInt("id"),
rs.getString("uname"),
rs.getString("password"),
rs.getInt("age")); }
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("find ID error");
e.printStackTrace();
}finally{
this.closeAll(conn, ptsm, rs);
}
return userinfo;
} /**
* 根据用户名查询
*/
public Userinfo getByNameByPWD(Userinfo userinfo) {
// TODO Auto-generated method stub
String sql="select * from userinfo where uname=? and password=?";
Object[] param={userinfo.getUname(),userinfo.getPassword()};
this.executeQuery(sql, param);
Userinfo user=null;
try {
if (rs.next()) {
user=new Userinfo(rs.getInt("id"),
rs.getString("uname"),
rs.getString("password"),
rs.getInt("age")); }
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("find ID error");
e.printStackTrace();
}finally{
this.closeAll(conn, ptsm, rs);
}
return user;
} /**
* 添加
*/
public int insert(Userinfo userinfo) {
// TODO Auto-generated method stub
String sql="insert into userinfo values(seq_userinfo.nextval,?,?,?)";
Object[] param={userinfo.getUname(),userinfo.getPassword(),userinfo.getAge()};
int num=this.executeUpdate(sql, param);
return num; } /**
* 删除
*/
public int delete(Integer ID) {
// TODO Auto-generated method stub
String sql="delete from userinfo where id=?";
Object[] param={ID};
int num=this.executeUpdate(sql, param);
return num;
} /**
* 修改
*/
public int update(Userinfo u) {
// TODO Auto-generated method stub
String sql="update userinfo set uname=?,password=?,age=? where id=?";
Object[] param={u.getUname(),u.getPassword(),u.getAge(),u.getUid()};
int num=this.executeUpdate(sql, param);
return num;
} /**
* 查询总条数
*/
public int totalCount() {
// TODO Auto-generated method stub
String sql="select count(*) from userinfo";
int num=;
rs=this.executeQuery(sql, null);
try {
if (rs.next()) {
num=rs.getInt();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("查总条数返回结果异常");
e.printStackTrace();
}
return num;
} /**
* 分页查询
*/
public List<Userinfo> pagefind(Page page) {
// TODO Auto-generated method stub
String sql="select * from " +
"(select rownum r,u.* from userinfo u where rownum<=" +page.getEndrow()+
") where r>"+page.getStratrow();
System.out.println("查询的sql语句是:"+sql);
rs=this.executeQuery(sql, null);
List<Userinfo> list=new ArrayList<Userinfo>();
try {
while (rs.next()) {
Userinfo userinfo=new Userinfo(rs.getInt("id"),
rs.getString("uname"),
rs.getString("password"),
rs.getInt("age"));
list.add(userinfo);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("查询所有解析异常");
e.printStackTrace();
}finally{
this.closeAll(conn, ptsm, rs);
}
return list;
} }

8.业务逻辑接口

package com.service;

import java.util.List;

import com.entity.Userinfo;
/**
* 业务逻辑接口
* @author Administrator
*
*/
public interface UserinfoService { List<Userinfo> findAll(); Userinfo getByID(Integer ID); Userinfo login(String uname,String pwd); int insert(Userinfo userinfo); int delete(Integer ID); int update(Userinfo userinfo); int totalCount(); List<Userinfo> pagefind(int pageNo,int pageSize);
}

9.业务方法实现类

package com.service.impl;

import java.util.List;

import com.dao.UserinfoDao;
import com.dao.impl.UserinfoDaoImpl;
import com.entity.Page;
import com.entity.Userinfo;
import com.service.UserinfoService;
/**
* 业务方法实现类
* @author Administrator
*
*/
public class UserinfoServiceImpl implements UserinfoService { private UserinfoDao udao=new UserinfoDaoImpl(); public List<Userinfo> findAll() {
// TODO Auto-generated method stub
return udao.findAll();
} public Userinfo getByID(Integer ID) {
// TODO Auto-generated method stub
return udao.getByID(ID);
} public Userinfo login(String uname,String pwd) {
// TODO Auto-generated method stub
Userinfo userinfo=new Userinfo(uname, pwd);
return udao.getByNameByPWD(userinfo);
} public int insert(Userinfo userinfo) {
// TODO Auto-generated method stub
return udao.insert(userinfo);
} public int delete(Integer ID) {
// TODO Auto-generated method stub
return udao.delete(ID);
} public int update(Userinfo userinfo) {
// TODO Auto-generated method stub
return udao.update(userinfo);
} public int totalCount() {
// TODO Auto-generated method stub
return udao.totalCount();
} /**
* 分页
*/
public List<Userinfo> pagefind(int pageNo,int pageSize) {
// TODO Auto-generated method stub
Page page=new Page(pageNo, pageSize, udao.totalCount());
return udao.pagefind(page);
} }

10.servlet代码

package com.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.entity.Page;
import com.entity.Userinfo;
import com.service.UserinfoService;
import com.service.impl.UserinfoServiceImpl; public class UserinfoServlet extends HttpServlet { /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doPost(request, response);
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.乱码处理
response.setContentType("text/html;Charset=UTF-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8"); UserinfoService us=new UserinfoServiceImpl(); //2.拦截form中数据
String uname=request.getParameter("name");
String password=request.getParameter("pwd");
String uage=request.getParameter("age");
String uid=request.getParameter("id");
String pano=request.getParameter("pano");//页面数
String flag=request.getParameter("flag");//页面数 int id=;
if (uid!=null) {
id=Integer.parseInt(uid);
} int age=;
if (uage!=null) {
age=Integer.parseInt(uage);
} int pageNo=;
if (pano!=null) {
pageNo=Integer.parseInt(pano);
} int pageSize=; Page page=new Page(pageNo, pageSize, us.totalCount());
//查询所有
if (flag==null) {
System.out.println("进入分页方法"); List<Userinfo> list=us.pagefind(pageNo, pageSize); if (list!=null) {
request.setAttribute("list", list);
request.setAttribute("page", page);
for (Userinfo userinfo : list) {
System.out.println(userinfo);
}
request.getRequestDispatcher("show.jsp").forward(request, response);
} else {
System.out.println("查询分页失败");
}
//添加
}else if (flag.equals("add")) {
Userinfo userinfo=new Userinfo(, uname, password, age);
System.out.println("添加的用户是:"+userinfo);
int num=us.insert(userinfo);
if (num>) {
response.sendRedirect("UserinfoServlet");
} else {
System.out.println("添加失败");
}
//查找单条
}else if (flag.equals("findone")) {
System.out.println();
Userinfo userinfo=us.getByID(id);
System.out.println("修改的userinfo是"+userinfo);
if (userinfo!=null) {
request.setAttribute("u", userinfo);
request.getRequestDispatcher("update.jsp").forward(request, response);
} else {
System.out.println("查询单条失败");
}
//修改
}else if (flag.equals("update")) {
Userinfo userinfo=new Userinfo(id, uname, password, age);
int num=us.update(userinfo);
if (num>) {
System.out.println("修改成功");
response.sendRedirect("UserinfoServlet");
} else {
System.out.println("修改失败");
}
//删除
}else if (flag.equals("delete")) {
int num=us.delete(id);
if (num>) {
response.sendRedirect("UserinfoServlet");
} else {
System.out.println("删除失败");
}
} } }

11.webXML文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<servlet>
<servlet-name>UserinfoServlet</servlet-name>
<servlet-class>com.servlet.UserinfoServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>UserinfoServlet</servlet-name>
<url-pattern>/UserinfoServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

11.add.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 'add.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="">
<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>
<center>
<form action="UserinfoServlet?flag=add" method="post">
<table border="1px" style="width: 400px">
<tr>
<td>姓名</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>密码</td>
<td><input type="text" name="pwd" /></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td colspan=""><input type="submit" value="提交注册" /></td>
</tr>
</table>
</form>
</center>
</body>
</html>

12.index.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 '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="">
<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>
<center>
<fieldset style="width: 400px">
<legend>登录</legend>
<form action="UserinfoServlet" method="post">
<table border="1px">
<tr>
<td>姓名:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="pwd"/></td>
</tr>
<tr>
<td colspan=""><input type="submit"/></td>
</tr>
</table>
</form>
</fieldset>
</center>
</body>
</html>

13.show.jsp

<%@ 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>My JSP 'show.jps' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="">
<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>
<center>
<a href="add.jsp">添加</a>
<table border="1px" style="width: 400px">
<tr>
<td>姓名</td>
<td>密码</td>
<td>年龄</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="i">
<tr>
<td>${i.uname}</td>
<td>${i.password}</td>
<td>${i.age}</td>
<td><a href="UserinfoServlet?flag=findone&id=${i.uid}">修改</a><a href="UserinfoServlet?flag=delete&id=${i.uid}">删除</a></td>
</tr>
</c:forEach>
<tr>
<td colspan=""><a href="UserinfoServlet?pano=1">首页</a> <c:choose>
<c:when test="${page.pageNo>1}">
<a href="UserinfoServlet?pano=${page.pageNo-1}">上一页</a>
</c:when>
<c:otherwise>
<a href="javaScript:alert('已经是首页了')">上一页</a>
</c:otherwise>
</c:choose> <c:choose>
<c:when test="${page.pageNo<page.totalpage}">
<a href="UserinfoServlet?pano=${page.pageNo+1}">下一页</a>
</c:when>
<c:otherwise>
<a href="javaScript:alert('已经是末页了')">下一页</a>
</c:otherwise>
</c:choose> <a href="UserinfoServlet?pano=${page.totalpage}">末页</a></td>
</tr>
</table>
</center>
</body>
</html>

14.update.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 'update.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="">
<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>
<center>
<form action="UserinfoServlet?flag=update" method="post">
<table border="1px" style="width: 400px">
<tr>
<td>编号:</td>
<td><input type="text" name="id" value="${u.uid}" readonly="readonly"/></td>
</tr>
<tr>
<td>姓名</td>
<td><input type="text" name="name" value="${u.uname}"/></td>
</tr>
<tr>
<td>密码</td>
<td><input type="text" name="pwd" value="${u.password}"/></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age" value="${u.age}"/></td>
</tr>
<tr>
<td colspan=""><input type="submit" value="提交修改" /></td>
</tr>
</table>
</form>
</center>
</body>
</html>