精华内容
下载资源
问答
  • servlet+jsp数据库增删改查实例

    万次阅读 2015-03-30 21:55:24
    个人觉得这种模式是MVC模式 1. 先写一个类,类里面有几个属性。...3. 写一个类实现这个接口(实现里面的增删改查等操作) (写在service里) 4. 连接数据库 5. 写 servlet操作, 处理增删改查的信息。

     

    个人觉得这种模式是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 List<Xinx>getXinxs();

          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<Xinx> getXinxs() {

    //用到了类型转换  (方法内定义的 public List<Xinx>getXinxs();)

               List<Xinx> list = newArrayList<Xinx>();

              

                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("<!DOCTYPEHTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

                     out.println("<HTML>");

                     out.println("  <HEAD><TITLE>添加成功</TITLE></HEAD>");

                     out.println("  <BODY>");

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

                     out.println("<a href ='login.jsp'> 返回主页面</a>");

                     out.println("  </BODY>");

                     out.println("</HTML>");

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

     <!--  修改成功! <a href="login.jsp">返回主界面</a>  -->  

     

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

             <th>操作</th>

      </tr>

        <%

       

            

                                 //   XinxManager xm= new XinxManagerImp(); 

       

                              // List<Xinx> list = xm.getXinxs();

           

                             //  if(list!=null)

                           // {

                          //    for(int i=0; i<list.size(); i++)

                             // {

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

        

       

          

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

              if(xin!=null)

        

        {

           

       %>

     <tr>

           <!--  <td><%=xin.getId()%></td>-->

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

             <!-- 点击修改,执行UpdateServlet1,通过id获取要修改的信息,,,转到-->

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

        <!--

        <link rel="stylesheet"type="text/css" href="styles.css">

        -->

     

      </head>

      <h2>管理信息</h2>

     

           欢迎${sessionScope.loginuser}登陆

      <!--

         request.getSession().getAttribute() ${sessionScope}  它们都是取值的,

             前面的是java代码,写在java源文件中,或者jsp<%%>

            后面的属于表达式,直接嵌在HTML代码中取值

            -->

     

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

             <th>操作</th>

      </tr>

        <%

       

           

        XinxManager xm = new XinxManagerImp();

        List<Xinx> list = xm.getXinxs();

      

         if(list!=null)

         {

         for(int i=0; i<list.size(); i++)

         {

            Xinx xin = list.get(i);

        

        

       

           

       %>

     <tr>

           <!--  <td><%=xin.getId()%></td>-->

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

             <!-- 点击修改,执行UpdateServlet1,通过id获取要修改的信息,,,转到-->

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

        <!--

        <link rel="stylesheet"type="text/css" href="styles.css">

        -->

     

      </head>

     

       <%

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

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

         

     

       %>

     

      <body>

       <h1>修改信息</h1>

       <hr/>

          <!-- 然后用 xin.getSpeaker() 等分别获的各自对应位置的数据-->

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

       <table>

                <!--id跟着表单一快传过去,id设置了style="display: none;"表单页面中id被隐藏看不到-->

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

      <!-- form表单中通过action="UpdateServlet" 将数据传到UpdateServlet中,,,转到-->

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

                           {

                           }

          }

    }

     

     

    展开全文
  • JSP对Oracle数据库进行增删改查实例.docx
  • jsp实现增删改查实例,里面有数据库和javaBean代码可以供你参考 jsp实现增删改查实例,里面有数据库和javaBean代码可以供你参考
  • jsp+servlet开发一个链接管理小项目,前台显示层用jsp实现,逻辑层用servlet实现,后台数据库采用mysql数据库,有实体表。适合web新手开发,根据实例能够清楚了解三层之间的关系及应用方法。另外把lib包也上传了,...
  • 十个JSP实例,实现了对数据库增删改查操作
  • 最基础的数据库增删改查操作,里面的实例简单易懂。DBUtil:数据库的连接。XXXDAO:对数据库的操作。XXXServlet:实现层。
  • 1.JSP的配置: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" ...

    1.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 'register.jsp' starting page</title>
    </head>
    
    <body>
        <pre>
            JSP:java servlet page
                jsp也是一个servlet:要继承HttpServlet--->service方法
                jsp当被访问的时候,tomcat会自动把它编译成Java class,会生成一个遵循某个命名规则的clas和Java文件(以login.jsp为例,首先会把.转换为_,然后进行连接--->login_jsp.java/class,这里的命名规则并不遵循Java的驼峰命名规则)
                这个class继承了--->org.apache.jasper.runtime.HttpJspBase--->拥有_jspService
                org.apache.jasper.runtime.HttpJspBase继承了---->HttpServlet--->重写了service方法---->调用了这个class的_jspService方法
                也就是相当于tomcat把jsp文件生成Java类继承了httpservlet
                所以说jsp也就是一个servlet
                ---->必须要配置
                <servlet>
                    <servlet-name></servlet-name>
                    <servlet-class></servlet-class>
                </servlet>
                
                <servlet-mapping>
                    <servlet-name></servlet-name>
                    <url-pattern></url-pattern>
                </servlet-mapping>
                
                jsp在tomcat的conf文件下web.xml进行配置
                 <servlet>
                    <servlet-name>jsp</servlet-name>
                    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
                    <init-param>
                        <param-name>fork</param-name>
                        <param-value>false</param-value>
                    </init-param>
                    <init-param>
                        <param-name>xpoweredBy</param-name>
                        <param-value>false</param-value>
                    </init-param>
                    <load-on-startup>3</load-on-startup>
                </servlet>
                 <servlet-mapping>
                    <servlet-name>jsp</servlet-name>
                    <url-pattern>*.jsp</url-pattern>
                    <url-pattern>*.jspx</url-pattern>
                    </servlet-mapping>
                   所以org.apache.jasper.servlet.JspServlet来处理以jsp为结尾的路径
                   JspServlet-->就是一个servlet--->重写了service方法--->把jsp(warrper)文件转换为class文件
        </pre>
    </body>
    </html>
    复制代码

    2.动态导入和静态导入JSP文件:

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%-- errorPage只能保护运行时异常(404,405,401),不能保护检查时异常(500,600) --%>
    <%@ page isErrorPage="true" %><%-- 标记本页面是否为错误页面,提供后来人观看代码 --%>
    <%@ page errorPage="error.jsp" %>
    <%-- <%@ page import="cn.zzsxt.lee.servlet.*" %> --%><%-- 导入servlet包下的所有Java文件 --%>
    <%@ page import="cn.zzsxt.lee.servlet.Test" %><%-- 导入Test.java --%>
    
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'login.jsp' starting page</title>
    
    </head>
    
    <body>
        
        <pre>
              jsp即可以写html代码,也可以写Java代码
              jsp第一个语法:
              <!-- 是把两个jsp文件合并成了一个jsp文件 -->
              <!-- 静态导入:首先会把两个jsp文件合成一个,然后再通过tomcat进行编译,所以只编译了一次,高耦合,所以效率也会提高 -->
              <%@ include file="top.jsp" %><!-- 无论定位到页面的某一个位置,都能进行导入jsp文件,说白了也就是无论放在任何位置,就把导入的jsp放在哪里 -->
                  <%
                    String name = "zhangsan";
                    System.out.println(name);
                    // String name2 = "lisi1";// 如果使用<%@ include file="top.jsp" %>导入,报两个变量名不能相同
                    String name3;
                    /* int x = 1/0; */
                    //System.out.println(name3);
                    // 运行时异常
                        // 提示错误信息
                        // 只有运行时异常,才会被errorpage保护
                    // 检查时异常
                        // 直接强行中断正在运行的程序
                        Test test = new Test();
                        test.getName();
                %>
                  <%=name%>
                  <%=name2%>
                  <%-- <%=x%> --%>
          </pre>
          
        <a href="register.jsp">我是跳转页面用的</a>
        <!-- 动态导入,会生成两个class文件,从而tomcat编译了两次 -->
        <jsp:include page="footer.jsp"></jsp:include>
    </body>
    </html>
    复制代码

     

    3.重定向和请求转发:

     

    请求转发:
      1.request.getRequestDispatcher("需要跳转的路径").forward(request, response);
      发送一次请求
      地址栏不发生改变
      request可以传递参数(能参数共享)
      请求转发并不能访问到外部资源(外部的地址)

     

    重定向:
      2.response.sendRedirect("需要跳转的路径");
      发送两次请求
      地址栏发生改变
      response不能传递参数(不能参数共享),如果想使用response进行参数传递,就得手动加载,自力更生
      重定向可以访问外部资源

       

      DIY 使用重定向response可以将post请求方式改变为get,反之不能(即默认为get请求方式)。

     

      使用请求转发request,客户端请求是什么方式就是什么方式

     


      请求转发
      当需要传递参数的时候
      访问内部资源的时候建议使用请求转发(服务器内部之间的调用)

      重定向
      访问外部资源
      比较隐私和保密的地址一般推荐使用重定向

      

      请求重定向:客户端行为,response.sendRedirect(),从本质上讲等同于两次请求,前一次的请求对象不会保持,地址栏的URL地址会改变。

     

     

     

      请求转发:服务器行为,request.getRequsetDispatcher().forward(requset,response);是一次请求,转发后请求对象会保存,地址栏的URL地址不会改变。(服务器内部转发,所有客户端看不到地址栏的改变)

     

     

     

    下面举个生活中的实例来说明:

     

      请求重定向:就好比我们找一个A广告公司给设计名片,A明确告诉我们他们不会设计,就让我们找B公司,结果B公司给我设计好了,所以我们会对外宣称是B公司给我们设计的名片,(所以我们就相当于发送了两次次请求,URL地址栏里就从A变成了B公司)

     

     

     

     

     

      请求转发:同样去找A公司给设计名片,A公司虽然不能设计但是他们接下了我们的活,把这项任务外包(转发)给B公司,最终我们会把钱给A公司,也就会对外宣称是A公司给我们设计的名片这就是请求重定向(所以我们就相当于只对A发送了一次请求,URL地址栏里依然是A公司)。

     

     

     4.使用JSP实现数据库的增删改查实例:

     

       注册:

     

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'register.jsp' starting page</title>
    
    
    </head>
    
    <body>
    
    
        <h1>注册页面</h1>
        <form action="deal_register.jsp" method="post">
            用户名:
            <input type="text" name="username" />
            <br /> 密码:
            <input type="password" name="pwd" /><br />
             重复密码:
             <input type="password" name="repwd" /><br />
              手机号:
              <input type="text" name="phone" /><br />
               爱好:
              <input type="checkbox" name="hobby" value="football" />足球
              <input type="checkbox" name="hobby" value="basketball" />篮球
               <input type="checkbox" name="hobby" value="Pingpong" />乒乓球
              <br />
                性别:
                <input type="radio" name="sex" value="male" />男
                <input type="radio" name="sex" value="female" />女<br />
                <input type="submit" value="提交" />
        </form>
    
    
    </body>
    </html>
    复制代码

     

      处理注册信息存入数据库:

    复制代码
    <%@ page language="java" import="java.util.*, java.sql.*" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'deal_register.jsp' starting page</title>
    
    
    </head>
    
    <body>
    
        <%
            // 第一步:获取input的值(也就是用户注册的信息)
            String username = request.getParameter("username");
            String password = request.getParameter("pwd");
            String phoneNumber = request.getParameter("phone");
            long phone = Long.parseLong(phoneNumber);
            // String hobby1 = request.getParameter("hobby");
            String[] hobby = request.getParameterValues("hobby");
            String[] sex = request.getParameterValues("sex");
            String hobbys= "";// "football,basketball,pingpong"
            //hobby.length为3
            for(int i = 0;i < hobby.length; i++) {
                /* if(hobby.length-1 > i) {
                    hobbys +=hobby[i]+",";// 最后一位是,
                } else {
                    hobbys +=hobby[i];
                } */
                
                hobbys +=hobby[i]+",";
            }
            hobbys = hobbys.substring(0,hobbys.length()-1);
            
            //String sex1 = request.getParameter("sex");// 如果是单选或者多选的话,使用request.getParameter()--->on,规定无论是单选还是多选或者下拉使用request.getParameterValues();
        
        
            // 第二步:插入数据,id使用UUID
                //1.导入ojdbc6.jar
                //2.加载驱动(反射)
                Class.forName("oracle.jdbc.driver.OracleDriver");
                //3.获取连接
                Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","scott");
                //4.获取预编译的statement(String sql)
                String sql = "insert into students (id, stu_name, stu_age, stu_pwd, stu_hobby, stu_sex, stu_phone) values(?,?,?,?,?,?,?)";
                PreparedStatement ps = conn.prepareStatement(sql);
                //5.设置参数ps.setxxxx
                ps.setString(1,UUID.randomUUID().toString());
                ps.setString(2, username);
                ps.setInt(3, 32);
                ps.setString(4, password);
                ps.setString(5, hobbys);
                ps.setString(6,sex[0]);
                ps.setLong(7, phone);
                //6.调用executeUpdate();--->返回值为受影响的行数
                int result = ps.executeUpdate();
                //7.判断接收的int类型数据,判断是否大于0(大于0成功,小于0失败)
                if(result > 0) {
                    // 成功
                } else {
                    // 失败
                }
        %>
    
    
    </body>
    </html>
    复制代码

      登录:

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'login.jsp' starting page</title>
    
    
    </head>
    
    <body>
    
        <form action="deal_login.jsp" method="post">
            用户名:
            <input type="text" name="username" />
            <br /> 密码:
            <input type="password" name="pwd" />
            <input type="submit" value="提交" />
        </form>
    
    
    </body>
    </html>
    复制代码

      处理登录,预跳转至主页处理的界面(查询数据库全部数据):

    复制代码
    <%@ page language="java"
        import="java.util.*, java.sql.*, cn.zzsxt.lee.web.entity.*"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'deal_login.jsp' starting page</title>
    
    
    </head>
    
    <body>
    
    
        <%
            String username = request.getParameter("username");
            String password = request.getParameter("pwd");
    
            //1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //2.获取连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
            //3.获取预编译的statement
            String sql = "select * from teacher where name=? and password=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            //4.设置参数
            ps.setString(1, username);
            ps.setString(2, password);
            //5.调用executeQuery();-->返回ResultSet
            ResultSet rs = ps.executeQuery();
            //6.遍历结果集
            Teacher teacher = new Teacher();
            while (rs.next()) {
                teacher.setId(rs.getInt("id"));
                teacher.setUsername(rs.getString("name"));
                teacher.setPassword(rs.getString("password"));
                teacher.setDescription(rs.getString("description"));
            }
            //7.判断是否查询出数据
            if (teacher.getUsername() != null && !"".equals(teacher.getUsername())) {// 把“”放在前面,防止空指针
                // 成功,跳转主页面的处理页面
            //    request.getRequestDispatcher("deal_index.jsp").forward(request, response);// 跳转页面
                request.getRequestDispatcher("frameset_index.jsp").forward(request, response);// 跳转页面
            } else {
                // 失败,跳转404
                //response.sendRedirect("404.jsp");
                request.getRequestDispatcher("404.jsp").forward(request, response);
            }
        %>
    
    
    
    </body>
    </html>
    复制代码

      主页处理界面,预跳转至主页:

    复制代码
    <%@ page language="java"
        import="java.util.*, java.sql.*, cn.zzsxt.lee.web.entity.*"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'deal_index.jsp' starting page</title>
    
    
    </head>
    
    <body>
    
    
        <%
            //1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //2.获取连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
            //3.获取预编译的statement
            String sql = "select * from students";
            PreparedStatement ps = conn.prepareStatement(sql);
            //4.调用executeQuery();-->返回ResultSet
            ResultSet rs = ps.executeQuery();
            //5.遍历结果集
            // 定义一个泛型为Student的List集合
            List<Student> list = new ArrayList<Student>();
            while (rs.next()) {
                Student student = new Student();
                student.setId(rs.getString("id"));
                student.setStuName(rs.getString("stu_name"));
                student.setStuPassword(rs.getString("stu_pwd"));
                list.add(student);
            }
            //6.判断list的长度大于0
            if(list.size() > 0) {
                // 成功,跳转到主页面
                request.setAttribute("list", list);//--->Map.get("key");--->map.put("name",24);Map<String, Object>
                request.getRequestDispatcher("index.jsp").forward(request, response);
            } else {
                // 失败
            }
        %>
    
    
    
    </body>
    </html>
    复制代码

      跳转至主页,显示所有数据,及修改和删除的功能:

    复制代码
    <%@ page language="java" import="java.util.*, cn.zzsxt.lee.web.entity.*"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'index.jsp' starting page</title>
    
    <script type="text/javascript">
    
        function trueDelete(id) {
            if (confirm("您确定要删除数据么?")) {
                window.location.href = "deal_delete.jsp?id=" + id;
            }
        }
    </script>
    
    </head>
    
    <body>
    
    
        <table border="1">
            <thead>
                <tr>
                    <th>学生编号</th>
                    <th>学生姓名</th>
                    <th>学生密码</th>
                    <th>操作</th>
                </tr>
            </thead>
    
            <tbody>
    
                <%
                    List<Student> listStudent = (List<Student>) request.getAttribute("list");
                    for (int i = 0; i < listStudent.size(); i++) {
                        listStudent.get(i).getId();// 获取student对象的id
                %>
                <%-- jsp的注释 --%>
                <tr>
                    <!-- 一个tr代表了一行,说白了就是代表一个student对象 -->
                    <td><%=listStudent.get(i).getId()%></td>
                    <!-- <%--<%= %>--%>输出页面 -->
                    <td><%=listStudent.get(i).getStuName()%></td>
                    <td><%=listStudent.get(i).getStuPassword()%></td>
                    <td><a href="javascript:void(0);"
                        οnclick="trueDelete('<%=listStudent.get(i).getId()%>');">删除</a>
                        <a href="select_by_id.jsp?id=<%=listStudent.get(i).getId()%>">修改</a>    
                    </td>
                    <!-- 删除功能(主键id删除)需要传递一个参数,同样需要操作数据库,需要deal_delete.jsp进行处理 -->
                </tr>
                <%
                    }
                %>
            </tbody>
    
        </table>
    
    
    
    
    </body>
    </html>
    复制代码

      删除功能,删除处理界面,预跳转至主页处理界面(查询删除后还剩的数据,即所有数据)

    复制代码
    <%@ page language="java" import="java.util.*, java.sql.*"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'deal_delete.jsp' starting page</title>
    
    
    </head>
    
    <body>
    
    
        <%
            //所有通过路径传递的参数都要使用request.getParameter()
            String id = request.getParameter("id");
            //1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //2.获取连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
            //3.获取预编译的statement
            String sql = "delete from students where id=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, id);
            int result = ps.executeUpdate();
            if (result > 0) {
                //成功
                request.getRequestDispatcher("deal_index.jsp").forward(request, response);
            } else {
                // 失败
            }
        %>
    
    </body>
    </html>
    复制代码

      修改功能,首先跳转至查询某一行的界面,预跳转至修改界面

    复制代码
    <%@ page language="java"
        import="java.util.*, java.sql.*, cn.zzsxt.lee.web.entity.*"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'select_by_id.jsp' starting page</title>
    
    
    </head>
    
    <body>
    
        <%
            String id = request.getParameter("id");
            // 进行查询(通过id)
            //1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //2.获取连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
            //3.获取预编译的statement
            String sql = "select * from students where id=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, id);
            //4.调用executeQuery();-->返回ResultSet
            ResultSet rs = ps.executeQuery();
            //5.遍历结果集
            Student stu = new Student();
            while (rs.next()) {
                stu.setId(rs.getString("id"));
                stu.setStuName(rs.getString("stu_name"));
                stu.setStuPassword(rs.getString("stu_pwd"));
            }
            if (stu.getId() != null) {
                request.setAttribute("stu", stu);
                request.getRequestDispatcher("update.jsp").forward(request, response);
            } else {
                // 跳转报错页面
            }
        %>
    
    
    
    
    </body>
    </html>
    复制代码

      修改界面,以form表单的形式显示让用户动态修改,预提交至修改处理界面

    复制代码
    <%@ page language="java" import="java.util.*, cn.zzsxt.lee.web.entity.*"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'update.jsp' starting page</title>
    
    
    </head>
    
    <body>
        <%
            Student stu = (Student) request.getAttribute("stu");
        %>
    
        <form action="deal_update.jsp" method="post">
            学生编号:
            <input type="text" value="<%=stu.getId()%>" name="id" readonly="readonly" />
            <br /> 学生姓名:
            <input type="text" value="<%=stu.getStuName()%>" name="username" />
            <br /> 学生密码:
            <input type="text" value="<%=stu.getStuPassword()%>" name="pwd" />
            <br />
            <input type="submit" value="修改" />
        </form>
    
    
    
    </body>
    </html>
    复制代码

      修改界面,修改数据库中的数据,预跳转至主页处理界面(查询修改后的数据,即所有数据)

    复制代码
    <%@ page language="java" import="java.util.*, java.sql.*"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    <title>My JSP 'deal_update.jsp' starting page</title>
    
    
    </head>
    
    
    <body>
    
    
        <%
            String id = request.getParameter("id");
            String username = request.getParameter("username");
            String pwd = request.getParameter("pwd");
    
            //1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //2.获取连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
            //3.获取预编译的statement
            String sql = "update students set stu_name=?, stu_pwd=? where id=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, pwd);
            ps.setString(3, id);
            int result = ps.executeUpdate();
            if (result > 0) {
                response.sendRedirect("deal_index.jsp");
                return;
                //request.getRequestDispatcher("deal_index.jsp").forward(request, response);//forward标识了跳转页面的规则,携带着request和response一起跳转页面,所以请求转发才可以传递参数
                //System.out.println("我是转发之后的代码,我被执行了");
                // 如果使用两个response或者request的情况下,就会报错Cannot call sendRedirect() after the response has been committed
                // 但是重定向直接报500,中断程序,请求转发不会中断程序,可以继续运行
                //response.sendRedirect("404.jsp");
            } else {
                //跳转错误页面
                response.sendRedirect("404.jsp");
                return;
            }
        %>
    
    
    </body>
    </html>
    复制代码

     

     
    分类: Java,Java EE,JSP

    转载于:https://www.cnblogs.com/yinyue-123/p/8659671.html

    展开全文
  • Java MVC 增删改查 实例

    2015-09-24 14:56:00
    需求:实现增加新部门的功能,对应数据库表示Oracle的dept表 一、Java MVC 实现: 1、视图层(V):注册部门 deptAdd.jsp 在注册新部门页面只需输入“部门名称”和“城市”两个字段。部门编号deptno的逻辑是...

    需求:实现增加新部门的功能,对应数据库表示Oracle的dept表

    一、Java MVC 增

    实现:

    1、视图层(V):注册部门 deptAdd.jsp

         在注册新部门页面只需输入“部门名称”和“城市”两个字段。部门编号deptno的逻辑是保存新的部门信息的时候在原有的部门编号的基础上去最大值加10,返回值是最新的部门编号。

    2、控制层(C):DeptController.java

         deptAdd.jsp中hidden callTp 为 deptAdd,在控制端接收后处理

         处理逻辑是先调用service层,获取新的deptno,然后组成完成的DeptBean后重新调用service

    else if (callTp.equals("deptAdd")) {
                String dname = request.getParameter("dnameTxt");
                String loc = request.getParameter("locTxt");
                
                int deptno = ds.getNextDetpno();
                
                DeptBean dept = new DeptBean();
                dept.setDeptno(deptno);
                dept.setDname(dname);
                dept.setLoc(loc);
                
                int addInt = ds.deptAdd(dept);
                if (addInt == 1) {
                    request.setAttribute("addResultMsg", "添加成功!");
                } else {
                    request.setAttribute("addResultMsg", "添加失败!");
                }
                request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
            }

    3、模型层(M):DeptBean.java、DeptService.java

         获取下一个部门编号(已有部门最大编号+10)

        // 获取下一个deptno
        public int getNextDetpno() {
            int nextDeptno = 0;
    
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("SELECT MAX(DEPTNO) + 10   AS DEPTNO  \n");
            sqlBf.append("FROM   DEPT                          \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    nextDeptno = rs.getInt("DEPTNO");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(rs, pstmt, conn);
            }
            
            return nextDeptno;
        }

         保存DeptBean

        // 增加一条dept数据
        public int deptAdd(DeptBean dept) {
            int insertInt = 0;
    
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("INSERT INTO DEPT(DEPTNO, DNAME, LOC)        \n");
            sqlBf.append("          VALUES(?                          \n");
            sqlBf.append("               , ?                          \n");
            sqlBf.append("               , ?)                         \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setInt(idx++, dept.getDeptno());
                pstmt.setString(idx++, dept.getDname());
                pstmt.setString(idx++, dept.getLoc());
                
                insertInt = pstmt.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(rs, pstmt, conn);
            }
            
            return insertInt;
        }

    二、Java MVC 删

    1、视图层(V):注册部门 deptList.jsp

        调用控制器时callTp=deptDelete和传输要删除的deptno。

    <td><a href="/web01/deptController?callTp=deptDelete&deptno=${dept.deptno }">删除</a></td>

    2、控制层(C):DeptController.java  

    else if (callTp.equals("deptDelete")) {
                int deleteInt = ds.deptDelete(Integer.parseInt(request.getParameter("deptno")));
                
                if (deleteInt == 1) {
                    request.setAttribute("deleteResultMsg", "删除成功!");
                } else {
                    request.setAttribute("deleteResultMsg", "删除失败!");
                }
                request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
            } 

    3、模型层(M):DeptBean.java、DeptService.java

        // 删除部门一条记录
        public int deptDelete(int deptno) {
            int deleteResulInt = 0;
            
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("DELETE FROM DEPT           \n");
            sqlBf.append("WHERE DEPTNO = ?           \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setInt(idx++, deptno);
                
                deleteResulInt = pstmt.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(null, pstmt, conn);
            }
            
            return deleteResulInt;
        }

    三、Java MVC 改

    1、视图层(V):注册部门 deptList.jsp、deptUpdate.jsp

         调用控制器时callTp=deptUpdate和传输要删除的deptno。

    <td><a href="/web01/deptController?callTp=deptUpdate&deptno=${dept.deptno }">更改</a></td> 

    2、控制层(C):DeptController.java

         调用控制器时callTp=deptUpdate和传输要删除的deptno,利用deptno重新查询dept数据,然后跳转到deptUpdate.jsp页面。

         在deptUpdate.jsp页面中修改“部门名称”和“城市”字段后点击保存,往控制器传输callTp=deptSave。

    else if (callTp.equals("deptUpdate")) {
                deptBean.setDeptno(Integer.parseInt(request.getParameter("deptno")));
                deptBean = ds.deptById(deptBean.getDeptno());
    
                request.setAttribute("deptBean", deptBean);
                request.getRequestDispatcher("/view/deptUpdate.jsp").forward(request, response);            
            } else if (callTp.equals("deptSave")) {
                deptBean.setDname(request.getParameter("dnameTxt"));
                deptBean.setLoc(request.getParameter("locTxt"));
                deptBean.setDeptno(Integer.parseInt(request.getParameter("deptno")));
                
                int updateInt = ds.deptSave(deptBean);
                if (updateInt == 1) {
                    request.setAttribute("updateResultMsg", "更新成功!");
                } else {
                    request.setAttribute("updateResultMsg", "更新失败!");
                }
                
                request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);                
            }

    3、模型层(M):DeptBean.java、DeptService.java

         利用deptno查找dept数据,返回给deptUpdate.jsp页面。

        // 利用deptno查询单条部门信息
        public DeptBean deptById(int deptno) {
            DeptBean dept = new DeptBean();
            
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("SELECT   DEPTNO                \n");
            sqlBf.append("       , DNAME                 \n");
            sqlBf.append("       , LOC                   \n");
            sqlBf.append("FROM     DEPT                  \n");
            sqlBf.append("WHERE    DEPTNO = ?            \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setInt(idx++, deptno);
                
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    dept.setDeptno(rs.getInt("DEPTNO"));
                    dept.setDname(rs.getString("DNAME"));
                    dept.setLoc(rs.getString("LOC"));
                }
                
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(rs, pstmt, conn);
            }
            
            return dept;
        }

         部门信息修改后进行保存。

        // 更新dept信息
        public int deptSave(DeptBean deptBean) {
            int updateResulInt = 0;
            
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("UPDATE DEPT SET DNAME = ?          \n");
            sqlBf.append("              , LOC = ?            \n");
            sqlBf.append("WHERE DEPTNO = ?                   \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setString(idx++, deptBean.getDname());
                pstmt.setString(idx++, deptBean.getLoc());
                pstmt.setInt(idx++, deptBean.getDeptno());
                
                updateResulInt = pstmt.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(null, pstmt, conn);
            }
            
            return updateResulInt;
        }

    四、Java MVC 查

    1、视图层(V):注册部门 deptList.jsp

         调用控制器时传输callTp=deptList和相应条件值

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>
    <link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <%@ include file="top.jsp" %>
    <form action="/web01/deptController" method="get">
    部门名称:<input type="text" name="dnameTxt">
    城市:<input type="text" name="locTxt">
    <input type="submit" value="Search">
    <input type="hidden" name="callTp" value="deptList">
    <br/>
    <table>
        <tr>
            <th>部门编号</th>
            <th>部门名称</th>
            <th>地点</th>
            <th>更新操作</th>    
            <th>删除操作</th>
        </tr>
        <c:forEach items="${requestScope.deptBeanList}" var="dept">
        <tr>
            <td><c:out value="${dept.deptno }" default=" "></c:out></td>
             <td><c:out value="${dept.dname }" default=" "></c:out></td>
            <td><c:out value="${dept.loc }" default=" "></c:out></td>
            <td><a href="/web01/deptController?callTp=deptUpdate&deptno=${dept.deptno }">更改</a></td>
            <td><a href="/web01/deptController?callTp=deptDelete&deptno=${dept.deptno }">删除</a></td>
        </tr>
        </c:forEach>
    </table>
    <em style="color: red"><c:out value="${requestScope.updateResultMsg }"></c:out></em>
    <em style="color: red"><c:out value="${requestScope.deleteResultMsg }"></c:out></em>
    <em style="color: red"><c:out value="${requestScope.addResultMsg }"></c:out></em>
    </form>
    <%@ include file="bottom.jsp" %>
    </body>
    </html>

    2、控制层(C):DeptController.java

    if (callTp.equals("deptList")) {
                deptBean.setDname(request.getParameter("dnameTxt"));
                deptBean.setLoc(request.getParameter("locTxt"));
                ArrayList<DeptBean> deptBeanList = ds.deptList(deptBean);            
                
                request.setAttribute("deptBeanList", deptBeanList);
                request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
            }

    3、模型层(M):DeptBean.java、DeptService.java

        // 获取dept list
        public ArrayList<DeptBean> deptList(DeptBean db){
            
            ArrayList<DeptBean> deptList = new ArrayList<DeptBean>();
            
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("SELECT   DEPTNO                \n");
            sqlBf.append("       , DNAME                 \n");
            sqlBf.append("       , LOC                   \n");
            sqlBf.append("FROM     DEPT                  \n");
            sqlBf.append("WHERE    DNAME LIKE UPPER(?) || '%'   \n");
            sqlBf.append("AND      LOC LIKE UPPER(?) || '%'     \n");
            sqlBf.append("ORDER BY DEPTNO                \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setString(idx++, db.getDname());
                pstmt.setString(idx++, db.getLoc());
                
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    DeptBean dept = new DeptBean();
                    
                    dept.setDeptno(rs.getInt("DEPTNO"));
                    dept.setDname(rs.getString("DNAME"));
                    dept.setLoc(rs.getString("LOC"));
                    
                    deptList.add(dept);
                }
                
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(rs, pstmt, conn);
            }
            
            return deptList;
        }

     

     

    全部代码如下:

     

    主页面:index.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>index page</title>
    <link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <%@ include file="/view/top.jsp" %>
    <ul>
        <li>员工管理
            <ul>
                <li><a href="/web01/empController">员工查询</a></li>
                <li>注册员工</li>
            </ul>
        </li>
        <li>部门管理
            <ul>
                <li><a href="/web01/deptController?callTp=deptList">部门查询</a></li>
                <li><a href="/web01/view/deptAdd.jsp">注册部门</a></li>
            </ul>
        </li>    
        <li>系统管理
            <ul>
                <li><a href="/web01/requestInfoController?callTp=requestInfoPageList&now_page_num=1">访问日志查询</a></li>
            </ul>
        </li>
    </ul>
    </body>
    </html>

     部门查询:deptList.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>
    <link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <%@ include file="top.jsp" %>
    <form action="/web01/deptController" method="get">
    部门名称:<input type="text" name="dnameTxt">
    城市:<input type="text" name="locTxt">
    <input type="submit" value="Search">
    <input type="hidden" name="callTp" value="deptList">
    <br/>
    <table>
        <tr>
            <th>部门编号</th>
            <th>部门名称</th>
            <th>地点</th>
            <th>更新操作</th>    
            <th>删除操作</th>
        </tr>
        <c:forEach items="${requestScope.deptBeanList}" var="dept">
        <tr>
            <td><c:out value="${dept.deptno }" default=" "></c:out></td>
             <td><c:out value="${dept.dname }" default=" "></c:out></td>
            <td><c:out value="${dept.loc }" default=" "></c:out></td>
            <td><a href="/web01/deptController?callTp=deptUpdate&deptno=${dept.deptno }">更改</a></td>
            <td><a href="/web01/deptController?callTp=deptDelete&deptno=${dept.deptno }">删除</a></td>        
        </tr>
        </c:forEach>
    </table>
    <em style="color: red"><c:out value="${requestScope.updateResultMsg }"></c:out></em>
    <em style="color: red"><c:out value="${requestScope.deleteResultMsg }"></c:out></em>
    <em style="color: red"><c:out value="${requestScope.addResultMsg }"></c:out></em>
    </form>
    <%@ include file="bottom.jsp" %>
    </body>
    </html>

     

    部门更新:deptUpdate.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>
    <link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <%@ include file="top.jsp" %>
    <form action="/web01/deptController" method="get">
    部门编号:<input type="text" disabled="disabled" value="${requestScope.deptBean.deptno}"><br>
    部门名称:<input type="text" name="dnameTxt" value="${requestScope.deptBean.dname}"><br>
    城市:<input type="text" name="locTxt" value="${requestScope.deptBean.loc}"><br>
    <input type="submit" value="Save">
    <input type="hidden" name="callTp" value="deptSave">
    <input type="hidden" name="deptno" value="${requestScope.deptBean.deptno}"">
    <br/>
    </form>
    <%@ include file="bottom.jsp" %>
    </body>
    </html>

     

    增加部门:deptAdd.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>
    <link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <%@ include file="top.jsp" %>
    <form action="/web01/deptController" method="get">
    部门名称:<input type="text" name="dnameTxt" value="" maxlength="14"><br>
    城市:<input type="text" name="locTxt" value="" maxlength="13"><br>
    <input type="submit" value="Add">
    <input type="hidden" name="callTp" value="deptAdd">
    <br/>
    </form>
    <%@ include file="bottom.jsp" %>
    </body>
    </html>

     

    部门的控制器:DeptController.java

    package com.test.biz.controller;
    
    import java.io.IOException;
    import java.util.ArrayList;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.test.biz.bean.DeptBean;
    import com.test.biz.service.DeptService;
    import com.test.system.service.RequestInfoService;
    
    /**
     * Servlet implementation class deptController
     */
    @WebServlet("/DeptController")
    public class DeptController extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public DeptController() {
            super();
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            RequestInfoService ris = new RequestInfoService();
            ris.saveRequestInfo(request);
            
            DeptService ds = new DeptService();
            DeptBean deptBean = new DeptBean();
            
            String callTp = request.getParameter("callTp");
            System.out.println("----callTp : "+callTp);
            if (callTp.equals("deptList")) {
                deptBean.setDname(request.getParameter("dnameTxt"));
                deptBean.setLoc(request.getParameter("locTxt"));
                ArrayList<DeptBean> deptBeanList = ds.deptList(deptBean);            
                
                request.setAttribute("deptBeanList", deptBeanList);
                request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
            } else if (callTp.equals("deptUpdate")) {
                deptBean.setDeptno(Integer.parseInt(request.getParameter("deptno")));
                deptBean = ds.deptById(deptBean.getDeptno());
    
                request.setAttribute("deptBean", deptBean);
                request.getRequestDispatcher("/view/deptUpdate.jsp").forward(request, response);            
            } else if (callTp.equals("deptSave")) {
                deptBean.setDname(request.getParameter("dnameTxt"));
                deptBean.setLoc(request.getParameter("locTxt"));
                
                deptBean.setDeptno(Integer.parseInt(request.getParameter("deptno")));
                
                int updateInt = ds.deptSave(deptBean);
                if (updateInt == 1) {
                    request.setAttribute("updateResultMsg", "更新成功!");
                } else {
                    request.setAttribute("updateResultMsg", "更新失败!");
                }
                
                request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);                
            } else if (callTp.equals("deptDelete")) {
                int deleteInt = ds.deptDelete(Integer.parseInt(request.getParameter("deptno")));
                
                if (deleteInt == 1) {
                    request.setAttribute("deleteResultMsg", "删除成功!");
                } else {
                    request.setAttribute("deleteResultMsg", "删除失败!");
                }
                request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
            } else if (callTp.equals("deptAdd")) {
                String dname = request.getParameter("dnameTxt");
                String loc = request.getParameter("locTxt");
                
                int deptno = ds.getNextDetpno();
                
                DeptBean dept = new DeptBean();
                dept.setDeptno(deptno);
                dept.setDname(dname);
                dept.setLoc(loc);
                
                int addInt = ds.deptAdd(dept);
                if (addInt == 1) {
                    request.setAttribute("addResultMsg", "添加成功!");
                } else {
                    request.setAttribute("addResultMsg", "添加失败!");
                }
                request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
            }
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    
    }

    部门Bean:DeptBean.java

    package com.test.biz.bean;
    
    public class DeptBean {
        private int deptno;
        private String dname;
        private String loc;
    
        public int getDeptno() {
            return deptno;
        }
    
        public void setDeptno(int deptno) {
            this.deptno = deptno;
        }
    
        public String getDname() {
            return dname;
        }
    
        public void setDname(String dname) {
            this.dname = dname;
        }
    
        public String getLoc() {
            return loc;
        }
    
        public void setLoc(String loc) {
            this.loc = loc;
        }
    }

    部门的服务层:DeptService.java

    package com.test.biz.service;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    
    import com.test.biz.bean.DeptBean;
    import com.test.common.dao.BaseDao;
    
    public class DeptService {
        
        private int idx = 1;
    
        private Connection conn = null;
        private PreparedStatement pstmt = null;
        private ResultSet rs = null;
    
        // 获取dept list
        public ArrayList<DeptBean> deptList(DeptBean db){
            
            ArrayList<DeptBean> deptList = new ArrayList<DeptBean>();
            
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("SELECT   DEPTNO                \n");
            sqlBf.append("       , DNAME                 \n");
            sqlBf.append("       , LOC                   \n");
            sqlBf.append("FROM     DEPT                  \n");
            sqlBf.append("WHERE    DNAME LIKE UPPER(?) || '%'   \n");
            sqlBf.append("AND      LOC LIKE UPPER(?) || '%'     \n");
            sqlBf.append("ORDER BY DEPTNO                \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setString(idx++, db.getDname());
                pstmt.setString(idx++, db.getLoc());
                
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    DeptBean dept = new DeptBean();
                    
                    dept.setDeptno(rs.getInt("DEPTNO"));
                    dept.setDname(rs.getString("DNAME"));
                    dept.setLoc(rs.getString("LOC"));
                    
                    deptList.add(dept);
                }
                
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(rs, pstmt, conn);
            }
            
            return deptList;
        }
    
        // 利用deptno查询单条部门信息
        public DeptBean deptById(int deptno) {
            DeptBean dept = new DeptBean();
            
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("SELECT   DEPTNO                \n");
            sqlBf.append("       , DNAME                 \n");
            sqlBf.append("       , LOC                   \n");
            sqlBf.append("FROM     DEPT                  \n");
            sqlBf.append("WHERE    DEPTNO = ?            \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setInt(idx++, deptno);
                
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    dept.setDeptno(rs.getInt("DEPTNO"));
                    dept.setDname(rs.getString("DNAME"));
                    dept.setLoc(rs.getString("LOC"));
                }
                
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(rs, pstmt, conn);
            }
            
            return dept;
        }
    
        // 更新dept信息
        public int deptSave(DeptBean deptBean) {
            int updateResulInt = 0;
            
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("UPDATE DEPT SET DNAME = ?          \n");
            sqlBf.append("              , LOC = ?            \n");
            sqlBf.append("WHERE DEPTNO = ?                   \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setString(idx++, deptBean.getDname());
                pstmt.setString(idx++, deptBean.getLoc());
                pstmt.setInt(idx++, deptBean.getDeptno());
                
                updateResulInt = pstmt.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(null, pstmt, conn);
            }
            
            return updateResulInt;
        }
    
        // 删除部门一条记录
        public int deptDelete(int deptno) {
            int deleteResulInt = 0;
            
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("DELETE FROM DEPT           \n");
            sqlBf.append("WHERE DEPTNO = ?           \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setInt(idx++, deptno);
                
                deleteResulInt = pstmt.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(null, pstmt, conn);
            }
            
            return deleteResulInt;
        }
    
        // 获取下一个deptno
        public int getNextDetpno() {
            int nextDeptno = 0;
    
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("SELECT MAX(DEPTNO) + 10   AS DEPTNO  \n");
            sqlBf.append("FROM   DEPT                          \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    nextDeptno = rs.getInt("DEPTNO");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(rs, pstmt, conn);
            }
            
            return nextDeptno;
        }
    
        // 增加一条dept数据
        public int deptAdd(DeptBean dept) {
            int insertInt = 0;
    
            BaseDao baseDao = new BaseDao();
            try {
                conn = baseDao.dbConnection();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            
            StringBuffer sqlBf = new StringBuffer();
            sqlBf.setLength(0);
            
            sqlBf.append("INSERT INTO DEPT(DEPTNO, DNAME, LOC)        \n");
            sqlBf.append("          VALUES(?                          \n");
            sqlBf.append("               , ?                          \n");
            sqlBf.append("               , ?)                         \n");
            
            try {
                pstmt = conn.prepareStatement(sqlBf.toString());
                idx = 1;
                pstmt.setInt(idx++, dept.getDeptno());
                pstmt.setString(idx++, dept.getDname());
                pstmt.setString(idx++, dept.getLoc());
                
                insertInt = pstmt.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                baseDao.dbDisconnection(rs, pstmt, conn);
            }
            
            return insertInt;
        }
    }

     公用BaseDao.java

    package com.test.common.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    
    public class BaseDao {
        Connection conn = null;
    
        public BaseDao() {
        }
        
        public Connection dbConnection() throws SQLException{
            try {
                Context sourceCtx  = new InitialContext();
                DataSource ds = (DataSource) sourceCtx.lookup("java:comp/env/jdbc/orcl");
                conn = ds.getConnection();
                System.out.println("----> Connection Success!");
            } catch (NamingException e) {
                e.printStackTrace();
            }
            
            return conn;
        }
        
        public void dbDisconnection() throws SQLException{
            conn.close();
            System.out.println("----> Connection End!");
        }    
        
        public void dbDisconnection(ResultSet rs, PreparedStatement pstmt, Connection conn) {
            if (rs != null) {
                try {
                    rs.close();
                    System.out.println("----> ResultSet End!");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if (pstmt != null) {
                try {
                    pstmt.close();
                    System.out.println("----> PreparedStatement End!");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if (conn != null) {
                try {
                    conn.close();
                    System.out.println("----> Connection End!");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

     

    转载于:https://www.cnblogs.com/seabird1979/p/4835360.html

    展开全文
  • 文件为项目源码,包含数据库,可以导入eclipse直接运行 地址为:http://127.0.0.1:8081/spbdemo/opinions.jsp
  • 下载地址:http://down.0379zd.com/news/show/15002.htm packagedao;/*数据库连接基类*/importjava.sql.*;importjava.util.List;publicclassBaseDao{protectedConnectionconn=null;protectedResultSetrs=...

    下载地址:http://down.0379zd.com/news/show/15002.htm

    package dao;
    /*数据库连接基类*/
    import java.sql.*;
    import java.util.List;
    public class BaseDao {
        
    protected Connection conn = null;
        
    protected ResultSet rs = null;
        
    protected PreparedStatement pstmt =null;
        
    //驱动路径
        private final String drive ="sun.jdbc.odbc.JdbcOdbcDriver";
        
    //url
        private static String url ="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=";
        
    //得到服务器端的url
        public static void getRealPath(String realPath){
            url
    =url+realPath;
        }
        
    /**
         * 得到连接对象
         * 
    @param realPath 在服务器端数据库的真是路径
         * 
    @return 连接对象
         
    */
        
    protected Connection getConn (){        
            
            
    try {
                Class.forName(drive);
                 conn 
    = DriverManager.getConnection(url);
            } 
    catch (ClassNotFoundException e) {
                
    // TODO Auto-generated catch block
                e.printStackTrace();
            } 
    catch (SQLException e) {
                
    // TODO Auto-generated catch block
                e.printStackTrace();
            }        
            
    return conn;
        }
        
    /**
         * 关闭连接
         *
         
    */
        
    protected void closeAll(){
            
    if(conn !=null){
                
    try {
                    conn.close();
                } 
    catch (SQLException e) {
                    
    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
    if(rs!=null){
                
    try {
                    rs.close();
                } 
    catch (SQLException e) {
                    
    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
    if(pstmt!=null){
                
    try {
                    pstmt.close();
                } 
    catch (SQLException e) {
                    
    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
    /**
         * 通用修改方法
         * 
    @param sql 
         * 
    @param paramList
         * 
    @return 修改的结果
         
    */
        
    protected int currencyUpdate(String sql,List paramList){
            
    int  result = 0;
            conn 
    = getConn();
            
    try {
                pstmt 
    = conn.prepareStatement(sql);
                result 
    = pstmt.executeUpdate();
            } 
    catch (SQLException e) {
                
    // TODO Auto-generated catch block
                e.printStackTrace();
            }        
            
    return result;
        }
    }

    转载于:https://www.cnblogs.com/greatverve/archive/2009/06/28/1512723.html

    展开全文
  • 用纯jsp+javabean技术开发的小系统,只包含功能,所用到的数据库为mysql。 备注比较详细,对于jsp刚入门的新手很适合
  • 适合刚学ssm框架的新手同学,增删改查都有,数据库用的mysql,也可以访问一下http://whutshy.vicp.net/StudentManagerSys/index.jsp来看看效果,前端不太熟练,凑合着看吧
  • 学生信息管理1.0 涉及的知识点:三层架构理论 ...应用实例:运用三层架构实现对学生信息得增删改查 项目目录结构图 1.需要用到的数据库与数据表 create database test; use test; drop table if exists student
  • 做一个简单的学生信息管理系统,实现增删改查的功能 # StudentDao package com.hdxy.Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql....
  • 主要介绍了jsp+mysql数据库操作常用方法,以实例形式较为详细的总结了JSP操作mysql数据库实现基本的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
  • 本人亲自用jsp的方式开发的一个完整的增删改查的小系统,遵循MVC架构,并且实现了模糊查询和用displaytag进行了分页,对输入垃圾字符进行了过滤处理,包含完整的代码注释,并且自带了Mysql的数据库脚本,很适合新手...
  • springMvc 入门学习(自动生成 springmvc 单表 两...自动生产web 增删查修改 springmvc+mybatis springmvc mybatis小实例 自动生成 java 类 和 mybatis sql 语句 和jsp 页面 ,属于自动生产 实例 增删查改 含简单数据库
  • (3 实现数据库访问和业务逻辑的结合体DAO类:StudentDAO类,该DAO类的实例对象应负责处理数据库记录的基本操作(增删改查),即完成对CRUD操作的封装。 (4)实现业务逻辑处理的接口:IStudentDAO。 ...
  • jsp+servlet+jdbc实现增删改查实例,下载后可根据你用的对应的数据库修改properties文件里的数据库配置,建一张对应的表就可以部署运行,写的比较简单易懂,适合刚进入行业的新手
  • jsp之javaBean操作数据库添加数据

    千次阅读 2017-03-15 22:55:26
    1.思想就是在数据库 中每步中都需要连接到数据库,为了简化代码。使用javaBean 分别把用户类,连接类,操作类 打包 2 login代码: 用户名: 密 码: 用户类型: 管理员 普通用户 dolign代码:...
  • 我学JSP的三个实例

    2011-04-26 08:48:17
    我现在正在学习jsp,这是我做的三个实现数据库操作的实例!分别实现增删改查!高手勿下,菜鸟请求相互学习!
  • 一个jsp做的分页完整实例,包含增删改查,并且增加了分页实现,用到非常流行的分页插件displaytag,插件的配置代码当中有详细的备注说明,数据库为mysql
  • 可当做一个简单的项目实例,包含数据库文件,有基本的增删改查,对于初学者来说简单易懂!
  • 利用jsp+javabean+Servlet模拟一个用户登陆,实现对数据库增删改查。 1,创建数据库 我使用的数据库是MySQL,创建一个Iuser表,具体如下 2,创建一个javabean类,对表中的3个属性进行封装 User.Java ...
  • 一个简单的MVC实例

    千次阅读 2016-04-28 08:48:11
    利用jsp+javabean+Servlet模拟一个用户登陆,实现对数据库增删改查。 1,创建数据库 我使用的数据库是MySql,创建一个Iuser表,具体如下   2,创建一个javabean类,对表中的3个属性进行封装 User.java ...
  • JSP学生信息管理系统

    2021-01-20 14:18:40
    * 负责学生信息的所有数据库操作,增删改查 */ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; impor

空空如也

空空如也

1 2 3 4
收藏数 66
精华内容 26
关键字:

jsp数据库增删改查实例