servlet+jsp数据库增删改查实例

 

个人觉得这种模式是MVC模式

1.      先写一个类,类里面有几个属性。 

2.      写一个接口。里面有增删改查的方法。                   (写在service里)

3.      写一个类实现这个接口(实现里面的增删改查等操作)     (写在service里)

4.      连接数据库

5.      写 servlet操作,  处理增删改查的信息。

6.      Jsp页面 (写页面显示或者上传,添加的页面布局等)与servlet实现交互,从而实现以上功能。

 

增删改查具体实例如下————  具体代码:

XinxManager.java

package cn.hpu.service;

importjava.util.List;

importcn.hpu.gu.Xinx;

//定义接口 增删改查,获取表单信息,通过id获取信息等方法

public interfaceXinxManager{

      public ListgetXinxs();

      public boolean add(Xinx xin);

      public boolean  del(String id);

      public boolean update( Xinx xin);

      public boolean select(String name,Stringpassword);

      public Xinx  getXinxById(String id);

}

 

//定义一个类实现这个接口的方法

XinxManagerImp.Java

 

 

 

packagecn.hpu.service;

 

importjava.sql.Connection;

importjava.sql.ResultSet;

importjava.sql.Statement;

importjava.util.ArrayList;

importjava.util.List;

 

importcn.hpu.gu.Xinx;

importcn.hpu.util.util;

 

importcom.mysql.jdbc.PreparedStatement;

 

