JavaWeb学习_增删改

1. 在列表中点击值显示详细信息

//IndexServlet

@WebServlet("/index")
public class IndexServlet  extends ViewBaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        FruitDAO fruitDAO=new FruitDAOImpl();
        List<Fruit>fruitList=fruitDAO.getFruitList();
        HttpSession session=req.getSession();
        session.setAttribute("fruitList", fruitList);

        //此处的视图名称是index,
        //那么thymeleaf会将这个 逻辑视图名称 对应到 物理视图 名称上去
        //逻辑视图名称:index
        //物理视图名称: view-prefix+逻辑视图名称+view-suffix
        //所以真是的视图名称为   /   index.    html
        super.processTemplate("index",req,resp);
    }
}

(1)index.html

<tr th:unless="${#lists.isEmpty(session.fruitList)}" th:each="fruit : ${session.fruitList}">
        <!-- <td ><a th:text="${fruit.fname}" th:href="@{'/edit.do?fid='+${fruit.fid}}">苹果</a></td>
           ( th:text="" 会把后面的值覆盖,添加超链接时候,为防止超链接被覆盖,将“th:text=”放入<a>标签中
@{}表示thymeleaf中的绝对路径 ${}表示需要thymeleaf来解析 而“/edit.do?fid=”是字符串不需要thymeleaf去解析,添加单引号) -->

         <!--
         给url地址后面附加请求参数:
         @{/order/process(exexId=${exexId},exexType="FAST")}  (键值对)
         -->
         <td><a th:text="${fruit.fname}"  th:href="@{/edit.do(fid=${fruit.fid})}"/>苹果</td>
         <td th:text="${fruit.price}">5</td>
         <td th:text="${fruit.fcount}">20</td>
     </tr>

(2)edit.do

package com.fruits.servelet;

import com.fruits.dao.FruitDAO;
import com.fruits.dao.Impl.FruitDAOImpl;
import com.fruits.pojo.Fruit;
import com.myssm.myspringmvc.ViewBaseServlet;

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 java.io.IOException;

@WebServlet("/edit.do")
public class EditServlet extends ViewBaseServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fidstr = request.getParameter("fid");
        int fid = Integer.parseInt(fidstr);
        FruitDAO fruitDAO1=new FruitDAOImpl();
        Fruit fruit1 = new Fruit();
        fruit1= fruitDAO1.getFruitById(fid);
        request.setAttribute("fruit",fruit1);
        super.processTemplate("edit",request,response);
    }
}

(3)FruitDAO和FruitDAOImpl

//FruitDAO
public interface FruitDAO {
    //获取所有的库存列表信息
    List<Fruit> getFruitList();
    //根据id获取特定的水果信息
    Fruit getFruitById(int fid);
}
//FruitDAOImpl
public class FruitDAOImpl extends DB implements FruitDAO {
    @Override
    public Fruit getFruitById(int fid) {
        Fruit fruit = new Fruit();
        fruit.setFid(fid);
        String sql = "select * from Fruit where fid = ?";
        getConn();
        try {
            ps =conn.prepareStatement(sql);
            ps.setInt(1,fruit.getFid());
            rs = ps.executeQuery();
            while (rs.next()){
            fruit.setFname(rs.getString(2));
            fruit.setPrice(rs.getInt(3));
            fruit.setFcount(rs.getInt(4));
            fruit.setRemark(rs.getString(5));}
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return fruit;
    }
}

(4)edit.html

  1. 操作请求域(request)

    Servlet中代码:

    String requestAttrName = "UserName";
    String requestAttrValue = "小王";
    request.setAttribute(requestAttrName, requestAttrValue);

    Thymeleaf表达式:

    <p th:text="${UserName}">request field value</p>
  2. 操作会话域

    Servlet中代码:

    // ①通过request对象获取session对象
    HttpSession session = request.getSession();
    
    // ②存入数据
    session.setAttribute("UserName", "小王");

    Thymeleaf表达式:

    <p th:text="${session.UserName}">这里显示会话域数据</p>
  3.  操作应用域

    Servlet中代码:

    // ①通过调用父类的方法获取ServletContext对象
    ServletContext servletContext = getServletContext();
    
    // ②存入数据
    servletContext.setAttribute("UserName", "小王");

    Thymeleaf表达式:

    <p th:text="${application.helloAppAttr}">这里显示应用域数据</p>
<body>
    <div>
        <input type="hidden" name="fid" th:value="${fruit.fid}">
        <!--隐藏域:功能类似于文本框,值会随着表单的发送传递给服务器,但是界面上用户看不到-->
        
        <form th:action="@{/update.do}" method="post">
            <table border="1" th:object="${fruit}">
                <tr>
                    <th>名称:</th>
                   
