本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2024-11(2)

浏览器界面下的基于JSP和servlet的数据的增删改查

发布于2021-05-29 20:59     阅读(1257)     评论(0)     点赞(7)     收藏(2)


JavaWeb学习大纲传送门

本章学习目录

一,jsp界面

  • 主界面index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!--实现一进如界面就跳转至queryGoods.jsp界面-->
<jsp:forward page="/goods.do?operate=queryGoods"></jsp:forward>
  • 展示商品界面showgoods.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html>
<head>
    <title>展示商品</title>
    <style>
        table{
            border: 1px solid orange;
            width: 600px;
            border-collapse: collapse;
        }
        th,td{
            border: 1px solid orange;
            height: 50px;
            line-height: 50px;
            text-align: center;

        }
    </style>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>商品编号</th>
        <th>商品名称</th>
        <th>商品单价</th>
        <th>上架时间</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
<c:forEach items="${requestScope.goodsList}" var="good">
    <tr>
        <td>${good.g_id}</td>
        <td>${good.g_name}</td>
        <td>${good.g_price}</td>
        <td><fmt:formatDate value="${good.g_date}" pattern="yyyy-MM-dd"/></td>
        <td>
            <a href="goods.do?g_id=${good.g_id}&operate=queryGoodsById">修改</a>
            <a href="goods.do?g_id=${good.g_id}&operate=delGoodsById">删除</a>
        </td>
    </tr>
</c:forEach>
    <tr>
        <td colspan="5">
            <a href="insertGoods.jsp">添加商品</a>
        </td>
    </tr>

    </tbody>
</table>
</body>
</html>

  • 更改商品信息界面updategoods.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>更新商品</title>
</head>
<body>
<h2>修改商品</h2>
<form method="post" action="goods.do?operate=updateGoods">
<table align="center">
        <input type="hidden" name="g_id" value="${requestScope.goods.g_id}">
        商品名称<input type="text" name="g_name" value="${requestScope.goods.g_name}">
        商品单价<input type="text" name="g_price" value="${requestScope.goods.g_price}">
        上架日期<input type="date" name="g_date" value="<fmt:formatDate value="${requestScope.goods.g_date}" pattern="yyyy-MM-dd"/>"/>
</table>
    <button>修改</button>
    <button type="reset">重置</button>
</form>
</body>
</html>

  • 添加商品界面insertgoods.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加商品</title>
</head>
<body>
<form method="post" action="goods.do?operate=insertGoods">
<input type="hidden" name="g_id">
商品名称<input type="text" name="g_name">
商品价格<input type="text" name="g_price">
商品上架日期<input type="date" name="g_date">
<button>添加</button>
<button type="reset">重置</button>
</form>
</body>
</html>

二,model层

  • 工具类DBUtil
package cn.jazhong.model;

import org.apache.commons.beanutils.ConvertUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public abstract class DBUtil {
    //连接属性
    protected Connection conn = null;
    //预处理对象属性
    protected PreparedStatement ps = null;
    //结果集对象
    protected ResultSet rs = null;
    /**
     * 连接数据库方法
     */
    protected Connection getConn() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/goods?useSSL=true","root","root");
        return conn;
    }
    /**
     * 释放数据库相关资源
     */
    protected void closeAll(){
        try { if(rs != null){ rs.close(); }
              if(ps != null){ ps.close(); }
              if(conn != null){ conn.close(); }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            conn = null;
            ps = null;
            rs = null;
        }
    }

    /**
     *对数据库进行操作的工具类
     */
    protected void myexecuteUpdate(String sql,Object... params){
        try {
            //调用获取连接方法
            this.getConn();
            ps=conn.prepareStatement(sql);
            //设置?占位符params
            if (sql!=null&&params.length!=0){
                for (int i=0;i<params.length;i++){
                    ps.setObject(i+1,params[i]);
                }
            }
            //判断是否操作成功
            if (ps.executeUpdate()>0){
                System.out.println("操作成功");
            }else {
                System.out.println("操作失败");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeAll();
        }
    }

    /**
     *对数据库进行查询的工具类
     */
    public <T>List<T> excuteQuery(String sql,Class<T> cla,Object...params){
        try {
            this.getConn();
            ps=conn.prepareStatement(sql);
            if (params!=null&&params.length!=0){
                for (int i=0;i<params.length;i++){
                    ps.setObject(i+1,params[i]);
                }
            }
            rs=ps.executeQuery();
            //获得查询结果的元数据(查询结果的表结构)
            //通过结果集获得查询结果的元数据
            ResultSetMetaData rsmt= rs.getMetaData();
            //获得查询结果集的列数方便遍历
            int columnCount = rsmt.getColumnCount();
            //用于存储对象的list集合
            List<T> list=new ArrayList<>();
            //遍历结果集,先将结果集中的对象封装到对象中,再将对象封装到list集合中
            while (rs.next()){
                //创建类的对象(实体对象)
                T t = cla.newInstance();
                //循环获取每一列数据
                for (int i = 1; i <=columnCount; i++) {
                    //根据列编号获取一列数据
                    Object value = rs.getObject(i);
                    //获得当前类所对应的实体类中的set方法,并调用
                    //获得当前列的列名
                    String columnName = rsmt.getColumnName(i);
                    //根据列名(属性名)属性field对象
                    Field field = cla.getDeclaredField(columnName);
                    //根据列名获取set方法,当前属性的方法=set+属性首字母大写
                    String methodName="set"+columnName.substring(0,1).toUpperCase()+columnName.substring(1);
                    //根据方法名和参数类型获取Method对象,因为方法名和参数可以唯一确定一个方法
                    Method method = cla.getDeclaredMethod(methodName, field.getType());
                    System.out.println(value);
                    //得到了set方法就可以调用了
                    //ConvertUtils.convert(value,field.getType())将值按照field下的属性的类型进行转换
                    //将数据库下的时间转换为Java下的时间
                    method.invoke(t, ConvertUtils.convert(value,field.getType()));
                }
                //将t添加到集合里
                list.add(t);
            }
            return list;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            this.closeAll();
        }
        return null;
    }
}

  • 商品类Goods
