第一级目录:src包,web包,pro07-javaweb-begin.iml
pro07-javaweb-begin.iml
- <module type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="web" name="Web">
- <configuration>
- <descriptors>
- <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/web/WEB-INF/web.xml" />
- descriptors>
- <webroots>
- <root url="file://$MODULE_DIR$/web" relative="/" />
- webroots>
- configuration>
- facet>
- component>
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
- content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" scope="PROVIDED" name="Tomcat 8.0.42" level="application_server_libraries" />
- <orderEntry type="library" name="lib" level="project" />
- component>
- module>
pro07-javaweb-begin.src.com.atguigu.fruit
pro07-javaweb-begin.src.com.atguigu.fruit.dao
pro07-javaweb-begin.src.com.atguigu.fruit.dao.base.BaseDAO.java
- package com.atguigu.fruit.dao.base;
-
- import java.lang.reflect.Field;
- import java.lang.reflect.ParameterizedType;
- import java.lang.reflect.Type;
- import java.sql.*;
- import java.util.ArrayList;
- import java.util.List;
-
- public abstract class BaseDAO
{ - public final String DRIVER = "com.mysql.jdbc.Driver" ;
- public final String URL = "jdbc:mysql://localhost:3306/fruitdb?useUnicode=true&characterEncoding=utf-8&useSSL=false";
- public final String USER = "root";
- public final String PWD = "123456" ;
-
- protected Connection conn ;
- protected PreparedStatement psmt ;
- protected ResultSet rs ;
-
- //T的Class对象
- private Class entityClass ;
-
- public BaseDAO(){
- //getClass() 获取Class对象,当前我们执行的是new FruitDAOImpl() , 创建的是FruitDAOImpl的实例
- //那么子类构造方法内部首先会调用父类(BaseDAO)的无参构造方法
- //因此此处的getClass()会被执行,但是getClass获取的是FruitDAOImpl的Class
- //所以getGenericSuperclass()获取到的是BaseDAO的Class
- Type genericType = getClass().getGenericSuperclass();
- //ParameterizedType 参数化类型
- Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
- //获取到的
中的T的真实的类型 - Type actualType = actualTypeArguments[0];
- try {
- entityClass = Class.forName(actualType.getTypeName());
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
-
- protected Connection getConn(){
- try {
- //1.加载驱动
- Class.forName(DRIVER);
- //2.通过驱动管理器获取连接对象
- return DriverManager.getConnection(URL, USER, PWD);
- } catch (ClassNotFoundException | SQLException e) {
- e.printStackTrace();
- }
- return null ;
- }
-
- protected void close(ResultSet rs , PreparedStatement psmt , Connection conn){
- try {
- if (rs != null) {
- rs.close();
- }
- if(psmt!=null){
- psmt.close();
- }
- if(conn!=null && !conn.isClosed()){
- conn.close();
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- //给预处理命令对象设置参数
- private void setParams(PreparedStatement psmt , Object... params) throws SQLException {
- if(params!=null && params.length>0){
- for (int i = 0; i < params.length; i++) {
- psmt.setObject(i+1,params[i]);
- }
- }
- }
-
- //执行更新,返回影响行数
- protected int executeUpdate(String sql , Object... params){
- boolean insertFlag = false ;
- insertFlag = sql.trim().toUpperCase().startsWith("INSERT");
- try {
- conn = getConn();
- if(insertFlag){
- psmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
- }else {
- psmt = conn.prepareStatement(sql);
- }
- setParams(psmt,params);
- int count = psmt.executeUpdate() ;
-
- rs = psmt.getGeneratedKeys();
- if(rs.next()){
- return ((Long)rs.getLong(1)).intValue();
- }
- return count ;
- } catch (SQLException e) {
- e.printStackTrace();
- }finally {
- close(rs,psmt,conn);
- }
- return 0;
- }
-
- //通过反射技术给obj对象的property属性赋propertyValue值
- private void setValue(Object obj , String property , Object propertyValue){
- Class clazz = obj.getClass();
- try {
- //获取property这个字符串对应的属性名 , 比如 "fid" 去找 obj对象中的 fid 属性
- Field field = clazz.getDeclaredField(property);
- if(field!=null){
- field.setAccessible(true);
- field.set(obj,propertyValue);
- }
- } catch (NoSuchFieldException | IllegalAccessException e) {
- e.printStackTrace();
- }
- }
-
- //执行复杂查询,返回例如统计结果
- protected Object[] executeComplexQuery(String sql , Object... params){
- try {
- conn = getConn() ;
- psmt = conn.prepareStatement(sql);
- setParams(psmt,params);
- rs = psmt.executeQuery();
-
- //通过rs可以获取结果集的元数据
- //元数据:描述结果集数据的数据 , 简单讲,就是这个结果集有哪些列,什么类型等等
-
- ResultSetMetaData rsmd = rs.getMetaData();
- //获取结果集的列数
- int columnCount = rsmd.getColumnCount();
- Object[] columnValueArr = new Object[columnCount];
- //6.解析rs
- if(rs.next()){
- for(int i = 0 ; i
- Object columnValue = rs.getObject(i+1); //33 苹果 5
- columnValueArr[i]=columnValue;
- }
- return columnValueArr ;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- close(rs,psmt,conn);
- }
- return null ;
- }
-
- //执行查询,返回单个实体对象
- protected T load(String sql , Object... params){
- try {
- conn = getConn() ;
- psmt = conn.prepareStatement(sql);
- setParams(psmt,params);
- rs = psmt.executeQuery();
-
- //通过rs可以获取结果集的元数据
- //元数据:描述结果集数据的数据 , 简单讲,就是这个结果集有哪些列,什么类型等等
-
- ResultSetMetaData rsmd = rs.getMetaData();
- //获取结果集的列数
- int columnCount = rsmd.getColumnCount();
- //6.解析rs
- if(rs.next()){
- T entity = (T)entityClass.newInstance();
-
- for(int i = 0 ; i
- String columnName = rsmd.getColumnName(i+1); //fid fname price
- Object columnValue = rs.getObject(i+1); //33 苹果 5
- setValue(entity,columnName,columnValue);
- }
- return entity ;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } finally {
- close(rs,psmt,conn);
- }
- return null ;
- }
-
-
- //执行查询,返回List
- protected List
executeQuery(String sql , Object... params){ - List
list = new ArrayList<>(); - try {
- conn = getConn() ;
- psmt = conn.prepareStatement(sql);
- setParams(psmt,params);
- rs = psmt.executeQuery();
-
- //通过rs可以获取结果集的元数据
- //元数据:描述结果集数据的数据 , 简单讲,就是这个结果集有哪些列,什么类型等等
-
- ResultSetMetaData rsmd = rs.getMetaData();
- //获取结果集的列数
- int columnCount = rsmd.getColumnCount();
- //6.解析rs
- while(rs.next()){
- T entity = (T)entityClass.newInstance();
-
- for(int i = 0 ; i
- String columnName = rsmd.getColumnName(i+1); //fid fname price
- Object columnValue = rs.getObject(i+1); //33 苹果 5
- setValue(entity,columnName,columnValue);
- }
- list.add(entity);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } finally {
- close(rs,psmt,conn);
- }
- return list ;
- }
- }
pro07-javaweb-begin.src.com.atguigu.fruit.dao.impl
- package com.atguigu.fruit.dao.impl;
-
- import com.atguigu.fruit.dao.FruitDAO;
- import com.atguigu.fruit.dao.base.BaseDAO;
- import com.atguigu.fruit.pojo.Fruit;
-
- import java.util.List;
-
- public class FruitDAOImpl extends BaseDAO<Fruit> implements FruitDAO {
- @Override
- public List<Fruit> getFruitList() {
- return super.executeQuery("select * from t_fruit");
- }
-
- @Override
- public boolean addFruit(Fruit fruit) {
- String sql = "insert into t_fruit values(null,?,?,?,?)";
- int count = super.executeUpdate(sql,fruit.getFname(),fruit.getPrice(),fruit.getFcount(),fruit.getRemark()) ;
- //insert语句返回的是自增列的值,而不是影响行数
- //System.out.println(count);
- return count>0;
- }
-
- @Override
- public boolean updateFruit(Fruit fruit) {
- String sql = "update t_fruit set fcount = ? where fid = ? " ;
- return super.executeUpdate(sql,fruit.getFcount(),fruit.getFid())>0;
- }
-
- @Override
- public Fruit getFruitByFname(String fname) {
- return super.load("select * from t_fruit where fname like ? ",fname);
- }
-
- @Override
- public boolean delFruit(String fname) {
- String sql = "delete from t_fruit where fname like ? " ;
- return super.executeUpdate(sql,fname)>0;
- }
- }
pro07-javaweb-begin.src.com.atguigu.fruit.dao.FruitDAO.java
- package com.atguigu.fruit.dao;
-
- import com.atguigu.fruit.pojo.Fruit;
-
- import java.util.List;
-
- public interface FruitDAO {
- //查询库存列表
- List
getFruitList(); -
- //新增库存
- boolean addFruit(Fruit fruit);
-
- //修改库存
- boolean updateFruit(Fruit fruit);
-
- //根据名称查询特定库存
- Fruit getFruitByFname(String fname);
-
- //删除特定库存记录
- boolean delFruit(String fname);
- }
pro07-javaweb-begin.src.com.atguigu.fruit.pojo.Fruit.java
- package com.atguigu.fruit.pojo;
-
- public class Fruit {
- private Integer fid ;
- private String fname ;
- private Integer price ;
- private Integer fcount ;
- private String remark ;
-
- public Fruit(){}
-
- public Fruit(Integer fid, String fname, Integer price, Integer fcount, String remark) {
- this.fid = fid;
- this.fname = fname;
- this.price = price;
- this.fcount = fcount;
- this.remark = remark;
- }
-
- public Integer getFid() {
- return fid;
- }
-
- public void setFid(Integer fid) {
- this.fid = fid;
- }
-
- public String getFname() {
- return fname;
- }
-
- public void setFname(String fname) {
- this.fname = fname;
- }
-
- public Integer getPrice() {
- return price;
- }
-
- public void setPrice(Integer price) {
- this.price = price;
- }
-
- public Integer getFcount() {
- return fcount;
- }
-
- public void setFcount(Integer fcount) {
- this.fcount = fcount;
- }
-
- public String getRemark() {
- return remark;
- }
-
- public void setRemark(String remark) {
- this.remark = remark;
- }
-
- @Override
- public String toString() {
- return fid + "\t\t" + fname + "\t\t" + price +"\t\t" + fcount +"\t\t" + remark ;
- }
- }
pro07-javaweb-begin.src.com.atguigu.servlets.AddServlet.java
- package com.atguigu.servlets;
-
- import com.atguigu.fruit.dao.FruitDAO;
- import com.atguigu.fruit.dao.impl.FruitDAOImpl;
- import com.atguigu.fruit.pojo.Fruit;
-
- 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(urlPatterns = "/Add")
- public class AddServlet extends HttpServlet {
- @Override
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- /*
- //get方式目前不需要设置编码(基于tomcat8)
- //如果是get请求发送的中文数据,转码稍微有点麻烦(tomcat8之前)
- String fname = request.getParameter("fname");
- //1.将得到的字符串打散成字节数组
- byte[] bytes = fname.getBytes("ISO-8859-1");
- //2.将字节数组按照设定的编码重新组装成字符串
- fname = new String(bytes,"UTF-8");
- */
- //post方式下,设置编码,防止中文乱码
- //需要注意的是,设置编码这一句代码必须在所有的获取参数动作之前
- request.setCharacterEncoding("UTF-8");
- String fname = request.getParameter("fname");
- String priceStr = request.getParameter("price");
- Integer price = Integer.parseInt(priceStr);
- String fcountStr = request.getParameter("fcount");
- Integer fcount = Integer.parseInt(fcountStr);
- String remark = request.getParameter("remark");
-
- FruitDAO fruitDAO = new FruitDAOImpl();
- boolean flag = fruitDAO.addFruit(new Fruit(0 , fname , price , fcount , remark));
-
- System.out.println(flag ? "添加成功!" : "添加失败!");
- }
- }
pro07-javaweb-begin.web.add.html
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Titletitle>
- head>
- <body>
- <form action="/Add" method="post">
- 名称:<input type="text" name="fname"/><br/>
- 价格:<input type="text" name="price"/><br/>
- 库存:<input type="text" name="fcount"/><br/>
- 备注:<input type="text" name="remark"/><br/>
- <input type="submit" value="添加" />
- form>
- body>
- html>
pro07-javaweb-begin.web.WEB-INF.web.xml
- <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
- version="4.0">
-
-
- web-app>
-
相关阅读:
vscode中运行脚手架项目报表
VUE快速入门-1
金九银十助力面试——手把手轻松读懂HashMap源码
生成式 AI 如何释放开发者的生产力?
Java中ArrayList集合中如何删除重复元素呢?
下载指定版本的pytorch
C/C++、Qt开发,跨平台CMake判断当前平台是Linux还是Windows,操作系统判断
【Elasticsearch】ES选主流程分析
圆锥曲线的分类
MySQL基础-----可视化工具DataGrip安装与使用
-
原文地址:https://blog.csdn.net/Mona_lxh/article/details/126235805