                    <!--<td><input type="text" name="fname" th:value="${fruit.fname}"/></td>
                     (若table中没有加 th:object="${fruit}") -->
                    <td><input type="text" name="fname" th:value="*{fname}"/></td>
                </tr>
                <tr>
                    <th>价格:</th>
                    <td><input type="text" name="price" th:value="*{price}"/></td>
                </tr>
                <tr>
                    <th>库存:</th>
                    <td><input type="text" name="fcount" th:value="*{fcount}"/></td>
                </tr>
                <tr>
                    <th>备注:</th>
                    <td><input type="text" name="remark" th:value="*{remark}"/></td>
                </tr>
                <tr >
                    <th colspan="2" ><input type="submit" value="修改"></th>
                </tr>
            </table>
        </form>
    </div>
</body>

2. 更改edit.html中显示的数据

(1)UpdateServlet

@WebServlet("/update.do")
public class UpdateServlet extends ViewBaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        String fidstr = request.getParameter("fid");
        int fid = Integer.parseInt(fidstr);
        String fname = request.getParameter("fname");
        String fpricestr = request.getParameter("price");
        int price =Integer.parseInt(fpricestr);
        String fcountstr = request.getParameter("fcount");
        int fcount =Integer.parseInt(fcountstr);
        String remark = request.getParameter("remark");

        //System.out.println(fid+" "+fname+" "+price+" "+fcount+" "+remark);

        FruitDAO fruitDAO=new FruitDAOImpl();

        /*Fruit fruit = new Fruit();
        fruit.setFid(fid);
        fruit.setFname(fname);
        fruit.setPrice(price);
        fruit.setFcount(fcount);
        fruit.setRemark(remark);
        boolean b = fruitDAO.updateFruitById(fruit);*/

        boolean b = fruitDAO.updateFruitById(new Fruit(fid, fname, price, fcount, remark));
        if(b){
            System.out.println("修改成功");
        }
        else{
            System.out.println("修改失败");
        }
        /*super.processTemplate("index",request,response);
        
        相当于
        request.getRequestDispatcher("index").forward(request,response); 获得的数据还是更新之前的数据
        此处需要重定向,目的是重新给IndexServlet发请求,
        重新获取fruitList,然后覆盖到session中,这样index.html页面上显示的session中的数据才是最新的。
        */
        response.sendRedirect("index");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

(2)FruitDAO和FruitDAOImpl

//FruitDAO
public interface FruitDAO {
    //获取所有的库存列表信息
    List<Fruit> getFruitList();
    //根据id获取特定的水果信息
    Fruit getFruitById(int fid);
    //根据id修改水果信息
    boolean updateFruitById(Fruit fruit);
}
//FruitDAOImpl
public class FruitDAOImpl extends DB implements FruitDAO {
    @Override
    public boolean updateFruitById(Fruit fruit) {
        boolean b = false;
        int fid = fruit.getFid();
        String  sql = "UPDATE Fruit set fname =? , price = ?, fcount = ?, remark = ? where fid = ?";
        getConn();
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,fruit.getFname());
            ps.setInt(2,fruit.getPrice());
            ps.setInt(3,fruit.getFcount());
            ps.setString(4,fruit.getRemark());
            ps.setInt(5,fid);
            ps.executeUpdate();
            b = true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return b;
    }
}

3.在页面上删除水果信息

(1)index.html

 在页面上添加”删除“图片,点击实现删除功能(引入 js ,点击图片跳转到 js 中的 delFruit(fid) 功能)

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <script language="JavaScript" src="js/index.js"></script>
</head>
<body>
<div >
    <div >
        <table >
            <tr>
                <th >名称</th>
                <th >单价</th>
                <th >库存</th>
                <th >操作</th>
            </tr>

            <tr th:if="${#lists.isEmpty(session.fruitList)}">
                <td colspan="4">对不起,货存为空!</td>
            </tr>
            <tr th:unless="${#lists.isEmpty(session.fruitList)}" th:each="fruit : ${session.fruitList}">
               <!-- <td ><a th:text="${fruit.fname}" href="@{'/edit.do?fid='+${fruit.fid}}">苹果</a></td>
                  ( th:text="" 会把后面的值覆盖,添加超链接时候,为防止超链接被覆盖,将“th:text=”放入<a>标签中
       @{}表示thymeleaf中的绝对路径 ${}表示需要thymeleaf来解析 而“/edit.do?fid=”是字符串不需要thymeleaf去解析,添加单引号) -->

                <!--
                给url地址后面附加请求参数:
                @{/order/process(exexId=${exexId},exexType="FAST")}  (键值对)
                -->
                <td><a th:text="${fruit.fname}"  href="@{/edit.do(fid=${fruit.fid})}">苹果</td>
                <td th:text="${fruit.price}">5</td>
                <td th:text="${fruit.fcount}">20</td>
                <!-- <td> <img src="img/del.png" th:onclick="'delFruit('+${fruit.fid}+')"></td> -->
                <td> <img src="img/del.png" th:onclick="|delFruit(${fruit.fid})|"></td>
            </tr>
        </table>
    </div>