package cn.jazhong.model;
import java.util.Date;

public class Goods {
    private Integer g_id;
    private String g_name;
    private Double g_price;
    private Date g_date;

    public Goods(){

    }
    /**
     *方便增加数据
     */
    public Goods(String g_name, Double g_price, Date g_date) {
        this.g_name = g_name;
        this.g_price = g_price;
        this.g_date = g_date;
    }

    /**
     * 方便更新数据
     */
    public Goods(Integer g_id, String g_name, Double g_price, Date g_date) {
        this.g_id = g_id;
        this.g_name = g_name;
        this.g_price = g_price;
        this.g_date = g_date;
    }

    public Integer getG_id() {
        return g_id;
    }

    public void setG_id(Integer g_id) {
        this.g_id = g_id;
    }

    public String getG_name() {
        return g_name;
    }

    public void setG_name(String g_name) {
        this.g_name = g_name;
    }

    public Double getG_price() {
        return g_price;
    }

    public void setG_price(Double g_price) {
        this.g_price = g_price;
    }

    public Date getG_date() {
        return g_date;
    }
    
    public void setG_date(Date g_date) {
        this.g_date = g_date;
    }
}



三,servlet层

  • 中转站BaseServlet
package cn.jazhong.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 相当于中转占
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //设置编码集
            request.setCharacterEncoding("UTF-8");
            //获得客户端提交的参数该参数为servlet的方法名
            String operate = request.getParameter("operate");
            //通过反射获得方法对象
            Method method = this.getClass().getDeclaredMethod(operate, HttpServletRequest.class, HttpServletResponse.class);
            //调用方法
            method.invoke(this,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

  • 操作商品类GoodsServlet
package cn.jazhong.servlet;

import cn.jazhong.model.Goods;
import cn.jazhong.service.GoodsService;
import cn.jazhong.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@WebServlet("/goods.do")
public class GoodsServlet extends BaseServlet {
    private GoodsService goodsService=new GoodsServiceImpl();
    //查询全部商品
    protected void queryGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Goods> goodsList=goodsService.queryAll();
        request.setAttribute("goodsList",goodsList);
        request.getRequestDispatcher("showgoods.jsp").forward(request,response);
    }
    //查询单个商品
    protected void queryGoodsById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int g_id = Integer.parseInt(request.getParameter("g_id"));
        Goods goods=goodsService.queryOne(g_id);
        request.setAttribute("goods",goods);
        request.getRequestDispatcher("updategoods.jsp").forward(request,response);
    }
    //更新商品
    protected void updateGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        int g_id = Integer.parseInt(request.getParameter("g_id"));
        String g_name = request.getParameter("g_name");
        double g_price = Double.parseDouble(request.getParameter("g_price"));
        Date g_date = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("g_date"));
        Goods goods=new Goods(g_id,g_name,g_price,g_date);
        goodsService.updateOne(goods);
        response.sendRedirect("index.jsp");
    }
    //删除商品
    protected void delGoodsById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int g_id = Integer.parseInt(request.getParameter("g_id"));
        goodsService.deleteOne(g_id);
        response.sendRedirect("index.jsp");
    }
    //添加商品
    protected void insertGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        String g_name = request.getParameter("g_name");
        double g_price = Double.parseDouble(request.getParameter("g_price"));
        Date g_date = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("g_date"));
        Goods goods=new Goods(g_name,g_price,g_date);
        goodsService.insertOne(goods);
        response.sendRedirect("index.jsp");
    }
}

