• 第一个servlet项目:pro07-javaweb-begin


    第一级目录:src包,web包,pro07-javaweb-begin.iml

     pro07-javaweb-begin.iml

    1. <module type="JAVA_MODULE" version="4">
    2. <component name="FacetManager">
    3. <facet type="web" name="Web">
    4. <configuration>
    5. <descriptors>
    6. <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/web/WEB-INF/web.xml" />
    7. descriptors>
    8. <webroots>
    9. <root url="file://$MODULE_DIR$/web" relative="/" />
    10. webroots>
    11. configuration>
    12. facet>
    13. component>
    14. <component name="NewModuleRootManager" inherit-compiler-output="true">
    15. <exclude-output />
    16. <content url="file://$MODULE_DIR$">
    17. <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    18. content>
    19. <orderEntry type="inheritedJdk" />
    20. <orderEntry type="sourceFolder" forTests="false" />
    21. <orderEntry type="library" scope="PROVIDED" name="Tomcat 8.0.42" level="application_server_libraries" />
    22. <orderEntry type="library" name="lib" level="project" />
    23. component>
    24. 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

    1. package com.atguigu.fruit.dao.base;
    2. import java.lang.reflect.Field;
    3. import java.lang.reflect.ParameterizedType;
    4. import java.lang.reflect.Type;
    5. import java.sql.*;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. public abstract class BaseDAO {
    9. public final String DRIVER = "com.mysql.jdbc.Driver" ;
    10. public final String URL = "jdbc:mysql://localhost:3306/fruitdb?useUnicode=true&characterEncoding=utf-8&useSSL=false";
    11. public final String USER = "root";
    12. public final String PWD = "123456" ;
    13. protected Connection conn ;
    14. protected PreparedStatement psmt ;
    15. protected ResultSet rs ;
    16. //T的Class对象
    17. private Class entityClass ;
    18. public BaseDAO(){
    19. //getClass() 获取Class对象,当前我们执行的是new FruitDAOImpl() , 创建的是FruitDAOImpl的实例
    20. //那么子类构造方法内部首先会调用父类(BaseDAO)的无参构造方法
    21. //因此此处的getClass()会被执行,但是getClass获取的是FruitDAOImpl的Class
    22. //所以getGenericSuperclass()获取到的是BaseDAO的Class
    23. Type genericType = getClass().getGenericSuperclass();
    24. //ParameterizedType 参数化类型
    25. Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
    26. //获取到的中的T的真实的类型
    27. Type actualType = actualTypeArguments[0];
    28. try {
    29. entityClass = Class.forName(actualType.getTypeName());
    30. } catch (ClassNotFoundException e) {
    31. e.printStackTrace();
    32. }
    33. }
    34. protected Connection getConn(){
    35. try {
    36. //1.加载驱动
    37. Class.forName(DRIVER);
    38. //2.通过驱动管理器获取连接对象
    39. return DriverManager.getConnection(URL, USER, PWD);
    40. } catch (ClassNotFoundException | SQLException e) {
    41. e.printStackTrace();
    42. }
    43. return null ;
    44. }
    45. protected void close(ResultSet rs , PreparedStatement psmt , Connection conn){
    46. try {
    47. if (rs != null) {
    48. rs.close();
    49. }
    50. if(psmt!=null){
    51. psmt.close();
    52. }
    53. if(conn!=null && !conn.isClosed()){
    54. conn.close();
    55. }
    56. } catch (SQLException e) {
    57. e.printStackTrace();
    58. }
    59. }
    60. //给预处理命令对象设置参数
    61. private void setParams(PreparedStatement psmt , Object... params) throws SQLException {
    62. if(params!=null && params.length>0){
    63. for (int i = 0; i < params.length; i++) {
    64. psmt.setObject(i+1,params[i]);
    65. }
    66. }
    67. }
    68. //执行更新,返回影响行数
    69. protected int executeUpdate(String sql , Object... params){
    70. boolean insertFlag = false ;
    71. insertFlag = sql.trim().toUpperCase().startsWith("INSERT");
    72. try {
    73. conn = getConn();
    74. if(insertFlag){
    75. psmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
    76. }else {
    77. psmt = conn.prepareStatement(sql);
    78. }
    79. setParams(psmt,params);
    80. int count = psmt.executeUpdate() ;
    81. rs = psmt.getGeneratedKeys();
    82. if(rs.next()){
    83. return ((Long)rs.getLong(1)).intValue();
    84. }
    85. return count ;
    86. } catch (SQLException e) {
    87. e.printStackTrace();
    88. }finally {
    89. close(rs,psmt,conn);
    90. }
    91. return 0;
    92. }
    93. //通过反射技术给obj对象的property属性赋propertyValue值
    94. private void setValue(Object obj , String property , Object propertyValue){
    95. Class clazz = obj.getClass();
    96. try {
    97. //获取property这个字符串对应的属性名 , 比如 "fid" 去找 obj对象中的 fid 属性
    98. Field field = clazz.getDeclaredField(property);
    99. if(field!=null){
    100. field.setAccessible(true);
    101. field.set(obj,propertyValue);
    102. }
    103. } catch (NoSuchFieldException | IllegalAccessException e) {
    104. e.printStackTrace();
    105. }
    106. }
    107. //执行复杂查询,返回例如统计结果
    108. protected Object[] executeComplexQuery(String sql , Object... params){
    109. try {
    110. conn = getConn() ;
    111. psmt = conn.prepareStatement(sql);
    112. setParams(psmt,params);
    113. rs = psmt.executeQuery();
    114. //通过rs可以获取结果集的元数据
    115. //元数据:描述结果集数据的数据 , 简单讲,就是这个结果集有哪些列,什么类型等等
    116. ResultSetMetaData rsmd = rs.getMetaData();
    117. //获取结果集的列数
    118. int columnCount = rsmd.getColumnCount();
    119. Object[] columnValueArr = new Object[columnCount];
    120. //6.解析rs
    121. if(rs.next()){
    122. for(int i = 0 ; i
    123. Object columnValue = rs.getObject(i+1); //33 苹果 5
    124. columnValueArr[i]=columnValue;
    125. }
    126. return columnValueArr ;
    127. }
    128. } catch (SQLException e) {
    129. e.printStackTrace();
    130. } finally {
    131. close(rs,psmt,conn);
    132. }
    133. return null ;
    134. }
    135. //执行查询,返回单个实体对象
    136. protected T load(String sql , Object... params){
    137. try {
    138. conn = getConn() ;
    139. psmt = conn.prepareStatement(sql);
    140. setParams(psmt,params);
    141. rs = psmt.executeQuery();
    142. //通过rs可以获取结果集的元数据
    143. //元数据:描述结果集数据的数据 , 简单讲,就是这个结果集有哪些列,什么类型等等
    144. ResultSetMetaData rsmd = rs.getMetaData();
    145. //获取结果集的列数
    146. int columnCount = rsmd.getColumnCount();
    147. //6.解析rs
    148. if(rs.next()){
    149. T entity = (T)entityClass.newInstance();
    150. for(int i = 0 ; i
    151. String columnName = rsmd.getColumnName(i+1); //fid fname price
    152. Object columnValue = rs.getObject(i+1); //33 苹果 5
    153. setValue(entity,columnName,columnValue);
    154. }
    155. return entity ;
    156. }
    157. } catch (SQLException e) {
    158. e.printStackTrace();
    159. } catch (IllegalAccessException e) {
    160. e.printStackTrace();
    161. } catch (InstantiationException e) {
    162. e.printStackTrace();
    163. } finally {
    164. close(rs,psmt,conn);
    165. }
    166. return null ;
    167. }
    168. //执行查询,返回List
    169. protected List executeQuery(String sql , Object... params){
    170. List list = new ArrayList<>();
    171. try {
    172. conn = getConn() ;
    173. psmt = conn.prepareStatement(sql);
    174. setParams(psmt,params);
    175. rs = psmt.executeQuery();
    176. //通过rs可以获取结果集的元数据
    177. //元数据:描述结果集数据的数据 , 简单讲,就是这个结果集有哪些列,什么类型等等
    178. ResultSetMetaData rsmd = rs.getMetaData();
    179. //获取结果集的列数
    180. int columnCount = rsmd.getColumnCount();
    181. //6.解析rs
    182. while(rs.next()){
    183. T entity = (T)entityClass.newInstance();
    184. for(int i = 0 ; i
    185. String columnName = rsmd.getColumnName(i+1); //fid fname price
    186. Object columnValue = rs.getObject(i+1); //33 苹果 5
    187. setValue(entity,columnName,columnValue);
    188. }
    189. list.add(entity);
    190. }
    191. } catch (SQLException e) {
    192. e.printStackTrace();
    193. } catch (IllegalAccessException e) {
    194. e.printStackTrace();
    195. } catch (InstantiationException e) {
    196. e.printStackTrace();
    197. } finally {
    198. close(rs,psmt,conn);
    199. }
    200. return list ;
    201. }
    202. }

    pro07-javaweb-begin.src.com.atguigu.fruit.dao.impl

    1. package com.atguigu.fruit.dao.impl;
    2. import com.atguigu.fruit.dao.FruitDAO;
    3. import com.atguigu.fruit.dao.base.BaseDAO;
    4. import com.atguigu.fruit.pojo.Fruit;
    5. import java.util.List;
    6. public class FruitDAOImpl extends BaseDAO<Fruit> implements FruitDAO {
    7. @Override
    8. public List<Fruit> getFruitList() {
    9. return super.executeQuery("select * from t_fruit");
    10. }
    11. @Override
    12. public boolean addFruit(Fruit fruit) {
    13. String sql = "insert into t_fruit values(null,?,?,?,?)";
    14. int count = super.executeUpdate(sql,fruit.getFname(),fruit.getPrice(),fruit.getFcount(),fruit.getRemark()) ;
    15. //insert语句返回的是自增列的值,而不是影响行数
    16. //System.out.println(count);
    17. return count>0;
    18. }
    19. @Override
    20. public boolean updateFruit(Fruit fruit) {
    21. String sql = "update t_fruit set fcount = ? where fid = ? " ;
    22. return super.executeUpdate(sql,fruit.getFcount(),fruit.getFid())>0;
    23. }
    24. @Override
    25. public Fruit getFruitByFname(String fname) {
    26. return super.load("select * from t_fruit where fname like ? ",fname);
    27. }
    28. @Override
    29. public boolean delFruit(String fname) {
    30. String sql = "delete from t_fruit where fname like ? " ;
    31. return super.executeUpdate(sql,fname)>0;
    32. }
    33. }

    pro07-javaweb-begin.src.com.atguigu.fruit.dao.FruitDAO.java

    1. package com.atguigu.fruit.dao;
    2. import com.atguigu.fruit.pojo.Fruit;
    3. import java.util.List;
    4. public interface FruitDAO {
    5. //查询库存列表
    6. List getFruitList();
    7. //新增库存
    8. boolean addFruit(Fruit fruit);
    9. //修改库存
    10. boolean updateFruit(Fruit fruit);
    11. //根据名称查询特定库存
    12. Fruit getFruitByFname(String fname);
    13. //删除特定库存记录
    14. boolean delFruit(String fname);
    15. }

    pro07-javaweb-begin.src.com.atguigu.fruit.pojo.Fruit.java

    1. package com.atguigu.fruit.pojo;
    2. public class Fruit {
    3. private Integer fid ;
    4. private String fname ;
    5. private Integer price ;
    6. private Integer fcount ;
    7. private String remark ;
    8. public Fruit(){}
    9. public Fruit(Integer fid, String fname, Integer price, Integer fcount, String remark) {
    10. this.fid = fid;
    11. this.fname = fname;
    12. this.price = price;
    13. this.fcount = fcount;
    14. this.remark = remark;
    15. }
    16. public Integer getFid() {
    17. return fid;
    18. }
    19. public void setFid(Integer fid) {
    20. this.fid = fid;
    21. }
    22. public String getFname() {
    23. return fname;
    24. }
    25. public void setFname(String fname) {
    26. this.fname = fname;
    27. }
    28. public Integer getPrice() {
    29. return price;
    30. }
    31. public void setPrice(Integer price) {
    32. this.price = price;
    33. }
    34. public Integer getFcount() {
    35. return fcount;
    36. }
    37. public void setFcount(Integer fcount) {
    38. this.fcount = fcount;
    39. }
    40. public String getRemark() {
    41. return remark;
    42. }
    43. public void setRemark(String remark) {
    44. this.remark = remark;
    45. }
    46. @Override
    47. public String toString() {
    48. return fid + "\t\t" + fname + "\t\t" + price +"\t\t" + fcount +"\t\t" + remark ;
    49. }
    50. }

    pro07-javaweb-begin.src.com.atguigu.servlets.AddServlet.java

    1. package com.atguigu.servlets;
    2. import com.atguigu.fruit.dao.FruitDAO;
    3. import com.atguigu.fruit.dao.impl.FruitDAOImpl;
    4. import com.atguigu.fruit.pojo.Fruit;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.IOException;
    11. @WebServlet(urlPatterns = "/Add")
    12. public class AddServlet extends HttpServlet {
    13. @Override
    14. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    15. /*
    16. //get方式目前不需要设置编码(基于tomcat8)
    17. //如果是get请求发送的中文数据,转码稍微有点麻烦(tomcat8之前)
    18. String fname = request.getParameter("fname");
    19. //1.将得到的字符串打散成字节数组
    20. byte[] bytes = fname.getBytes("ISO-8859-1");
    21. //2.将字节数组按照设定的编码重新组装成字符串
    22. fname = new String(bytes,"UTF-8");
    23. */
    24. //post方式下,设置编码,防止中文乱码
    25. //需要注意的是,设置编码这一句代码必须在所有的获取参数动作之前
    26. request.setCharacterEncoding("UTF-8");
    27. String fname = request.getParameter("fname");
    28. String priceStr = request.getParameter("price");
    29. Integer price = Integer.parseInt(priceStr);
    30. String fcountStr = request.getParameter("fcount");
    31. Integer fcount = Integer.parseInt(fcountStr);
    32. String remark = request.getParameter("remark");
    33. FruitDAO fruitDAO = new FruitDAOImpl();
    34. boolean flag = fruitDAO.addFruit(new Fruit(0 , fname , price , fcount , remark));
    35. System.out.println(flag ? "添加成功!" : "添加失败!");
    36. }
    37. }

    pro07-javaweb-begin.web.add.html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. head>
    7. <body>
    8. <form action="/Add" method="post">
    9. 名称:<input type="text" name="fname"/><br/>
    10. 价格:<input type="text" name="price"/><br/>
    11. 库存:<input type="text" name="fcount"/><br/>
    12. 备注:<input type="text" name="remark"/><br/>
    13. <input type="submit" value="添加" />
    14. form>
    15. body>
    16. html>

    pro07-javaweb-begin.web.WEB-INF.web.xml

    1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    4. version="4.0">
    5. 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