public classXinxManagerImp  implements XinxManager{

 

     

    //增加

      public boolean add(Xinx xin) {

           boolean          flag =  false;

//定义一个标志,赋值为false

           Connection  conn = null;

           PreparedStatement pst =null;

         conn = util.getConnection();

     String sql="insert into report(title,speaker ,address ,unit , time,content,dateposted)values(?,?,?,?,?,?,?)";

//几个参数几个问号,这里id设置的是自增的所以没必要添加

       try{

conn = util.getConnection();  

pst = (PreparedStatement)conn.prepareStatement(sql);

           //pst.setString(1, xin.getId());

           //pst.setInt(1, xin.getId());

//get所要添加的信息,set到数据库对应的位置

            pst.seString(, xin.getTitle());

            pst.setString(2, xin.getSpeaker());

            pst.setString(3, xin.getAddress());

            pst.setString(4, xin.getUnit());

            pst.setString(5, xin.getTime().toString());

            pst.setString(6, xin.getContent());

            pst.setString(7,xin.getDateposted().toString());

           //executeUpdate(sql)是更新数据,

            //返回int类型是返回的更新了多少行,也就是受影响的行数,如果为0,则表示无更新

          

            int rows = pst.executeUpdate();

            if(rows>0)

            {

                   flag=true;

                   }

       }catch (Exception e) {

           e.printStackTrace();

      }finally{

           util.close(pst, conn);

      }

       return flag;        //返回flag方便后面的获取

      }

   

      //删除

      public boolean del(String id) {

           boolean   flag = false;

Connection conn = null;

           PreparedStatement pst = null;

           conn = util.getConnection();

           try{

                 String sql = "delete fromreport where id like?";

                 pst = (PreparedStatement)conn.prepareStatement(sql);

                 pst.setString(1, id);

                 int rows = pst.executeUpdate();

                 if(rows>0){

                  flag = true;

                 }

           }catch (Exception e) {

                 e.printStackTrace();

                 }finally{

                      util.close(pst, conn);

                 }

                 return flag;

      }

 

      //查询

      public List getXinxs() {

//用到了类型转换  (方法内定义的 public ListgetXinxs();)

           List list = newArrayList();

          

            Connection conn = null;

            ResultSet rs = null;    //!!!!!!!

         Statement stmt = null;

         try{

           conn = util.getConnection();

           String sql = "select * fromreport";

                       //创建Statement (Sql语句的执行环境)

           stmt = conn.createStatement();

                      

           rs = stmt.executeQuery(sql);

                 //executeQuery(StringsqlString)执行查询数据库的SQL,

                 //eg:SELECT语句,返回一个结果集(ResultSet)

           while( rs.next()){     //!!!!

           Xinx xin = new Xinx();

             //查询。类的所有成员信息都set出来

           xin.setId(rs.getString("id"));

//解读一下,请求获取 字符串,然后都set出来

           xin.setSpeaker(rs.getString("speaker"));               xin.setAddress(rs.getString("address"));

           xin.setTitle(rs.getString("title"));

           xin.setTime(rs.getString("time"));

           xin.setContent(rs.getString("content"));

           xin.setUnit(rs.getString("unit"));

            xin.setDateposted(rs.getString("dateposted"));

            list.add(xin);   //!!!!!!

           }

         }catch (Exception e) {

                 e.printStackTrace();

           }finally{

           util.close(rs, stmt, conn);

           }

       return list;

      }

     

 //修改

      public boolean update(Xinx xin){

         boolean flag = false;

           Connection conn = null;

           java.sql.PreparedStatement pst =null;

           conn = util.getConnection();

           String sql= "update report settitle=?,speaker=?,address=?,unit=?,time=?,content=?,dateposted=? where id ="+xin.getId();     //where id =?";  (两个是一个意思,自where后的东西,是可以替换的,下面会稍作修改,因为多了一个问号)       

          

           try{

                 pst =conn.prepareStatement(sql);

                 pst.setString(1,xin.getTitle());

                 pst.setString(2,xin.getSpeaker());  

                 pst.setString(3,xin.getAddress());

                 pst.setString(4,xin.getUnit());

                 pst.setString(5,xin.getTime());

                 pst.setString(6, xin.getContent());

                 pst.setString(7,xin.getDateposted());

                 //如果不加这个会出错(Statement parameter 8 not set.)说为设置,所以如果用问号,那就几个问号,设计几个Statement parameter。

              //pst.setString(8, xin.getId());

                 int  rows = pst.executeUpdate();

                 if(rows>0)

                 {flag = true;}

           }catch (Exception e)

           {

                 e.printStackTrace();

           }

            finally

           {

                 util.close(pst, conn);

                 }

          

           return flag;

      }

     

     

      //根据id查询它的所有信息

     

      public Xinx getXinxById(String id) {

      Connection conn = null;

       ResultSet rs = null;

       Statement  stmt = null;

       Xinx xin = new Xinx();

       try{

            conn = util.getConnection();

            String sql = "select * from report whereid ="+id;

           stmt = conn.createStatement();

           rs =  stmt.executeQuery(sql);

           while(rs.next())

           {

          //测试一下看看获取id了木有

                System.out.println(rs.getString("id")+"通过id查询信息");

                if(rs.getString("id").equals(id)) {

                            //查询  显示出来

                      xin.setId(rs.getString("id"));

                      xin.setTitle(rs.getString("title"));

                   xin.setSpeaker(rs.getString("speaker"));

                   xin.setAddress(rs.getString("address"));

                   xin.setTime(rs.getString("time"));

                   xin.setContent(rs.getString("content"));

                   xin.setUnit(rs.getString("unit"));

                   xin.setDateposted(rs.getString("dateposted"));

                      }

           }

            

       }catch (Exception e)

       {

            e.printStackTrace();

      }finally

      {

           util.close(rs, stmt, conn);

      }

        

      System.out.println(xin.getId());

      return xin;

      }

     

      public boolean select(String name, Stringpassword) {

           // TODO Auto-generated method stub

           return false;

      }

 

}

addServlet.java

packagecn.hpu.servlet;

importjava.io.IOException;

importjava.io.PrintWriter;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

importcn.hpu.gu.Xinx;

importcn.hpu.service.XinxManager;

importcn.hpu.service.XinxManagerImp;

 

