jdbc_servlet基础增删改分页2(userinfo表的)
生活随笔
收集整理的這篇文章主要介紹了
jdbc_servlet基础增删改分页2(userinfo表的)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.創建如下文件目錄
?
2.導入MyBatis的jar文件
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;}@Overridepublic 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==0?pageCount/pageSize:pageCount/pageSize+1;this.stratrow=(pageNo-1)*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 blockSystem.out.println("數據庫異常");e.printStackTrace();}}//6.定義鏈接數據庫的方法public Connection getConnection(){try {//驅動管理對象去加載數據庫地址,用戶名,密碼鏈接數據庫conn=DriverManager.getConnection(URL, username, password);} catch (SQLException e) {// TODO Auto-generated catch blockSystem.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 = 0; i < param.length; i++) {ptsm.setObject(i+1, 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=0;conn=this.getConnection();try {//從建立的鏈接中獲取執行查詢的對象,請獲取sql語句ptsm=conn.prepareStatement(sql);//將sql對象補充完整if (param!=null) {for (int i = 0; i < param.length; i++) {ptsm.setObject(i+1, 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 stubString 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 blockSystem.out.println("查詢所有解析異常");e.printStackTrace();}finally{this.closeAll(conn, ptsm, rs);}return list;}/*** 根據ID查詢*/public Userinfo getByID(Integer ID) {// TODO Auto-generated method stubString 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 blockSystem.out.println("find ID error");e.printStackTrace();}finally{this.closeAll(conn, ptsm, rs);}return userinfo;}/*** 根據用戶名查詢*/public Userinfo getByNameByPWD(Userinfo userinfo) {// TODO Auto-generated method stubString 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 blockSystem.out.println("find ID error");e.printStackTrace();}finally{this.closeAll(conn, ptsm, rs);}return user;}/*** 添加*/public int insert(Userinfo userinfo) {// TODO Auto-generated method stubString 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 stubString 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 stubString 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 stubString sql="select count(*) from userinfo";int num=0;rs=this.executeQuery(sql, null);try {if (rs.next()) {num=rs.getInt(1);}} catch (SQLException e) {// TODO Auto-generated catch blockSystem.out.println("查總條數返回結果異常");e.printStackTrace();}return num;}/*** 分頁查詢*/public List<Userinfo> pagefind(Page page) {// TODO Auto-generated method stubString 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 blockSystem.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 stubreturn udao.findAll();}public Userinfo getByID(Integer ID) {// TODO Auto-generated method stubreturn udao.getByID(ID);}public Userinfo login(String uname,String pwd) {// TODO Auto-generated method stubUserinfo userinfo=new Userinfo(uname, pwd);return udao.getByNameByPWD(userinfo);}public int insert(Userinfo userinfo) {// TODO Auto-generated method stubreturn udao.insert(userinfo);}public int delete(Integer ID) {// TODO Auto-generated method stubreturn udao.delete(ID);}public int update(Userinfo userinfo) {// TODO Auto-generated method stubreturn udao.update(userinfo);}public int totalCount() {// TODO Auto-generated method stubreturn udao.totalCount();}/*** 分頁*/public List<Userinfo> pagefind(int pageNo,int pageSize) {// TODO Auto-generated method stubPage 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=0;if (uid!=null) {id=Integer.parseInt(uid);}int age=0;if (uage!=null) {age=Integer.parseInt(uage);}int pageNo=1;if (pano!=null) {pageNo=Integer.parseInt(pano);}int pageSize=3;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(1, uname, password, age);System.out.println("添加的用戶是:"+userinfo);int num=us.insert(userinfo);if (num>0) {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>0) {System.out.println("修改成功");response.sendRedirect("UserinfoServlet");} else {System.out.println("修改失敗");}//刪除}else if (flag.equals("delete")) {int num=us.delete(id);if (num>0) {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="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><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="2"><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="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><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="2"><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="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><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="4"><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="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><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="2"><input type="submit" value="提交修改" /></td></tr></table></form></center></body> </html>?
轉載于:https://www.cnblogs.com/samsblog/p/5564571.html
總結
以上是生活随笔為你收集整理的jdbc_servlet基础增删改分页2(userinfo表的)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 嵌入视频音频
- 下一篇: Linux下面 多线程死锁问题的调试