发布于2021-05-29 20:59 阅读(1234) 评论(0) 点赞(7) 收藏(2)
问题的引出:学了提升作用域request篇和response篇,EL表达式,jsp标签库,反射我们怎样去应用呢?
问题的解决:针对于数据的增删改查的浏览器界面化,我们对它们的实现进一步深入了解!
页内可跳转目录
一,jsp界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!--实现一进如界面就跳转至queryGoods.jsp界面-->
<jsp:forward page="/goods.do?operate=queryGoods"></jsp:forward>
<%@ 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>
<%@ 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>
<%@ 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>
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&¶ms.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&¶ms.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;
}
}
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;
}
}
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();
}
}
}
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");
}
}
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);
}
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);
}
}
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);
}
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());
}
}
查询全部商品
查询单个商品并修改信息
删除商品
添加商品信息
作者:coding
链接:http://www.javaheidong.com/blog/article/207418/8ce3977476b47dd84317/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!