public classAddServlet extends HttpServlet {

 

      public void doGet(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

                 this.doPost(request, response);

          

      }

 

      public void doPost(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

         //防止中文乱码,这样最保险  

           response.setContentType("text/html;chartset=utf-8");

           request.setCharacterEncoding("utf-8");

           response.setCharacterEncoding("utf-8");

             

           //   request.getParameter()获取jsp页面提交的数据

        String  id = request.getParameter("id");

           String title =request.getParameter("title");

           String speaker = request.getParameter("speaker");

           String address =request.getParameter("address");

           String unit =request.getParameter("unit");

           String time =request.getParameter("time");

           String content =request.getParameter("content");

           String dateposted = request.getParameter("dateposted");

          

           Xinx xin = new Xinx();

           //xin.setId(0);

           xin.setTitle(title);

           xin.setSpeaker(speaker);

           xin.setAddress(address);

           xin.setUnit(unit);

           xin.setTime(time);

           xin.setContent(content);

           xin.setDateposted(dateposted);

          

           XinxManager   xm = new XinxManagerImp();

           boolean flag = xm.add(xin);

          

           System.out.println("增加这里的"+flag);

          

           if(flag == true )

           //跟上面的意思是一样的if(flag)

                 {

                 //作用:增加成功后会调到一个页面,显示出来

                   Xinx xin1 = xm.getXinxById(id);

                   //通过id获的这组信息,用setAttribute传到表单页面

                request.setAttribute("xin1", xin);

//在     login1.jsp显示新添加的信息,这样一目了然         

request.getRequestDispatcher("login1.jsp").forward(request,response);

                  

                 /*或者直接跳到主页面

                 //request.setAttribute("param","success");

                 System.out.println("添加成功");

                 //request.getRequestDispatcher("login.jsp").forward(request,response);

                 response.setContentType("text/html");

                 PrintWriter out =response.getWriter();

                 out.println("");

                 out.println("");

                 out.println("  添加成功");

                 out.println("  ");

                 out.println("添加成功!!!");

                 out.println(" 返回主页面");

                 out.println("  ");

                 out.println("");

                 out.flush();

                 out.close();

*/

           }else {

                

                 //request.setAttribute("param","failed");

                 System.out.println("添加失败");

                 //如果添加失败转发到原来的页面

                 request.getRequestDispatcher("add.jsp").forward(request,response);

                

           }

      }

 

}

 

 

 

 

 

 

 

<%@ page language="java"import="java.util.*,cn.hpu.gu.*" pageEncoding="utf-8"%>

<%

String path =request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

Login1.jsp

DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>My JSP 'login1.jsp' starting pagetitle>

   

    <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">

   

 

  head>

 

  <body>

   

 

   <h3>增加或者修改后的信息   | <a href="login.jsp">返回主界面a>  h3>

  

   <table border="1"cellpadding="0" cellspacing="0"width="80%" align="center">

  <tr>

      

         <th>题目th>

         <th>主讲th>

         <th>地址th>

         <th>主讲人单位th>

         <th>时间th>

         <th>内容th>

         <th>发布时间th>

         <th>操作th>

  tr>

    <%

   

        

                             //   XinxManager xm= new XinxManagerImp(); 

   

                          // List list = xm.getXinxs();

       

                         //  if(list!=null)

                       // {

                      //    for(int i=0; i

                         // {

                                //   Xinx xin =list.get(i);

    

   

      

         Xinx xin =(Xinx)request.getAttribute("xin1");

          if(xin!=null)

    

    {

       

   %>

 <tr>

      

        <td><%=xin.getTitle() %>td>

        <td><%=xin.getSpeaker() %>td>

        <td><%=xin.getAddress()%>td>

        <td><%=xin.getUnit() %>td>

        <td><%=xin.getTime() %>td>

        <td><%=xin.getContent() %>td>

        <td><%=xin.getDateposted()%>td>

       

        <td>

        <a href="DelServlet?id=<%=xin.getId() %>">删除a>

        <a href="UpdateServlet1?id=<%=xin.getId() %>">修改a> 

        

        td>

   

  tr> 

  <%

  //    }

   }

   %>

  table> 

  body>

html>

 

 

 

 

DelServlet.Java

packagecn.hpu.servlet;

 

importjava.io.IOException;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importcn.hpu.service.XinxManager;

importcn.hpu.service.XinxManagerImp;

 