四,service层

  • 服务层接口GoodsService
package cn.jazhong.service;

import cn.jazhong.model.Goods;

import java.util.List;

public interface GoodsService {
    /**
     *查询全部商品信息
     */
    List<Goods> queryAll();
    /**
     *根据g_id查询单个商品信息
     */
    Goods queryOne(int g_id);
    /**
     *更改商品信息
     */
    void updateOne(Goods goods);
    /**
     *根据g_id删除商品信息
     */
    void deleteOne(int g_id);
    /**
     *添加商品信息
     */
    void insertOne(Goods goods);
}

  • 服务层接口的实现类GoodsServiceImpl
package cn.jazhong.service.impl;

import cn.jazhong.dao.GoodsDao;
import cn.jazhong.dao.impl.GoodsDaoImpl;
import cn.jazhong.model.Goods;
import cn.jazhong.service.GoodsService;

import java.util.List;

public class GoodsServiceImpl implements GoodsService {
    private GoodsDao goodsDao=new GoodsDaoImpl();
    /**
     *查询全部商品信息
     */
    @Override
    public List<Goods> queryAll() {
        return goodsDao.selectAll();
    }
    /**
     *根据g_id查询单个商品信息
     */
    @Override
    public Goods queryOne(int g_id) {
        return goodsDao.selectOne(g_id);
    }
    /**
     *更改商品信息
     */
    @Override
    public void updateOne(Goods goods) {
        goodsDao.update(goods);
    }
    /**
     *根据g_id删除商品信息
     */
    @Override
    public void deleteOne(int g_id) {
        goodsDao.delete(g_id);
    }
    /**
     *添加商品信息
     */
    @Override
    public void insertOne(Goods goods) {
        goodsDao.insert(goods);
    }
}

五,dao层

  • 操作层接口GoodsDao
package cn.jazhong.dao;

import cn.jazhong.model.Goods;

import java.util.List;

public interface GoodsDao {
    /**
     *对数据库查询全部商品信息
     */
    List<Goods> selectAll();
    /**
     *对数据库根据g_id查询单个商品信息
     */
    Goods selectOne(int g_id);
    /**
     *对数据库更新商品信息
     */
    void update(Goods goods);
    /**
     *对数据库根据g_id删除商品信息
     */
    void delete(int g_id);
    /**
     *对数据库插入商品信息
     */
    void insert(Goods goods);
}

  • 服务层接口的实现类GoodsDaoImpl
package cn.jazhong.dao.impl;

import cn.jazhong.dao.GoodsDao;
import cn.jazhong.model.DBUtil;
import cn.jazhong.model.Goods;

import java.util.List;

public class GoodsDaoImpl extends DBUtil implements GoodsDao {
    /**
     *对数据库查询全部商品信息
     */
    @Override
    public List<Goods> selectAll() {
        String sql="select * from tbl_goods";
        return super.excuteQuery(sql,Goods.class);
    }
    /**
     *对数据库根据g_id查询单个商品信息
     */
    @Override
    public Goods selectOne(int g_id) {
        String sql="select * from tbl_goods where g_id=?";
        List<Goods> goods=super.excuteQuery(sql,Goods.class,g_id);
        if (goods!=null&&goods.size()!=0){
            return goods.get(0);
        }
        return null;
    }
    /**
     *对数据库更新商品信息
     */
    @Override
    public void update(Goods goods) {
        String sql="update tbl_goods set g_name=?,g_price=?,g_date=? where g_id=?";
        super.myexecuteUpdate(sql,goods.getG_name(),goods.getG_price(),goods.getG_date(),goods.getG_id());
    }
    /**
     *对数据库根据g_id删除商品信息
     */
    @Override
    public void delete(int g_id) {
        String sql="delete from tbl_goods where g_id=?";
        super.myexecuteUpdate(sql,g_id);
    }
    /**
     *对数据库插入商品信息
     */
    @Override
    public void insert(Goods goods) {
        String sql="insert into tbl_goods values(default,?,?,?)";
        super.myexecuteUpdate(sql,goods.getG_name(),goods.getG_price(),goods.getG_date());
    }
}

六,界面操作的展示

  • 查询全部商品
    l流程

  • 查询单个商品并修改信息
    流程
    在这里插入图片描述
    流程

  • 删除商品
    流程
    流程

  • 添加商品信息
    流程
    流程
    流程



所属网站分类: 技术文章 > 博客

作者:coding

链接:http://www.javaheidong.com/blog/article/207418/8ce3977476b47dd84317/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

7 0
收藏该文
已收藏

评论内容:(最多支持255个字符)