Servlet 实现增删改查功能


MVCMVCMVCMVC模式模式模式模式 � M:Model,即模型,对于 JavaBean � V:View, 即试图,对应 JSP 页面 � C:Controller,即控制器,对应 Servlet 1. 以下为 MVC实现一个简单的 增删改查 功能 1> 显示记录 2> 增加一条记录 3> 修改一条记录 4> 删除一条记录 程序源代码: M层:模型层 1.封装一条信息的所有属性 JavaBean.java ,即 VO packagepackagepackagepackage muta.bean; /** *@author@author@author@author help *封装一条信息的所有属性 */ publicpublicpublicpublic classclassclassclass JavaBean { privateprivateprivateprivate intintintint id; privateprivateprivateprivate String name; privateprivateprivateprivate String password; privateprivateprivateprivate String sex; privateprivateprivateprivate intintintint age; publicpublicpublicpublic intintintint getId() { returnreturnreturnreturn id; } publicpublicpublicpublic voidvoidvoidvoid setId(intintintint id) { thisthisthisthis.id = id; } publicpublicpublicpublic String getName() { returnreturnreturnreturn name; } publicpublicpublicpublic voidvoidvoidvoid setName(String name) { thisthisthisthis.name = name; } publicpublicpublicpublic String getPassword() { returnreturnreturnreturn password; } publicpublicpublicpublic voidvoidvoidvoid setPassword(String password) { thisthisthisthis.password = password; } publicpublicpublicpublic String getSex() { returnreturnreturnreturn sex; } publicpublicpublicpublic voidvoidvoidvoid setSex(String sex) { thisthisthisthis.sex = sex; } publicpublicpublicpublic intintintint getAge() { returnreturnreturnreturn age; } publicpublicpublicpublic voidvoidvoidvoid setAge(intintintint age) { thisthisthisthis.age = age; } } 2.封装数据库连接以及操作 JavaBean 所用到的方法,即 DAO packagepackagepackagepackage muta.bean; importimportimportimport java.sql.Connection; importimportimportimport java.sql.DriverManager; importimportimportimport java.sql.PreparedStatement; importimportimportimport java.sql.ResultSet; importimportimportimport java.sql.SQLException; importimportimportimport java.util.ArrayList; importimportimportimport java.util.List; /** *@author@author@author@author help *操作数据库的方法 */ publicpublicpublicpublic classclassclassclass SqlBean { Connection con; PreparedStatement pre; ResultSet rs; publicpublicpublicpublic SqlBean() { trytrytrytry { Class.forName("com.mysql.jdbc.Driver"); } catchcatchcatchcatch (ClassNotFoundException e) { e.printStackTrace(); } trytrytrytry { con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/M yServlet","root","122828"); } catchcatchcatchcatch (SQLException e) { e.printStackTrace(); } } /** *@author@author@author@author help * *插入新的一条记录 *@return@return@return@return */ publicpublicpublicpublic intintintint getInsert(String sql,JavaBean jBean) { intintintint count =0; trytrytrytry { pre = con.prepareStatement(sql); pre.setString(1,jBean.getName()); pre.setString(2,jBean.getPassword()); pre.setString(3,jBean.getSex()); pre.setInt(4,jBean.getAge()); count=pre.executeUpdate(); } catchcatchcatchcatch (SQLException e) { e.printStackTrace(); } finallyfinallyfinallyfinally { trytrytrytry { pre.close(); con.close(); } catchcatchcatchcatch (SQLException e) { //TODOTODOTODOTODO Auto-generated catch block e.printStackTrace(); } } returnreturnreturnreturn count; } /** *@author@author@author@author help * *删除一条记录 *@return@return@return@return */ publicpublicpublicpublic intintintint getDelete(String sql,intintintint id) { intintintint count =0; trytrytrytry { pre = con.prepareStatement(sql); pre.setInt(1, id); count=pre.executeUpdate(); } catchcatchcatchcatch (SQLException e) { e.printStackTrace(); } finallyfinallyfinallyfinally { trytrytrytry { pre.close(); con.close(); } catchcatchcatchcatch (SQLException e) { //TODOTODOTODOTODO Auto-generated catch block e.printStackTrace(); } } returnreturnreturnreturn count; } /** *@author@author@author@author help * *根据ID查询某一条记录 *@return@return@return@return */ publicpublicpublicpublic JavaBean getSearchById(String sql,intintintint id) { JavaBean jBean = newnewnewnew JavaBean(); trytrytrytry { pre = con.prepareStatement(sql); pre.setInt(1, id); rs=pre.executeQuery(); whilewhilewhilewhile(rs.next()) { jBean.setId(rs.getInt("id")); jBean.setName(rs.getString("name")); jBean.setPassword(rs.getString("password")); jBean.setSex(rs.getString("sex")); jBean.setAge(rs.getInt("age")); } } catchcatchcatchcatch (SQLException e) { e.printStackTrace(); } returnreturnreturnreturn jBean; } /** *@author@author@author@author help * *更新某一条记录 *@return@return@return@return */ publicpublicpublicpublic intintintint getUpdate(String sql,JavaBean jBean) { intintintint count =0; trytrytrytry { pre = con.prepareStatement(sql); pre.setInt(5,jBean.getId()); pre.setString(1,jBean.getName()); pre.setString(2,jBean.getPassword()); pre.setString(3,jBean.getSex()); pre.setInt(4,jBean.getAge()); count = pre.executeUpdate(); } catchcatchcatchcatch (SQLException e) { //TODOTODOTODOTODO Auto-generated catch block e.printStackTrace(); } finallyfinallyfinallyfinally { trytrytrytry { pre.close(); con.close(); } catchcatchcatchcatch (SQLException e) { //TODOTODOTODOTODO Auto-generated catch block e.printStackTrace(); } } returnreturnreturnreturn count; } /** *@author@author@author@author help * *显示所有记录 *@return@return@return@return */ publicpublicpublicpublic List getSearch(String sql) { List list = newnewnewnew ArrayList(); //获取 prepareStatement对象 trytrytrytry { pre = con.prepareStatement(sql); rs =pre.executeQuery(); whilewhilewhilewhile(rs.next()) { JavaBean jBean =newnewnewnew JavaBean(); jBean.setId(rs.getInt("id")); jBean.setName(rs.getString("name")); jBean.setPassword(rs.getString("password")); jBean.setSex(rs.getString("sex")); jBean.setAge(rs.getInt("age")); list.add(jBean); } } catchcatchcatchcatch (SQLException e) { //TODOTODOTODOTODO Auto-generated catch block e.printStackTrace(); } finallyfinallyfinallyfinally { trytrytrytry { pre.close(); con.close(); } catchcatchcatchcatch (SQLException e) { //TODOTODOTODOTODO Auto-generated catch block e.printStackTrace(); } } returnreturnreturnreturn list; } } V层:试图层 1. 显示记录集的页面 SearchList.jsp <%@pagelanguage="java"import="java.util.*" pageEncoding="UTF-8"%> <% Stringpath=request.getContextPath(); StringbasePath= request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> 显示记录
学生信息如下:
ID 姓名 密码 性别 年龄
操作
<% Stringsql="select*fromstudentorderbyid"; java.util.Listlist=sBean.getSearch(sql); forforforfor(java.util.Iteratorit =list.iterator();it.hasNext();) { //获取一个JavaBean对象 jBean=(muta.bean.JavaBean)it.next(); %> <%=jBean.getId()%> <%=jBean.getName()%> <%=jBean.getPassword()%> <%=jBean.getSex()%> <%=jBean.getAge()%> 增加 ">删 除  更新 <%}%>
2. 插入页面 Insert.jsp <%@pagelanguage="java"import="java.util.*" pageEncoding="UTF-8"%> <% Stringpath=request.getContextPath(); StringbasePath= request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> 插入新值
学生管理页面
姓名: 密码: 性别: 女 年龄:
查询
3. 更新页面 Update.jsp <%@pagelanguage="java"import="java.util.*" pageEncoding="UTF-8"%> <% Stringpath=request.getContextPath(); StringbasePath= request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> 更新
学生管理页面
学生ID: " readonly> 学生姓名: "> 学生密码: " > 学生性别: >男 >女 学生年龄: " >
查询
4. 出错页面 Error.jsp <%@pagelanguage="java"import="java.util.*" pageEncoding="UTF-8"%> <% Stringpath=request.getContextPath(); StringbasePath= request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> 出错啦!!! 对不起!您<%=request.getAttribute("error")%>失败 C层:控制层—Servlet 1.显示记录集的 Servlet----SearchById.java packagepackagepackagepackage muta.servlet; importimportimportimport java.io.IOException; importimportimportimport javax.servlet.ServletException; importimportimportimport javax.servlet.http.HttpServlet; importimportimportimport javax.servlet.http.HttpServletRequest; importimportimportimport javax.servlet.http.HttpServletResponse; importimportimportimport muta.bean.JavaBean; importimportimportimport muta.bean.SqlBean; publicpublicpublicpublic classclassclassclass SearchById extendsextendsextendsextends HttpServlet { privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal longlonglonglong serialVersionUID = 1L; /** * The doDelete method of the servlet.
* * This method is called when a HTTP delete request is received. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doDelete(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //获取用户ID String sid = request.getParameter("id"); intintintint id =Integer.parseInt(sid); String sql ="select * from student where id=?"; SqlBean sBean = newnewnewnew SqlBean(); JavaBean jBean = sBean.getSearchById(sql, id); //用户ID request.setAttribute("id",jBean.getId()); //用户姓名 request.setAttribute("name",jBean.getName()); //用户密码 request.setAttribute("password",jBean.getPassword()); //用户性别 String sex=""; String man=""; String woman=""; ifififif(jBean.getSex()!=nullnullnullnull) { sex=jBean.getSex().trim(); ifififif(sex.equals("男")) { man ="checked"; } elseelseelseelse { woman ="checked"; } } request.setAttribute("man",man); request.setAttribute("woman",woman); //用户年龄 request.setAttribute("age",jBean.getAge()); //转发 request.getRequestDispatcher("Update.jsp").forward(request, response); } } 2.增加记录的 Servlet----Insert.java packagepackagepackagepackage muta.servlet; importimportimportimport java.io.IOException; importimportimportimport javax.servlet.ServletException; importimportimportimport javax.servlet.http.HttpServlet; importimportimportimport javax.servlet.http.HttpServletRequest; importimportimportimport javax.servlet.http.HttpServletResponse; importimportimportimport muta.bean.SqlBean; importimportimportimport muta.bean.JavaBean; publicpublicpublicpublic classclassclassclass Insert extendsextendsextendsextends HttpServlet { /** * */ privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal longlonglonglong serialVersionUID = 1L; /** * The doDelete method of the servlet.
* * This method is called when a HTTP delete request is received. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doDelete(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { response.setContentType("text/html"); doPost(request,response); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //获取前台页面数据 String name =request.getParameter("name"); String password =request.getParameter("password"); String sex =request.getParameter("sex"); String sage = request.getParameter("age"); intintintint age =Integer.parseInt(sage); //封装到JavaBean对象中去 JavaBean jBean = newnewnewnew JavaBean(); ת转发// { ;(" ��ע","request.setAttribute("error url ="error.jsp"; { elseelseelseelse } url="SearchList.jsp"; { ifififif(count>0) String url=""; intintintint count =sBean.getInsert(sql,jBean); SqlBean sBean = newnewnewnew SqlBean(); values(?,?,?,?)"; String sql = "insert into student(name,password,sex,age) //调用模型层 jBean.setAge(age); jBean.setSex(sex); jBean.setPassword(password); jBean.setName(name); request.getRequestDispatcher("SearchList.jsp").forward(request, response); } } 3.更新记录的 Servlet----Updated.java packagepackagepackagepackage muta.servlet; importimportimportimport java.io.IOException; importimportimportimport java.io.PrintWriter; importimportimportimport javax.servlet.ServletException; importimportimportimport javax.servlet.http.HttpServlet; importimportimportimport javax.servlet.http.HttpServletRequest; importimportimportimport javax.servlet.http.HttpServletResponse; importimportimportimport muta.bean.JavaBean; importimportimportimport muta.bean.SqlBean; publicpublicpublicpublic classclassclassclass Update extendsextendsextendsextends HttpServlet { /** * */ privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal longlonglonglong serialVersionUID = 1L; /** * The doDelete method of the servlet.
* * This method is called when a HTTP delete request is received. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doDelete(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //获得前台表单信息 String sid = request.getParameter("id"); intintintint id =Integer.parseInt(sid); String name =request.getParameter("name"); String password =request.getParameter("password"); String sex =request.getParameter("sex"); String sage = request.getParameter("age"); intintintint age =Integer.parseInt(sage); //封装到JavaBean对象中去 JavaBean jBean = newnewnewnew JavaBean(); jBean.setId(id); jBean.setName(name); jBean.setPassword(password); jBean.setSex(sex); jBean.setAge(age); String sql ="update student set name=?,password=?,sex=?,age=? where id=?"; SqlBean sBean = newnewnewnew SqlBean(); intintintint count =sBean.getUpdate(sql,jBean); String url=""; ifififif(count>0) { url="SearchList.jsp"; } elseelseelseelse { url ="error.jsp"; request.setAttribute("error","更新"); } request.getRequestDispatcher("SearchList.jsp").forward(request, response); } } 4.删除记录的 Servlet----Delete.java packagepackagepackagepackage muta.servlet; importimportimportimport java.io.IOException; importimportimportimport javax.servlet.ServletException; importimportimportimport javax.servlet.http.HttpServlet; importimportimportimport javax.servlet.http.HttpServletRequest; importimportimportimport javax.servlet.http.HttpServletResponse; importimportimportimport muta.bean.SqlBean; publicpublicpublicpublic classclassclassclass Delete extendsextendsextendsextends HttpServlet { privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal longlonglonglong serialVersionUID = 1L; /** * The doDelete method of the servlet.
* * This method is called when a HTTP delete request is received. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doDelete(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { response.setContentType("text/html"); doPost(request,response); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * *@param@param@param@param request the request send by the client to the server *@param@param@param@param response the response send by the server to the client *@throws@throws@throws@throws ServletException if an error occurred *@throws@throws@throws@throws IOException if an error occurred */ publicpublicpublicpublic voidvoidvoidvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsthrowsthrowsthrows ServletException, IOException { response.setContentType("text/html"); //获取超链接传来的数据 String sId = request.getParameter("id"); intintintint id =Integer.parseInt(sId); // //调用模型层删除方法 String sql = "delete from student where id=?"; SqlBean sBean = newnewnewnew SqlBean(); intintintint count =sBean.getDelete(sql, id); String url=""; ifififif(count>0) { url="SearchList.jsp"; } elseelseelseelse { url ="error.jsp"; request.setAttribute("error","删除"); } //转发 request.getRequestDispatcher(url).forward(request, response); } } XML 文件 Update muta.servlet.Update SearchById muta.servlet.SearchById Insert muta.servlet.Insert Delete muta.servlet.Delete Update /Update SearchById /SearchById Insert /Insert Delete /Delete index.jsp
还剩46页未读

继续阅读

下载pdf到电脑,查找使用更方便

pdf的实际排版效果,会与网站的显示效果略有不同!!

需要 8 金币 [ 分享pdf获得金币 ] 1 人已下载

下载pdf

pdf贡献者

mali412824

贡献于2012-09-07

下载需要 8 金币 [金币充值 ]
亲,您也可以通过 分享原创pdf 来获得金币奖励!
下载pdf