public classDelServlet extends HttpServlet {

 

     

      public void doGet(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

                 this.doPost(request, response);

          

      }

      public void doPost(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

           String id =request.getParameter("id");

           XinxManager  xm = new XinxManagerImp();

           boolean flag = xm.del(id);

           if(flag == true)

           {

          response.sendRedirect("login.jsp");  

           }

          

          

      }

 

}

Search.java   查询的servlet

packagecn.hpu.servlet;

 

importjava.io.IOException;

importjava.sql.ResultSet;

importjava.util.List;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

importorg.omg.PortableServer.ForwardRequest;

 

 

importcn.hpu.gu.Xinx;

importcn.hpu.service.XinxManager;

importcn.hpu.service.XinxManagerImp;

 

public classSearch extends HttpServlet {

 

      public void doGet(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

                 this.doPost(request, response);

      }

 

      public void doPost(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

              XinxManager xm = new XinxManagerImp();

              List  list =xm.getXinxs();

              request.setAttribute("list", list);

              //转发

              request.getRequestDispatcher("login.jsp").forward(request,response);

             

      }

}

 

Login.jsp

 

 

 

<%@ page language="java"import="java.util.*,cn.hpu.gu.*" pageEncoding="utf-8"%>

<%@page import="cn.hpu.service.XinxManager"%>

<%@page import="cn.hpu.service.XinxManagerImp"%>

<%

