精华内容
下载资源
问答
  • jsp servlet 增删改查

    2013-01-07 12:12:57
    用基本的jspservlet编写的一个增删改查项目。
  • jsp servlet 增删改查 例子

    热门讨论 2012-07-20 09:53:40
    jsp+servlet增删改查 jsp servlet 增删改查 例子
  • JSP/Servlet增删改查

    2020-09-03 14:58:48
    这是一套简单的JSP/Servlet/mysql数据库增删改查代码,可以用来参考.................................................
  • jsp+servlet增删改查分页显示 项目中有个info.doc照着里面的说明建表跟序列
  • 采用简单的MVC设计模式,M(模型层) -> Address.java 里面包含id,name,street,city,state,zip 等相关属性和set,get方法 V(视图层) -> 主要指... C(控制层) -> 这里只用一个servlet实现其增删改查(简单明了,方便理解)
  • jspservlet 增删改查

    2008-11-27 14:32:41
    这是使用jspservlet写的一个比较实用的增删改查
  • jsp &servlet增删改查

    2016-08-09 18:13:36
    数据自己建,很简单的表。用的mysql。
  • jsp+servlet开发一个链接管理小项目,前台显示层用jsp实现,逻辑层用servlet实现,后台数据库采用mysql数据库,有实体表。适合web新手开发,根据实例能够清楚了解三层之间的关系及应用方法。另外把lib包也上传了,...
  • servlet+jsp增删改查

    2018-07-30 10:45:49
    myeclipes+servlet+jsp增删改查文件 myeclipes+servlet+jsp增删改查文件 myeclipes+servlet+jsp增删改查文件
  • jsp+servlet增删改查

    2018-08-07 20:58:00
    import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ceet.ac....

    1:首先根据数据库字段建立实体类

    package ceet.ac.cn.model;
    //数据封装类
    public class Admin {  
    
        private int id;
        private String username;
        private String userpwd;
    
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getUserpwd() {
            return userpwd;
        }
        public void setUserpwd(String userpwd) {
            this.userpwd = userpwd;
        }
    
    }

    2:建立数据库连接类

    package ceet.ac.cn.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DbHelper {
         private static String url = "jdbc:mysql://localhost:3306/admin";  //数据库地址
            private static String userName = "root";  //数据库用户名
            private static String passWord = "359129127";  //数据库密码
            private static Connection conn = null;
    
            private DbHelper(){
    
            }
    
            public static Connection getConnection(){
                if(null == conn){
                    try {
                        Class.forName("com.mysql.jdbc.Driver");
                        conn = DriverManager.getConnection(url, userName, passWord);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return conn;
            }
    
            public static void main(String[] args) {  //测试数据库是否连通
                System.err.println(getConnection());
            }
    }
    


    3:建立dao层和dao的实现层(daoImple)----这里把dao层和实现层写在一起

    package ceet.ac.cn.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import ceet.ac.cn.model.Admin;
    
    public class AdminDao {
    	 public List<Admin> getAllAdmin(){
    		 	//查询所有信息
    	        List<Admin> list = new ArrayList<Admin>();  //创建集合
    	        Connection conn = DbHelper.getConnection();
    	        String sql  = "select * from admin";  //SQL查询语句
    	        try {
    	            PreparedStatement pst = conn.prepareStatement(sql);
    	            ResultSet rst = pst.executeQuery();
    	            while (rst.next()) {
    	                Admin admin = new Admin();
    	                admin.setId(rst.getInt("id"));  //得到ID
    	                admin.setUsername(rst.getString("username"));
    	                admin.setUserpwd(rst.getString("userpwd"));
    	                list.add(admin);
    	            }
    	            rst.close();  //关闭
    	            pst.close();  //关闭
    	        } catch (SQLException e) {
    	            e.printStackTrace();  //抛出异常
    	        }
    	        return list;  //返回一个集合
    	    }
    	 	//添加信息
    	    public boolean addAdmin(Admin admin){  
    	        String sql = "INSERT INTO `admin`(`id`,`username`,`userpwd`) VALUES (?,?,?)";  //添加的SQL语句
    	        Connection conn = DbHelper.getConnection();
    	        try {
    	            PreparedStatement pst = conn.prepareStatement(sql);
    	            pst.setInt(1, admin.getId());
    	            pst.setString(2, admin.getUsername());
    	            pst.setString(3, admin.getUserpwd());
    	            int count = pst.executeUpdate();
    	            pst.close();
    	            return count>0?true:false;  //是否添加的判断
    	        } catch (SQLException e) {
    	            e.printStackTrace();
    	        }
    	        return false;
    	    }
    	    //修改
    	    public boolean updateAdmin(Admin admin){ 
    	        String sql = "UPDATE `admin` SET `username`=?,`userpwd`=? WHERE `id` = ?";  //修改的SQL语句,根据ID修改
    	        Connection conn = DbHelper.getConnection();
    	        try {
    	            PreparedStatement pst = conn.prepareStatement(sql);
    	            pst.setString(1, admin.getUsername());
    	            pst.setString(2, admin.getUserpwd());
    	            pst.setInt(3, admin.getId());  //根据的ID
    	            int count = pst.executeUpdate();
    	            pst.close();  //关闭
    	            return count>0?true:false;  //是否修改的判断
    	        } catch (SQLException e) {
    	            e.printStackTrace();
    	        }
    	        return false;
    	    }
    	    //删除
    	    public boolean deleteAdmin(int id){
    	        String sql = "delete from admin where id = ?";  //删除的SQL语句,根据ID删除
    	        Connection conn = DbHelper.getConnection();
    	        try {
    	            PreparedStatement pst = conn.prepareStatement(sql);
    	            pst.setInt(1, id);
    	            int count = pst.executeUpdate();
    	            pst.close();
    	            return count>0?true:false;  //是否删除的判断
    	        } catch (SQLException e) {
    	            e.printStackTrace();
    	        }
    	        return false;
    	    }
    	    //根据ID进行查询
    	    public Admin selectAdminById(int id){
    	        Connection conn = DbHelper.getConnection();
    	        String sql  = "select * from admin where id = "+id;
    	        Admin admin = null;
    	        try {
    	            PreparedStatement pst = conn.prepareStatement(sql);
    	            ResultSet rst = pst.executeQuery();
    	            while (rst.next()) {
    	                admin = new Admin();
    	                admin.setId(rst.getInt("id"));
    	                admin.setUsername(rst.getString("username"));
    	                admin.setUserpwd(rst.getString("userpwd"));
    	            }
    	            rst.close();
    	            pst.close();
    	        } catch (SQLException e) {
    	            e.printStackTrace();
    	        }
    	        return admin;  //返回
    	    }
    }
    

    4:建立servlet作为控制层

        a:建立添加数据的servlet控制层

    package ceet.ac.cn.servlet;
    
    import java.io.IOException;
    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 ceet.ac.cn.dao.AdminDao;
    import ceet.ac.cn.model.Admin;
    
    @WebServlet("/AddServlet")
    public class AddServlet extends HttpServlet {
    	 //添加数据
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            this.doPost(req, resp);
        }
    
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            String username = req.getParameter("username");
            String userpwd = req.getParameter("userpwd");
            Admin admin = new Admin();
            //转值,中文需要转换为utf-8
            admin.setUsername(new String(username.getBytes("ISO-8859-1"),"UTF-8"));
            admin.setUserpwd(new String(userpwd.getBytes("ISO-8859-1"),"UTF-8"));
            AdminDao dao = new AdminDao();
            dao.addAdmin(admin);
            req.getRequestDispatcher("ShowServlet").forward(req, resp);
        }
    }
    

        b:建立删除数据servlet控制层

    package ceet.ac.cn.servlet;
    
    import java.io.IOException;
    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 ceet.ac.cn.dao.AdminDao;
    
    /**
     * Servlet implementation class DeleteServlet
     */
    @WebServlet("/DeleteServlet")
    public class DeleteServlet extends HttpServlet {
    	//删除数据
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            this.doPost(req, resp);
        }
    
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            String idStr = req.getParameter("id");  //删除数据的ID,根据ID删除
            if(idStr != null && !idStr.equals("")){
                int id = Integer.valueOf(idStr);
                AdminDao dao = new AdminDao();
                dao.deleteAdmin(id);
            }
            req.getRequestDispatcher("ShowServlet").forward(req, resp);
        }
    }
    

        c:建立查询所有数据servlet控制层

    package ceet.ac.cn.servlet;
    
    import java.io.IOException;
    import java.util.List;
    
    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 ceet.ac.cn.dao.AdminDao;
    import ceet.ac.cn.model.Admin;
    
    /**
     * Servlet implementation class ShowServlet
     */
    @WebServlet("/ShowServlet")
    public class ShowServlet extends HttpServlet {
    	//显示全部数据
    
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            this.doPost(req, resp);
        }
    
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            AdminDao dao = new AdminDao();
            List<Admin> list = dao.getAllAdmin();
            req.setAttribute("list", list);
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }
    }
    

        d:建立修改数据servlet控制层

    package ceet.ac.cn.servlet;
    
    import java.io.IOException;
    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 ceet.ac.cn.dao.AdminDao;
    import ceet.ac.cn.model.Admin;
    
    /**
     * Servlet implementation class UpdateServlet
     */
    @WebServlet("/UpdateServlet")
    public class UpdateServlet extends HttpServlet {
    	//修改
        private static final long serialVersionUID = 1L;
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {  
        	//查询到选中ID的值所对应的数据
            String idStr = req.getParameter("id");
            if(idStr != null && !idStr.equals("")){
                int id = Integer.valueOf(idStr);
                AdminDao dao = new AdminDao();
                Admin admin = dao.selectAdminById(id);
                req.setAttribute("admin", admin);
            }
            req.getRequestDispatcher("update.jsp").forward(req, resp);
        }
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {  //根据此ID对数据的值进行修改
            String username = req.getParameter("username");
            String userpwd = req.getParameter("userpwd");
            String idStr = req.getParameter("id");
            Admin admin = new Admin();
            admin.setId(Integer.valueOf(idStr));
            admin.setUsername(new String(username.getBytes("ISO-8859-1"),"UTF-8"));
            admin.setUserpwd(new String(userpwd.getBytes("ISO-8859-1"),"UTF-8"));
            AdminDao dao = new AdminDao();
            dao.updateAdmin(admin);
            req.getRequestDispatcher("ShowServlet").forward(req, resp);
        }
    }
    

        5:建立jsp页面

    index.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!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>
        <style type="text/css">
                table {
                    border: 1px solid pink;
                    margin: 0 auto;
                }
    
                td{
                    width: 150px;
                    border: 1px solid pink;
                    text-align: center;
                }
        </style>
    </head>
    <body>
        <table>
            <tr>
                <td>编号</td>
                <td>帐号</td>
                <td>密码</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${list}" var="item">
                <tr>
                    <td>${item.id }</td>
                    <td>${item.username }</td>
                    <td>${item.userpwd }</td>
                    <td><a href="DeleteServlet?id=${item.id }">删除</a>|<a href="UpdateServlet?id=${item.id }">修改</a></td>
                </tr>
            </c:forEach>
            <tr>
                <td colspan="6" style="text-align: left;"><a href="add.jsp">添加管理员</a></td>
            </tr>
        </table>
    </body>
    </html>

    add.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>添加</title>
        <link rel="stylesheet" href="css/index.css" type="text/css" />
      </head>
      <body>
      <form action="AddServlet" method="post">
        <table border="1" class="t1">
            <tr>
                <td colspan="2s"><h1>添加管理员</h1></td>
            </tr>
            <tr>
                <td>管理员帐号:</td>
                <td><input  type="text" name="username"/></td>
            </tr>
            <tr>
                <td>管理员密码:</td>
                <td><input  type="password" name="userpwd"/></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input  type="submit" value="提交"/>
                    <input  type="reset" value="清空"/>
                </td>
            </tr>
        </table> 
       </form>
      </body>
    </html>

    updata.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>修改</title>
        <link rel="stylesheet" href="css/index.css" type="text/css" />
      </head>
    
      <body>
        <form action="UpdateServlet" method="post">
        <table border="1" class="t1">
            <tr>
                <td colspan="2"><h1>修改管理员信息</h1></td>
            </tr>
            <tr>
                <td>编号:</td>
                <td><input  type="text" name="id" value="${admin.id}" readonly="readonly"/></td>
            </tr>
    
            <tr>
                <td>管理员帐号:</td>
                <td><input  type="text" name="username" value="${admin.username}"/></td>
            </tr>
            <tr>
                <td>管理员密码:</td>
                <td><input  type="text" name="userpwd" value="${admin.userpwd}"/></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input  type="submit" value="提交"/>
                    <input  type="button" value="返回" onclick="history.go(-1)"/>
                </td>
            </tr>
        </table>
       </form>
      </body>
    </html>

    css代码部分:

    @CHARSET "UTF-8";
            table.t1 {
                margin-top:10px;
                margin-left:20px;
                margin-right:20px;
                margin-bottom:5px;
                #background-color: #FFF;
                #background:#EEF4F9;
                #border: none;
                border: 1;
                #color:#003755;
                border-collapse:collapse;
                font: 14px  "宋体";
                text-align: center;
            }
    
            table.t1 th{
                    background:#7CB8E2;
                    color:#fff;
                    padding:6px 4px;
                    text-align:center;
            }
    
            table.t1 td{
                    background:#C7DDEE none repeat-x scroll center left;
                    color:#000;
                    padding:4px 2px;
            }
    
            table.t1 a{
                    text-decoration:none;
                    height:1em;
            }
    
            table.t1 a:link, table.t1  a:visited{
                    color:#3366CC;
            }
    
            table.t1  a:hover{
                    color:#B50000;
                    text-decoration:underline;
            }

    增删改查成果图:

    b138efef6bac2748c476dc207cdf6c07a82.jpg

    添加操作:

    89d696700c58601fa9455e8155e1ff54875.jpg

    添加后显示:

    bedd685608b3ec3bb42b170ed5504791571.jpg

    然后进行删除跟修改。

    转载于:https://my.oschina.net/u/3740271/blog/1924121

    展开全文
  • 通过Java,jdbc,mysql,实现后端对数据库的操作
  • Servlet+JSP增删改查

    2018-04-20 16:01:35
    Servlet+JSP增删改查是框架最底层的写法,学习框之前建议先学jsp
  • jsp + servlet 增删改查

    千次阅读 2010-08-24 20:47:00
    这个项目是别人的结晶,有下载,希望不要找我麻烦。我只是觉得很好 servlet package com.test.servlet;...import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; impo

    这个项目是别人的结晶,有下载,希望不要找我麻烦。我只是觉得很好

    servlet

     

    dao

     

    util

     

    主要显示页面

     

    insert

     

    modify

     

    展开全文
  • //修改编辑页面,点击提交时请求此servlet,对数据库修改,并回到展示全部数据的页面(即请求selectAllServlet) public class UpSubmitServlet extends HttpServlet { @Override protected void doGet...

    1,项目结构
    在这里插入图片描述
    2,数据库中建表,创建商品表格goods,项目中建实体Goods,如下:

    public class Goods {
    		   private Integer goodsId;
    		   private String goodsName;
    		   private Integer price;
    		   private String brand;
    		   private Integer goodsNum;
    		   //构造方法、get、set方法、toString方法均省略
    		   //.......
    		}
    

    3, dao接口编写,如图1中,代码如下:

      public interface GoodsDao {
        //查询所有
        public List<Goods>  selectAll() throws SQLException;
        //添加
        public void addGoods(Goods goods) throws SQLException;
        //删除
        public void delGoods(Integer id) throws SQLException;
       //查询一条
        public Goods selectOne(Integer id) throws SQLException;
        //修改
        public void updateGoods(Goods goods) throws SQLException;
    
    }
    

    4,接口实现类

    public class GoodsDaoImpl implements GoodsDao {//接口实现类
         QueryRunner qr=new QueryRunner(new ComboPooledDataSource());
         //查询所有
         @Override
         public List<Goods> selectAll() throws SQLException {
            String sql="select * from goods ";
            List<Goods> goodsList = qr.query(sql, new BeanListHandler<Goods>(Goods.class));
            return goodsList;
         }
         //添加
          @Override
          public void addGoods(Goods goods) throws SQLException {
             String sql="INSERT INTO goods(goodsName,price,brand,goodsNum) VALUES(?,?,?,?)";
             qr.insert(sql,new BeanHandler<Goods>(Goods.class),goods.getGoodsName(),goods.getPrice(),
                  goods.getBrand(),goods.getGoodsNum());
          }
          //删除
          @Override
          public void delGoods(Integer id) throws SQLException {
             String sql="DELETE FROM goods WHERE goodsId = ?";
             qr.update(sql,id);
          }
          //查询一条
          @Override
          public Goods selectOne(Integer id) throws SQLException {
              String sql="SELECT * FROM goods WHERE goodsId=?";
              Goods goods = qr.query(sql, new BeanHandler<Goods>(Goods.class), id);
              return goods;
          }
          //修改
           @Override
           public void updateGoods(Goods goods) throws SQLException {
              String sql="UPDATE goods SET goodsName=?,price=?,brand=?,goodsNum=? WHERE goodsId=?";
               qr.update(sql,goods.getGoodsName(),goods.getPrice(),goods.getBrand(),
                   goods.getGoodsNum(),goods.getGoodsId());
           }
    }
    

    5,查询所有servlet

    public class SelectAllServlet extends HttpServlet {
     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           //字符集
           req.setCharacterEncoding("utf-8");
           resp.setCharacterEncoding("utf-8");
    
           GoodsDao goodsDao=new GoodsDaoImpl();
           List<Goods> goodsList=null;
           try {
                 goodsList = goodsDao.selectAll();
            } catch (SQLException e) {
                 e.printStackTrace();
            }
    
            System.out.println("goodsList = " + goodsList);
            //将结果放到域中
            req.setAttribute("list",goodsList);
    
            RequestDispatcher dispatcher = req.getRequestDispatcher( "crudJSP/list.jsp");
            dispatcher.forward(req,resp);
    
     }
    }
    

    查询所有的展示页面,jsp页面

    <body>
    <%
       List<Goods> list =(List<Goods>) request.getAttribute("list");
    %>
    
    <table border="1" width="50%" align="center">
        <tr>
            <td colspan="7" align="center">商品信息明细表</td>
        </tr>
        <th>编号</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>品牌</th>
        <th>数量</th>
        <th>修改</th>
        <th>删除</th>
        
        <%
           for(Goods goods:list){
        %>
        <tr>
            <td><%=goods.getGoodsId()%></td>
            <td><%=goods.getGoodsName()%></td>
            <td><%=goods.getPrice()%></td>
            <td><%=goods.getBrand()%></td>
            <td><%=goods.getGoodsNum()%></td>
            <td><a href="<%=request.getContextPath()%>/upEditServlet?id=<%=goods.getGoodsId()%>">修改</a></td>
            <td><a href="<%=request.getContextPath()%>/delServlet?id=<%=goods.getGoodsId()%>">删除</a></td>
        </tr>
        <%
          }
        %>
        <tr><td colspan="7"><a href="crudJSP/add.jsp">添加</a></td></tr>
    </table>
    </body>
    

    以下的添加功能的servlet

    public class AddServlet extends HttpServlet {
    
     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           //字符集
           req.setCharacterEncoding("utf-8");
           resp.setCharacterEncoding("utf-8");
    
          String name = req.getParameter("name");
          Integer price = Integer.parseInt(req.getParameter("price"));
          String brand = req.getParameter("brand");
          Integer num =Integer.parseInt( req.getParameter("num"));
    
           Goods goods=new Goods(name,price,brand,num);
           GoodsDao goodsDao=new GoodsDaoImpl();
              try {
                   goodsDao.addGoods(goods);
              } catch (SQLException e) {
                   e.printStackTrace();
              }
    
              resp.sendRedirect(req.getContextPath()+"/selectAllServlet");
    
     }
    }
    

    以下是添加的编辑页面jsp

    <body>
            <form action="<%=request.getContextPath()%>/addServlet">
                <p>商品名称:<input type="text" name="name" value=""></p>
                <p>价格:<input type="text" name="price" value=""></p>
                <p>品牌:<input type="text" name="brand" value=""></p>
                <p>数量:<input type="text" name="num" value=""></p>
                <input type="submit" value="添加">
            </form>
    
    </body>
    

    以下是删除的servlet

    public class DeleteServlet extends HttpServlet {
     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          //字符集
          req.setCharacterEncoding("utf-8");
          resp.setCharacterEncoding("utf-8");
    
          GoodsDao goodsDao=new GoodsDaoImpl();
          /*Integer id = Integer.parseInt(req.getParameter("id"));
          goodsDao.delGoods(id);*/
          String id = req.getParameter("id");
           try {
               goodsDao.delGoods(Integer.parseInt(id));
           } catch (SQLException e) {
               e.printStackTrace();
           }
    
           resp.sendRedirect(req.getContextPath()+"/selectAllServlet");
     }
    }
    

    以下 获取修改的编辑页面实现,servlet

       //获取点击的那条记录(数据),然后进入修改编辑页面
    public class UpEditServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           //字符集
           req.setCharacterEncoding("utf-8");
           resp.setCharacterEncoding("utf-8");
           //从页面获取需要修改某条记录的id
           Integer id = Integer.parseInt(req.getParameter("id"));
    
           GoodsDao goodsDao=new GoodsDaoImpl();
           Goods goods=null;
           try {
                 goods = goodsDao.selectOne(id);
                } catch (SQLException e) {
                 e.printStackTrace();
                }
                //将获取一条的记录放入域中
               req.setAttribute("goods",goods);
               //转发到修改编辑页面
              RequestDispatcher dispatcher = req.getRequestDispatcher("crudJSP/updateEdit.jsp");
              dispatcher.forward(req,resp);
    
          }
    }
    

    以下编辑修改页面jsp

    <body>
    <%--这个修改编辑页面,获取点击后的那条信息--%>
    <%
           Goods goods = (Goods)request.getAttribute("goods");
    %>
    
    <form action="<%=request.getContextPath()%>/updateSubmitServlet">
        <%--id设置为隐藏hidden--%>
        <input type="hidden" name="id" value="<%=goods.getGoodsId()%>">
        <p>商品名称:<input type="text" name="name" value="<%=goods.getGoodsName()%>"></p>
        <p>价格:<input type="text" name="price" value="<%=goods.getPrice()%>"></p>
        <p>品牌:<input type="text" name="brand" value="<%=goods.getBrand()%>"></p>
        <p>数量:<input type="text" name="num" value="<%=goods.getGoodsNum()%>"></p>
        <input type="submit" value="修改">
    
    </form>
    </body>
    

    以下提交修改页面,修改的信息存到数据库并展示更新后的所有数据servlet。

     //修改编辑页面,点击提交时请求此servlet,对数据库修改,并回到展示全部数据的页面(即请求selectAllServlet)
    public class UpSubmitServlet extends HttpServlet {
     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          //字符集
          req.setCharacterEncoding("utf-8");
          resp.setCharacterEncoding("utf-8");
          //修改页面已经完成,即将把数据保存放到数据库,首先要从页面获取数据
          String name = req.getParameter("name");
          Integer price = Integer.parseInt(req.getParameter("price")) ;
          String brand = req.getParameter("brand");
          Integer num =Integer.parseInt(req.getParameter("num")) ;
          Integer id = Integer.parseInt(req.getParameter("id"));
          //将参数封装起来
          Goods goods=new Goods(id,name,price,brand,num);
          GoodsDao goodsDao=new GoodsDaoImpl();
          try {
               goodsDao.updateGoods(goods);
          } catch (SQLException e) {
                e.printStackTrace();
          }
          //修改完成后,重定向,进入查询展示页面
          resp.sendRedirect(req.getContextPath()+"/selectAllServlet");
     }
    }
    
    展开全文
  • 开始之前的准备(servlet+jsp+javaBean增删改查)2.查询3.删除4.添加5.修改5.1.进入修改的页面 1.开始之前的准备(servlet+jsp+javaBean增删改查) jsp:页面的请求和展示 在前台主要学了jsp进行页面的请求和展示 ...

    1.开始之前的准备(servlet+jsp+javaBean增删改查)

    • jsp:页面的请求和展示

      • 在前台主要学了jsp进行页面的请求和展示
    • java后台

    • mysql数据库

      • 学习了java如何进行数据库增删改查
        • JDBC
        • JDBC重构Dao
          • Dao进行sql语句
      • 将数据库的获取结果响应到页面上
    • 页面向后台进行请求

      • 请求:(url:http://xx.8080/student.do)
      • servlet进行响应
    • jsp+servlet+javaBean+mysql === M2

    • 代码准备

      • StudentServlet.java

        • package com.Li;
          
          import java.io.IOException;
          
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServlet;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          
          /**
           * @desc Student 模块的 Servlet
           * @author Li Ya Hui 
           * @time   2021年6月2日 上午8:34:22
           */
          public class StudentServlet extends HttpServlet {
          
              @Override
              protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  System.out.println("Student--->service");
              }
          }
          
      • index.jsp

        • <%@ page language="java" contentType="text/html; charset=UTF-8"
              pageEncoding="UTF-8"%>
          <!DOCTYPE html>
          <html>
              <head>
                  <meta charset="UTF-8">
                  <title>JSP+Servlet+JavaBean实现表单的增删改查</title>
              </head>
              <body>
                  <a href="<%=request.getContextPath()%>/student.do">Student模块的全部查询 </a>
              </body>
          </html>
          
      • web.xml

        • <servlet>
              <servlet-name>ser</servlet-name>
              <servlet-class>com.Li.StudentServlet</servlet-class>
          </servlet>
          
          <servlet-mapping>
              <servlet-name>ser</servlet-name>
              <url-pattern>/studnet.do</url-pattern>
          </servlet-mapping>
          

    2.查询

    • 首先创建一个Dao(连接数据库)

    • 然后创建一个查询的类StudnetService实例化Dao(StudnetService)

    • 在StudentServlet里创建一个StudnetService对象的query方法

    • query方法将数据转成list<map>然后再存储到request对象里去

    • 在StudentServlet里service方法里获取链接里的method如果匹配 调用 query查询方法

    • 在主页面里写一个超链接,超链接为<a href="<%=request.getContextPath()%>/student.do?method=query"> Student模块的全部查询 </a>

    • method的参数为query代表我的一个匹配参数

    • 当servlet匹配成功时,会将request.getRequestDispatcher("/jsps/studnet/list_student.jsp").forward(request, response);发送请求

    • 子页面接收数据的代码(list_student.jsp)

      • <%@page import="java.util.Map"%>
        <%@page import="java.util.List"%>
        <%@ page language="java" contentType="text/html; charset=UTF-8"
            pageEncoding="UTF-8"%>
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
        <title>Student 模块的查询展示界面</title>
        <style type="text/css">
        	*{
        		margin: 0;
        		padding: 0;
        	}
        	table{
        	border-width:2px;
        		border-color: red;
        		text-align: center;
        	}
        </style>
        </head>
        <body>
        	<table border="1">
        		<tr>
        			<td>学号</td>
        			<td>姓名</td>
        			<td>年龄</td>
        			<td>性别</td>
        			<td>操作</td>
        		</tr>
        		<%
        			List list = (List) request.getAttribute("list");
        			for(int i = 0 ; i < list.size() ; i++)
        			{
        				Map map =(Map) list.get(i);
        		%>
        		<tr>
        			<td><%=map.get("sno") %></td>
        			<td><%=map.get("sname") %></td>
        			<td><%=map.get("sage") %></td>
        			<td><%=map.get("ssex") %></td>
        			<td>
        				<a href="#">添加</a>
        				<a href="#">修改</a>
        				<a href="#">删除</a>
        			</td>
        		</tr>
        		<%
        			}
        		%>
        	</table>
        </body>
        </html>
        
    • 配置web.xml

      • <?xml version="1.0" encoding="UTF-8"?>
        <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://JAVA.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
          <display-name>WebM2Demo001</display-name>
          <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
          </welcome-file-list>
          <servlet>
          	<servlet-name>StudentServlet</servlet-name>
          	<servlet-class>com.Li.student.StudentServlet</servlet-class>
          </servlet>
          <servlet-mapping>
          	<servlet-name>StudentServlet</servlet-name>
          	<url-pattern>/student.do</url-pattern>
          </servlet-mapping>
        </web-app>
        

    3.删除

    • 删除的第一步,首先给删除的按钮加上链接:<a href="<%=request.getContextPath()%>/student.do?method=delete&sno=<%=map.get("sno") %>">删除</a>

    • method=delete 制造关键字

    • sno=<%=map.get(“sno”) %> 制造主键

    • 在StudentServlet的service方法里添加method=delete时的方法,调用delete方法

    • delete方法里调用StudentService里的deleteBySno方法

      • /**
        	 * @desc 根据学号删除了一条学生信息
        	 * @param sno
        	 * @throws SQLException 
        	 * @throws ClassNotFoundException 
        	 */
        	public void deleteBySno(String sno) throws ClassNotFoundException, SQLException {
        		// 删除
        		dao.executeUpdate(" delete from student where sno='"+sno+"'");
        	}
        
    • 在StudentServlet的delete方法里进行重定向

      • //2.调用studentService中的方法执行sql语句实现删除该条记录
        studentservice.deleteBySno(sno);
        //3.重定向:刷新   重新指向新的页面  简介进行刷新页面
        response.sendRedirect(request.getContextPath()+"/student.do?method=query");
        

    4.添加

    • 添加的第一步,首先给添加按钮加上链接:<a href="<%=request.getContextPath()%>/student.do?method=addPage">添加</a>

    • method=addPage 代表要进入信息添加页面

    • 新建student模块添加页面

      • <%@ page language="java" contentType="text/html; charset=UTF-8"
            pageEncoding="UTF-8"%>
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
        <title>student模块的添加页面</title>
        <style type="text/css">
        	*{
        		margin:0;
        		padding:0;	
        	}
        
        </style>
        </head>
        <body>
        	<form action="<%=request.getContextPath()%>/student.do?method=add" method="post">
        		<table border="2" algin="center">
        			<tr>
        				<td>姓名</td>
        				<td><input type="text" name="sname" value=""/></td>
        			</tr>
        			<tr>
        				<td>年龄</td>
        				<td><input type="text" name="sage" value=""/></td>
        			</tr>
        			<tr>
        				<td>性别</td>
        				<td><input type="text" name="ssex" value=""/></td>
        			</tr>
        			<tr>
        				<td colspan="2"><input type="submit" style="display:block;margin:auto;" value="提交"/></td>
        			</tr>
        		</table>
        	</form>
        </body>
        </html>
        
    • 在添加页面的表单里提交地址为:action="<%=request.getContextPath()%>/student.do?method=add"

    • 因为表单存在英文,当前前台向后台用form表单传输数据时,需要设定编码request.setCharacterEncoding("utf-8");

    • 在StudentService里service判断里添加else if(“addPage”.equals(method)) {this.addPage(request,response);
      }

    • 在StudentService里service判断里添加

      else if("add".equals(method)) {
          this.add(request,response);
      }
      
    • 在StudentService里添加add数据方法

      • /**
        	 * @desc 保存添加页面的数据
        	 * @param request
        	 * @param response
        	 * @throws SQLException 
        	 * @throws ClassNotFoundException 
        	 * @throws IOException 
        	 */
        	private void add(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, IOException {
        		System.out.println("StudentServlet--->add()");
        		//1.接值
        		String sname = request.getParameter("sname");
        		String sage = request.getParameter("sage");
        		String ssex = request.getParameter("ssex");
        		
        		System.out.println(sname+sage+ssex);
        		//2.调用StudentService中的方法执行sql语句实现将数据保存到mysql数据库中
        		studentservice.save(sname,sage,ssex);
        		
        		//3.进行重定向(刷新)
        		response.sendRedirect(request.getContextPath()+"/student.do?method=query");
        	}
        
    • 还需要在StudentService里添加一个save保存方法

      • /**
        	 * @desc 根据前台的信息从而添加一条学生信息到数据库
        	 * @param sname
        	 * @param sage
        	 * @param ssex
        	 * @throws SQLException 
        	 * @throws ClassNotFoundException 
        	 */
        	public void save(String sname, String sage, String ssex) throws ClassNotFoundException, SQLException {
        		dao.executeUpdate("insert into student values ('"+UUID.randomUUID().toString().substring(0, 9)+"','"+sname+"','"+Integer.parseInt(sage)+"','"+ssex+"')");
        	}
        
    • 测试添加数据(完成)

    5.修改

    5.1.进入修改的页面

    • 首先讲展示数据页面的修改连接改为

      • <a href="<%=request.getContextPath()%>/student.do?method=editPage&sno=<%=map.get("sno")%>">修改</a>
        
    • method=editPage 代表将进入修改信息界面内 并且将此数据的sno作为参数传入

    • 然后将StudentServlet里的service方法method关键字判断加入editPage

      • else if("editPage".equals(method)) 
        {
            this.editPage(request,response);
        }
        
    • 然后创建一个editPage函数

      • /**
        	 * @desc 跳转到学生信息修改页面  转发
        	 * @param request
        	 * @param response
        	 * @throws SQLException 
        	 * @throws ClassNotFoundException 
        	 * @throws IOException 
        	 * @throws ServletException 
        	 * @throws  
        	 */
        private void editPage(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, IOException, ServletException {
            System.out.println("StudentServlet--->editPage");
            //1.接值
            String sno = request.getParameter("sno");
            System.out.println(sno);
            //2.根据传递过来的sno查询该条数据信息
            Map<String, Object> map = studentservice.queryOneBySno(sno);	
            System.out.println(map);
            //3.存值
            request.setAttribute("map", map);
            //4.转发地址  
           request.getRequestDispatcher("/jsps/studnet/edit_student.jsp").forward(request, response);
        }
        
    • 我们发现,现在需要一个方法来根据sno查找数据 studentservice.queryOneBySno(sno)

    • 在StudentService 里创建方法

      • /**
        	 * @desc 4.根据sno查询一条数据
        	 * @param sno
        	 * @return
        	 * @throws SQLException 
        	 * @throws ClassNotFoundException 
        	 */
        	public Map<String, Object> queryOneBySno(String sno) throws ClassNotFoundException, SQLException {
        		return dao.executeQueryForMap("select * from student where sno = '"+sno+"'");
        	}
        
    • 接下来数据已经存入到了 request 并且已经转到了修改页面,只剩下了 “ 喷数据 ”

      • 新建/jsps/studnet/edit_student.jsp,代码:

      • <%@page import="java.util.Map"%>
        <%@ page language="java" contentType="text/html; charset=UTF-8"
            pageEncoding="UTF-8"%>
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
        <title>Student模块的修改页面</title>
        </head>
        <body>
        	<%
        	//取出StudentServlet里的request的数据  "map"
        		Map map =(Map) request.getAttribute("map");
        	%>
        	<!-- 目前没有加提交地址 -->
        	<table border="2" bordercolor="green" align="center">
        		<tr>
        			<td>姓名</td>
        			<td><input type="text" name="sname" value="<%=map.get("sname") %>"/></td>
        		</tr>
        		<tr>
        			<td>年龄</td>
        			<td><input type="text" name="sage" value="<%=map.get("sage") %>"/></td>
        		</tr>
        		<tr>
        			<td>性别</td>
        			<td><input type="text" name="ssex" value="<%=map.get("ssex") %>"/></td>
        		</tr>	
        		<tr>
        			<td colspan="2"><input type="submit" style="margin :auto; display:block;" value="更新"/></td>
        		</tr>
        	</table>
        </body>
        </html>
        
    展开全文
  • jsp+servlet增删改查

    2014-11-08 15:00:36
    jsp+servlet做的用户增删改查,练手写了玩的,功能不全
  • jsp+servlet增删改查分页 项目中有个info.doc文档,里面有需要的表跟字段序列
  • servlet+jsp数据库增删改查实例

    万次阅读 2015-03-30 21:55:24
    个人觉得这种模式是MVC模式 1. 先写一个类,类里面有几个属性。  2. 写一个接口。里面有增删改查的方法。 (写在service里) 3. 写一个类实现这个接口(实现里面...5. 写 servlet操作, 处理增删改查的信息。
  • 所以,熟练使用增删改查是java的入门标准尺,现在我们就来学习一个最最最基础的增删改查,基于servlet+tomcat+jsp的crud(增删改查学术名字) 源码 csdn:CSDN下载 github:GITHUB下载 环境 ide:idea jdk:1.8 mysql:...
  • jsp + servlet + jdbc 实现增删改查事例
  • jsp+servlet实现CRUD功能,ajax验证用户名,退出系统,数据库密码加密,过滤器解决中文乱码,实现分页功能,实现导出Excel等等功能。页面不是很美观、、、、
  • jspservlet实现增删改查

    千次阅读 2019-03-22 18:38:29
    jspservlet实现增删改查 最终实现的效果如下(并没有加上css修饰,就实现最简单功能) 先要事先新建一个jsp文件,和4个servler文件,4个是调用ajax方法给予回调函数,一个是sql方法函数我命名为SqlConnection ...
  • Servlet+JSP实现员工增删改查-附件资源
  • servlet+JSTL+JSP增删改查

    2015-06-19 09:47:14
    servlet+JSTL+JSP增删改查,简单的,很详细,初学者适合
  • jsp+servlet最简单的增删改查,简单的不能再简单的增删改查
  • 增删改查:( Servlet实现增删改查功能_+jsp登录页面.)

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,458
精华内容 583
关键字:

jspservlet增删改查