</div>
</body>
</html>

(2)js

function delFruit( fid ) {
    if(confirm("是否确认删除?")){
        window.location.href="del.do?fid="+fid;  //地址栏发生变化,带参数fid 转到del.do
    }
}

(3)DeleteServlet

@WebServlet("/del.do")
public class DeleteServlet extends ViewBaseServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fidstr = request.getParameter("fid");
        int fid = Integer.parseInt(fidstr);
        FruitDAO fruitDAO = new FruitDAOImpl();
        boolean b = fruitDAO.deleteFruitById(fid);
        if(b){
            System.out.println("删除成功!");
        }
        else{
            System.out.println("删除失败!");
        }
        response.sendRedirect("index");
    }
}

(4)FruitDAO和FruitDAOImpl

public interface FruitDAO {
    //获取所有的库存列表信息
    List<Fruit> getFruitList();
    //根据id获取特定的水果信息
    Fruit getFruitById(int fid);
    //根据id修改水果信息
    boolean updateFruitById(Fruit fruit);
    //根据id删除水果信息
    boolean deleteFruitById(int fid);
}

public class FruitDAOImpl extends DB implements FruitDAO {
    @Override
    public boolean deleteFruitById(int fid) {
        boolean b = false;
        String sql = "delete from fruit where fid = ? ";
        getConn();
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1,fid);
            ps.executeUpdate();
            b=true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return b;
    }
}

 4. 添加水果信息

(1)add.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <form action="add.do"  method="post"> <!--不能使用th:action="@{/add.do}" 无法通过thymeleaf渲染-->
        <table border="1" >
            <tr>
                <th>id:</th>
                <td><input type="text" name="fid" ></td>
            </tr>
            <tr>
                <th>名称:</th>
                <td><input type="text" name="fname" /></td>
            </tr>
            <tr>
                <th>价格:</th>
                <td><input type="text" name="price" ></td>
            </tr>
            <tr>
                <th>库存:</th>
                <td><input type="text" name="fcount" ></td>
            </tr>
            <tr>
                <th>备注:</th>
                <td><input type="text" name="remark" ></td>
            </tr>
            <tr >
                <th colspan="2" ><input type="submit" value="添加"></th>
            </tr>
        </table>
    </form>
</div>
</body>
</html>

(2)add.do

@WebServlet("/add.do")
public class AddServlet extends ViewBaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String fidstr = request.getParameter("fid");
        int fid = Integer.parseInt(fidstr);
        String fname = request.getParameter("fname");
        String fpricestr = request.getParameter("price");
        int price =Integer.parseInt(fpricestr);
        String fcountstr = request.getParameter("fcount");
        int fcount =Integer.parseInt(fcountstr);
        String remark = request.getParameter("remark");

        System.out.println(fid+" "+fname+" "+price+" "+fcount+" "+remark);

        FruitDAO fruitDAO = new FruitDAOImpl();
        boolean b = fruitDAO.addFruits(new Fruit(fid,fname,price,fcount,remark));
        if(b){
            System.out.println("添加成功");
        }
        else{
            System.out.println("添加失败");
        }
        response.sendRedirect("index");
    }
}

(3)FruitDAO和FruitDAOImpl

public interface FruitDAO {
    //获取所有的库存列表信息
    List<Fruit> getFruitList();
    //根据id获取特定的水果信息
    Fruit getFruitById(int fid);
    //根据id修改水果信息
    boolean updateFruitById(Fruit fruit);
    //根据id删除水果信息
    boolean deleteFruitById(int fid);
    //添加水果信息
    boolean addFruits(Fruit fruit);
}
public class FruitDAOImpl extends DB implements FruitDAO {
 @Override
    public boolean addFruits(Fruit fruit) {
        boolean b = false;
        String sql = "insert into fruit values(?,?,?,?,?)";
        getConn();
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1,fruit.getFid());
            ps.setString(2,fruit.getFname());
            ps.setInt(3,fruit.getPrice());
            ps.setInt(4,fruit.getFcount());
            ps.setString(5,fruit.getRemark());
            ps.executeUpdate();
            b = true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return b;
    }
}
posted @   浑浑噩噩一只小迷七  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示