String path =request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>管理员操作页面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">

   

 

  head>

  <h2>管理信息h2>

 

       欢迎${sessionScope.loginuser}登陆

 

 

   <a href="add.jsp">添加学生a>  <a href= "index.jsp">退出a>

    

  

   <hr/>

  <body>

 

  <table border="1"cellpadding="0" cellspacing="0"width="80%" align="center">

  <tr>

      

         <th>题目th>

         <th>主讲th>

         <th>地址th>

         <th>主讲人单位th>

         <th>时间th>

         <th>内容th>

         <th>发布时间th>

         <th>操作th>

  tr>

    <%

   

       

    XinxManager xm = new XinxManagerImp();

    List list = xm.getXinxs();

  

     if(list!=null)

     {

     for(int i=0; i

     {

        Xinx xin = list.get(i);

    

    

   

       

   %>

 <tr>

      

        <td><%=xin.getTitle() %>td>

        <td><%=xin.getSpeaker() %>td>

        <td><%=xin.getAddress()%>td>

        <td><%=xin.getUnit() %>td>

        <td><%=xin.getTime() %>td>

        <td><%=xin.getContent() %>td>

        <td><%=xin.getDateposted()%>td>

       

        <td>

        <a href="DelServlet?id=<%=xin.getId() %>">删除a>

        <a href="UpdateServlet1?id=<%=xin.getId() %>">修改a> 

        

        td>

   

  tr> 

  <%

   }

   }

   %>

  table>

 

  body>

html>

 

UpdateServlet1.java

 

packagecn.hpu.servlet;

 

importjava.io.IOException;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importcn.hpu.gu.Xinx;

importcn.hpu.service.XinxManager;

importcn.hpu.service.XinxManagerImp;

 

public classUpdateServlet1 extends HttpServlet {

 

          //通过login.jsp中的修改跳这,(获取数据库中要更改单的信息)

      public void doGet(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

 

            this.doPost(request, response);

      }

 

      public void doPost(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

             

            //通过id获取要修改的信息

                 String id =request.getParameter("id");

                 XinxManager  xm = new XinxManagerImp();

                 System.out.println("获取数据库中要更新id的所有信息"+id);

                

                 //调用XinxManagerImp.java里的方法

                 Xinx  xin = xm.getXinxById(id);

          

              if(xin != null)

              {

                  //通过id获得的xin的信息用setAttribute方法穿到表单中

                  request.setAttribute("xin",xin);

                  //跳转到更改页面

                  request.getRequestDispatcher("update.jsp").forward(request,response);              }

               

             }

 

}

 

update.jsp

 

 

 

<%@ page language="java"import="java.util.*,cn.hpu.gu.*" pageEncoding="utf-8"%>

<%

String path =request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>修改页面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">

   

 

  head>

 

   <%

     //表单中通过getAttribute获取setAttribute 传来的xin的信息

     Xinx xin =(Xinx)request.getAttribute("xin");

     

 

   %>

 

  <body>

   <h1>修改信息h1>

   <hr/>

      

   <form action="UpdateServlet"method="post">

   <table>

            

       <input name="id" type="text" value="<%=xin.getId()%> " style="display: none;"/>  

      <tr align="left"> <th> 题  目th>

         <th><input name="title" type="text"value="<%=xin.getTitle()%>">th>

        tr>

      <tr align="left"><th> 主  讲th>

          <th><input name="speaker"type="text"  value="<%=xin.getSpeaker() %>">th>

      tr>

    <tr align="left">

           <th> 地  址th> <th><input name="address"type="text" value="<%=xin.getAddress()%>"> th>

   tr>

    <tr align="left">

           <th>主讲人单位th> <th><input name="unit"type="text" value="<%=xin.getUnit() %> ">th>

    tr>

    <tr align="left">

            <th> 时  间th> <th><input name="time"type="date" value="<%=xin.getTime() %> ">th>

   tr>

    <tr align="left">

           <th>  内  容th> <th ><input name="content"type="text" value=" <%=xin.getContent() %> ">th>

   tr>

    <tr align="left">

           <th>发布时间th> <th><input name="dateposted" type="date" value=" <%=xin.getDateposted()%>">th>

   tr>

 

         <tr align="left">

         <th><input type="submit"value=" 修改" />th>

   tr>

  

   table>

  form>

 

  body>

html>

 

UpdateServlet.java

 

packagecn.hpu.servlet;

 

importjava.io.IOException;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

 

importcn.hpu.gu.Xinx;

importcn.hpu.service.XinxManager;

importcn.hpu.service.XinxManagerImp;

 

public classUpdateServlet extends HttpServlet {

 

     

      //进行数据库中信息修好,也就是重新获取修改后提交的信息

 

      public void doGet(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

                 this.doPost(request, response);

      }

 

     

      public void doPost(HttpServletRequestrequest, HttpServletResponse response)

                 throws ServletException,IOException {

                      response.setContentType("text/html;chartset=utf-8");

                      response.setCharacterEncoding("utf-8");

                      request.setCharacterEncoding("utf-8");

                 

                      //request.getParameter()方法是获取Http(这里是更改表单)提交过来的数据

                      String id = request.getParameter("id");

                      String title =request.getParameter("title");

                      String speaker =request.getParameter("speaker");

                      String address =request.getParameter("address");

                      String unit =request.getParameter("unit");

                      String time = request.getParameter("time");

                      String content =request.getParameter("content");

                      String dateposted =request.getParameter("dateposted");

                       

                      XinxManager xm = newXinxManagerImp();

                       Xinx xin = new Xinx();

                          //将新数据set进去。。。

                       xin.setId(id);

                       xin.setTitle(title);

                       xin.setSpeaker(speaker);

                       xin.setAddress(address);

                       xin.setUnit(unit);

                       xin.setTime(time);

                       xin.setContent(content);

                       xin.setDateposted(dateposted);

                          //调用update(Xinxxin)方法{里面将get的新数据信息,再set到数据库中,从而完成修改}

                     

                       boolean flag = xm.update(xin);

                        System.out.println("修改后提交的信息"+id);

                       if(flag == true)

                       {      

                                //例子

                                //Student stu1 = sm.getStudentById(id);

                                  //request.setAttribute("stu1",stu1);

                                

                                  Xinx xin1 = xm.getXinxById(id);

                                  request.setAttribute("xin1",xin);

                                 request.getRequestDispatcher("login1.jsp").forward(request,response);

                              System.out.println(xin.getId()+"9999999999999");

                            //request.getRequestDispatcher("login.jsp").forward(request,response);

                       }else

                       {

                       }

      }

}

 

 

你可能感兴趣的:(servlet+jsp数据库增删改查实例)