Use the javaweb project to realize the operation of adding, deleting, modifying and checking the database

1. What is javaweb

 

JavaWeb refers to the technology of using Java language for web application development. Java can be used to write some dynamic web pages, interactive web pages, enterprise-level applications, etc. JavaWeb technology mainly includes Servlet, JSP, JDBC, JavaBean, JNDI, EJB, Web Services, etc.

Servlet is one of the core components of JavaWeb technology. It is a Java program running on a Web server that can receive HTTP requests and return HTTP responses. It is often used to implement controllers or middleware in Web applications. Through Servlet, we can process the form data submitted by the user, query the database, call other services and other operations, and return the results to the client browser.

JSP (JavaServer Pages) is another important JavaWeb technology. It is a technology that embeds Java code in HTML pages and can generate dynamic Web pages. JSP files are compiled into Servlets on the Web server and executed when requested by the client. In JSP, we can use Java code, JSTL tag library and EL expressions to process data and logic, so as to realize the rendering of dynamic pages.

JDBC (Java Database Connectivity) is an API provided by Java to access relational databases based on standard SQL language, which can facilitate database connection, query, update and other operations. In Java web applications, we usually use JDBC to interact with the database and get the required data.

JavaBean is a special Java class, which usually contains some properties and methods, and follows a specific naming convention. In JavaWeb applications, we can define JavaBean objects to encapsulate data and business logic, and use them in JSP or Servlet to realize the functions of the model layer.

In short, JavaWeb technology is a Web application development technology based on the Java language, which provides rich APIs and components, and can easily realize functions such as dynamic web pages and enterprise-level applications.

2. How to use javaweb

Project display:

1. Database creation

#判断存在即删除数据库
drop database if exists mydb;
#创建数据库
create database mydb;
#使用数据库
use mydb;


#创建表
create table t_user
(
	uid int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	phone varchar(11),
	address varchar(50)
);


insert into t_user(username,password,phone,address) values('张三','666','18965423548','南阳');
insert into t_user(username,password,phone,address) values('李四','333','18754263548','许昌');
insert into t_user(username,password,phone,address) values('小美','123','18565234759','信阳');

select * from t_user where username=? and password=?
select * from t_user;
select * from t_goods


create table t_goods
(
	gid int primary key auto_increment,
	gname varchar(20),
	price double,
	mark varchar(100)
);


DROP TABLE t_goods;

TRUNCATE TABLE t_goods;


insert into t_goods(gname,price,mark) values('泡面',4.5,'够香够辣就是这个味!');
insert into t_goods(gname,price,mark) values('火腿',8.5,'肉质细腻Q弹!');
insert into t_goods(gname,price,mark) values('雪碧',3.5,'清爽冰凉随心爽!');

select * from t_goods where gid=1

update t_goods set gname='3',price=4.3,mark='5'  where gid=1

select * from t_goods;

2. Hierarchical structure

Herald

code part: 

Bean layer

Commodity entity class

package com.liu.Bean;

public class Goods {

    private Integer gid;
    private String gname;
    private Double price;
    private String mark;

    public Integer getGid() {
        return gid;
    }

    public void setGid(Integer gid) {
        this.gid = gid;
    }

    public String getGname() {
        return gname;
    }

    public void setGname(String gname) {
        this.gname = gname;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    @Override
    public String toString() {
        return "Good{" +
                "gid=" + gid +
                ", gname='" + gname + '\'' +
                ", price=" + price +
                ", mark='" + mark + '\'' +
                '}';
    }
}

User entity class:

package com.liu.Bean;

public class User {
    private Integer uid;
    private String username;
    private String password;
    private String phone;
    private String address;

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Database operation part

util layer

package com.liu.util;

import java.sql.*;

public class JDBCUtil {
    static String driver = "com.mysql.cj.jdbc.Driver"; // 定义数据库驱动程序名称
    static String url = "jdbc:mysql:///mydb?useSSL=false&serverTimezone=UTC"; // 定义数据库连接URL
    static String username = "root"; // 定义数据库用户名
    static String password = "root"; // 定义数据库密码
    static Connection conn = null; // 声明Connection对象

    /**
     * 获取数据库连接对象
     * @return 数据库连接对象
     */
    public static Connection getCon(){
        try {
            Class.forName(driver); // 加载数据库驱动程序
            conn = DriverManager.getConnection(url,username,password); // 获取数据库连接对象
        } catch (Exception e) { // 处理异常
            throw new RuntimeException(e);
        }
        return conn; // 返回数据库连接对象
    }

    /**
     * 关闭ResultSet、PreparedStatement和Connection对象
     * @param rs ResultSet对象
     * @param pstm PreparedStatement对象
     * @param conn Connection对象
     * @throws SQLException SQL异常
     */
    public static void colse(ResultSet rs, PreparedStatement pstm,Connection conn) throws SQLException {
        if (rs != null) { // 判断ResultSet对象是否为null
            rs.close(); // 关闭ResultSet对象
        }
        if (pstm != null){ // 判断PreparedStatement对象是否为null
            pstm.close(); // 关闭PreparedStatement对象
        }
        if (conn != null){ // 判断Connection对象是否为null
            conn.close(); // 关闭Connection对象
        }
    }

    /**
     * 关闭PreparedStatement和Connection对象
     * @param pstm PreparedStatement对象
     * @param conn Connection对象
     * @throws SQLException SQL异常
     */
    public static void colse(PreparedStatement pstm,Connection conn) throws SQLException {
        if (pstm != null){ // 判断PreparedStatement对象是否为null
            pstm.close(); // 关闭PreparedStatement对象
        }
        if (conn != null){ // 判断Connection对象是否为null
            conn.close(); // 关闭Connection对象
        }
    }
}

dao layer

package com.liu.dao.impl;

import com.liu.Bean.Goods;
import com.liu.util.JDBCUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class GoodsDao {
    Goods goods = null; // 定义Goods对象
    Connection con = null; // 数据库连接对象
    PreparedStatement pstm = null; // 预编译语句对象
    ResultSet rs = null; // 结果集对象
    int twe = 0; // 操作结果

    /**
     * 查询所有商品信息
     * @return 商品列表
     */
    public List<Goods> shopping() {
        List<Goods> goodsList =new ArrayList<>(); // 创建商品列表
        try {
            con = JDBCUtil.getCon(); // 获取数据库连接
            String sql = "select  * from t_goods"; // SQL查询语句
            pstm = con.prepareStatement(sql); // 建立预编译语句
            rs = pstm.executeQuery(); // 执行查询操作
            while (rs.next()) { // 遍历结果集
                Goods goods = new Goods(); // 创建商品对象
                goods.setGid(rs.getInt("gid")); // 设置商品ID
                goods.setGname(rs.getString("gname")); // 设置商品名称
                goods.setPrice(rs.getDouble("price")); // 设置商品价格
                goods.setMark(rs.getString("mark")); // 设置商品备注
                goodsList.add(goods); // 将商品添加到列表中
            }
            for (Goods goods1 : goodsList) { // 遍历商品列表
                System.out.println(goods1); // 输出商品信息
            }

        } catch (Exception e) { // 处理异常
            e.printStackTrace();
        } finally { // 关闭资源
            try {
                JDBCUtil.colse(rs, pstm, con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return goodsList; // 返回商品列表
    }

    /**
     * 添加商品信息
     * @param goods 商品对象
     * @return 操作结果
     */
    public int tianjia(Goods goods){
        con = JDBCUtil.getCon(); // 获取数据库连接
        String sql = "insert into t_goods(gname,price,mark)values(?,?,?)"; // SQL插入语句
        try {
            pstm = con.prepareStatement(sql); // 建立预编译语句
            pstm.setObject(1,goods.getGname()); // 设置商品名称
            pstm.setObject(2,goods.getPrice()); // 设置商品价格
            pstm.setObject(3,goods.getMark()); // 设置商品备注
            twe = pstm.executeUpdate(); // 执行插入操作
        } catch (Exception e) { // 处理异常
            e.printStackTrace();
        }finally { // 关闭资源
            try {
                JDBCUtil.colse(pstm,con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return twe; // 返回操作结果
    }

    /**
     * 删除商品信息
     * @param id 商品ID
     * @return 操作结果
     */
    public int shanchu(int id){
        con = JDBCUtil.getCon(); // 获取数据库连接
        String sql = "delete from t_goods where gid = ?"; // SQL删除语句
        try {
            pstm = con.prepareStatement(sql); // 建立预编译语句
            pstm.setObject(1,id); // 设置商品ID
            twe = pstm.executeUpdate(); // 执行删除操作
        } catch (Exception e) { // 处理异常
            e.printStackTrace();
        }finally { // 关闭资源
            try {
                JDBCUtil.colse(pstm,con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(twe);
        return twe; // 返回操作结果
    }

    /**
     * 查询指定商品信息
     * @param gid 商品ID
     * @return 商品对象
     */
    public Goods xiugai1(int gid){
        Goods goods = null; // 创建商品对象
        con = JDBCUtil.getCon(); // 获取数据库连接
        String sql = "select  * from t_goods where gid = ?"; // SQL查询语句
        try {
            pstm = con.prepareStatement(sql); // 建立预编译语句
            pstm.setObject(1,gid); // 设置商品ID
            con = JDBCUtil.getCon();
            // 获取数据库连接
            rs = pstm.executeQuery(); // 执行查询操作
            if (rs.next()) { // 判断结果集是否有数据
                goods = new Goods(); // 创建商品对象
                goods.setGid(rs.getInt("gid")); // 设置商品ID
                goods.setGname(rs.getString("gname")); // 设置商品名称
                goods.setPrice(rs.getDouble("price")); // 设置商品价格
                goods.setMark(rs.getString("mark")); // 设置商品备注
            }
            System.out.println(goods); // 输出商品信息
        } catch (Exception e) { // 处理异常
            e.printStackTrace();
        } finally { // 关闭资源
            try {
                JDBCUtil.colse(rs, pstm, con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return goods; // 返回商品对象
    }

    /**
     * 修改商品信息
     * @param goods 商品对象
     * @return 操作结果
     */
    public int xiugai2(Goods goods){
        System.out.println(goods); // 输出商品信息
        con = JDBCUtil.getCon(); // 获取数据库连接
        String sql = "update t_goods set gname=?,price=?,mark=? where gid = ?"; // SQL更新语句
        try {
            pstm = con.prepareStatement(sql); // 建立预编译语句
            pstm.setObject(1,goods.getGname()); // 设置商品名称
            pstm.setObject(2,goods.getPrice()); // 设置商品价格
            pstm.setObject(3,goods.getMark()); // 设置商品备注
            pstm.setObject(4,goods.getGid()); // 设置商品ID
            twe = pstm.executeUpdate(); // 执行更新操作
        } catch (Exception e) { // 处理异常
            e.printStackTrace();
        }finally { // 关闭资源
            try {
                JDBCUtil.colse(pstm,con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return twe; // 返回操作结果
    }

    /**
     * 模糊查询商品信息
     * @param n 商品名称关键字
     * @return 商品列表
     */
    public List<Goods> mohuchaxun(String n){
        List<Goods> goodsList =new ArrayList<>(); // 创建商品列表
        try {
            con = JDBCUtil.getCon(); // 获取数据库连接
            String sql = "select  * from t_goods where gname like concat('%',?,'%')"; // SQL模糊查询语句
            pstm = con.prepareStatement(sql); // 建立预编译语句
            pstm.setObject(1,n); // 设置商品名称关键字
            rs = pstm.executeQuery(); // 执行查询操作
            while (rs.next()) { // 遍历结果集
                Goods goods = new Goods(); // 创建商品对象
                goods.setGid(rs.getInt("gid")); // 设置商品ID
                goods.setGname(rs.getString("gname")); // 设置商品名称
                goods.setPrice(rs.getDouble("price")); // 设置商品价格
                goods.setMark(rs.getString("mark")); // 设置商品备注
                goodsList.add(goods); // 将商品添加到列表中
            }
            for (Goods goods1 : goodsList) { // 遍历商品列表
                System.out.println(goods1); // 输出商品信息
            }

        } catch (Exception e) { // 处理异常
            e.printStackTrace();
        } finally { // 关闭资源
            try {
                JDBCUtil.colse(rs, pstm, con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return goodsList; // 返回商品列表
    }
}

package com.liu.dao.impl;

import com.liu.Bean.User;
import com.liu.dao.UserDao;
import com.liu.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaolmpl implements UserDao {
    Connection con = null; // 数据库连接对象
    User user = null; // 用户对象
    PreparedStatement pstm = null; // 预编译语句对象
    ResultSet rs = null; // 结果集对象
    int row = 0; // 操作结果

    // 实现用户登录功能
    public User Login(String username,String password){
        con = JDBCUtil.getCon(); // 获取数据库连接
        String sql = "select * from t_user where username = ? and password = ?"; // SQL查询语句
        try {
            pstm = con.prepareStatement(sql); // 建立预编译语句
            pstm.setObject(1,username); // 设置第一个占位符的值为用户名
            pstm.setObject(2,password); // 设置第二个占位符的值为密码

            rs = pstm.executeQuery(); // 执行查询操作
            if (rs.next()) { // 如果存在用户,则将查询结果存放到User对象中
                user = new User();
                user.setUid(rs.getInt("uid")); // 设置User对象的id属性
                user.setUsername(rs.getString("username")); // 设置User对象的用户名属性
                user.setPassword(rs.getString("password")); // 设置User对象的密码属性
                user.setPhone(rs.getString("phone")); // 设置User对象的电话号码属性
                user.setAddress(rs.getString("address")); // 设置User对象的地址属性

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                JDBCUtil.colse(rs,pstm,con); // 关闭ResultSet、PreparedStatement和Connection对象
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user; // 返回User对象
    }

    // 实现用户注册功能
    public int register(User user){
        con = JDBCUtil.getCon(); // 获取数据库连接
        String sql = "insert into t_user(username,password,phone,address)value(?,?,?,?)"; // SQL插入语句
        try {
            pstm = con.prepareStatement(sql); // 建立预编译语句
            pstm.setObject(1,user.getUsername()); // 设置第一个占位符的值为用户名
            pstm.setObject(2,user.getPassword()); // 设置第二个占位符的值为密码
            pstm.setObject(3,user.getPhone()); // 设置第三个占位符的值为电话号码
            pstm.setObject(4,user.getAddress()); // 设置第四个占位符的值为地址
            row = pstm.executeUpdate(); // 执行插入操作
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                JDBCUtil.colse(pstm,con); // 关闭PreparedStatement和Connection对象
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return row; // 返回操作结果
    }
}

dao layer interface:

package com.liu.dao;

import com.liu.Bean.User;

public interface UserDao {
    User Login(String username,String password);
    int register(User user);
}

Filter layer (filter)

package com.liu.Filter;

import com.liu.Bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class Filters implements Filter {
    // 初始化方法
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化.........");
    }

    // 过滤方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest; // 转换ServletRequest为HttpServletRequest对象
        HttpServletResponse response = (HttpServletResponse) servletResponse; // 转换ServletResponse为HttpServletResponse对象

        String servletPath = request.getServletPath(); // 获取Servlet路径
        System.out.println(servletPath);

        HttpSession session = request.getSession(); // 获取Session对象
        User user = (User)session.getAttribute("user"); // 从Session中获取User对象
        System.out.println(user);

        if (servletPath.equals("/index.jsp") || servletPath.equals("/login.jsp") || servletPath.equals("/login") ||
                servletPath.equals("/register.jsp") || servletPath.equals("/register")){ // 允许访问的页面
            filterChain.doFilter(servletRequest,servletResponse); // 放行请求
        } else if (user != null) { // 如果用户已登录,则放行请求
            filterChain.doFilter(servletRequest,servletResponse);
        }else { // 否则重定向到登录页面
            response.sendRedirect("login.jsp");
        }
    }

    // 销毁方法
    @Override
    public void destroy() {
        System.out.println("销毁.........");
    }
}

servlet layer

package com.liu.servlet;

import com.liu.Bean.User;
import com.liu.dao.impl.UserDaolmpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/long")
public class Login extends HttpServlet {
    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8"); // 设置响应编码
        request.setCharacterEncoding("utf-8"); // 设置请求编码

        response.setContentType("text/html;charset = utf-8"); // 设置响应类型

        String username = request.getParameter("username"); // 获取用户名
        String password = request.getParameter("password"); // 获取密码

        UserDaolmpl userDaolmpl = new UserDaolmpl(); // 创建UserDaoImpl对象
        User loging = userDaolmpl.Login(username,password); // 调用Login()方法进行登录校验,并返回User对象
        System.out.println(loging);

        if (loging != null){ // 如果登录成功,则将User对象存储到Session中,并重定向到商品列表Servlet
            HttpSession session = request.getSession();
            session.setAttribute("user",loging);
            request.getRequestDispatcher("ServletAllGoods").forward(request,response);
        }else { // 否则重定向到错误页面
            response.sendRedirect("error.jsp");
        }
    }
}

 This class implements the HttpServlet interface and provides the user login function. In the doPost() method, first set the request encoding, response encoding and response type, then obtain the user name and password, create a UserDaoImpl object, and call the Login() method for login verification. If the login is successful, store the User object in the Session and redirect to the product list Servlet; otherwise, redirect to the error page. When implementing the Servlet, it is necessary to pay attention to setting information such as request encoding, response encoding, and response type, and to process the User object and Session object returned by the Login() method.

package com.liu.servlet;

import com.liu.Bean.Goods;
import com.liu.dao.impl.GoodsDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/mohu")
public class Mohu extends HttpServlet {
    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8"); // 设置响应编码
        request.setCharacterEncoding("utf-8"); // 设置请求编码

        GoodsDao goodsDao = new GoodsDao(); // 创建GoodsDao对象
        String sousuo = request.getParameter("sousuo"); // 获取查询关键字
        System.out.println(sousuo);
        List<Goods> goodsList = goodsDao.mohuchaxun(sousuo); // 调用模糊查询方法进行查询,并返回查询结果列表
        System.out.println(goodsList);
        HttpSession session = request.getSession(); // 获取Session对象
        session.setAttribute("shopping",goodsList); // 将查询结果存储到Session中
        response.sendRedirect("goods.jsp"); // 重定向到商品列表页面
    }
}

This class implements the HttpServlet interface and provides the fuzzy query function of commodities. In the doPost() method, first set the request code and response code, then create the GoodsDao object and get the query keyword, call the fuzzy query method to query, store the query result in the Session, and finally redirect to the product list page. When implementing the Servlet, it is necessary to pay attention to setting information such as request encoding, response encoding, and query keywords, and to process the query result list and Session object returned by the fuzzy query method.

package com.liu.servlet;

import com.liu.Bean.User;
import com.liu.dao.impl.UserDaolmpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/register")
public class Register extends HttpServlet {
    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User(); // 创建User对象
        String username = request.getParameter("username"); // 获取用户名
        String password = request.getParameter("password"); // 获取密码
        String phone = request.getParameter("phone"); // 获取电话号码
        String address = request.getParameter("address"); // 获取地址
        user.setUsername(username); // 设置用户名
        user.setPassword(password); // 设置密码
        user.setPhone(phone); // 设置电话号码
        user.setAddress(address); // 设置地址
        System.out.println(user);

        UserDaolmpl userDaolmpl = new UserDaolmpl();  // 创建 UserDaoImpl 对象
        int row = userDaolmpl.register(user);  // 调用 UserDaoImpl 中的 register() 方法进行注册,返回受影响行数
        System.out.println(row);  // 输出注册结果

        if (row > 0){ // 如果注册成功,则重定向到登录页面
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }else{ // 否则重定向到注册页面
            response.sendRedirect("register.jsp");
        }
    }
}

This class implements the HttpServlet interface and provides the user registration function. In the doPost() method, first create a User object and obtain information such as user name, password, phone number, and address, then set the User object properties and output to the console, create a UserDaoImpl object, and call the register() method to register, and return Affected rows. If the registration is successful, redirect to the login page; otherwise, redirect to the registration page. When implementing the Servlet, you need to pay attention to setting the User object attribute, processing the return value of the register () method, and redirecting to the correct page and other information. 

package com.liu.servlet;

import com.liu.Bean.Goods;
import com.liu.dao.impl.GoodsDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/ServletAllGoods")
public class ServletAllGoods extends HttpServlet {
    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GoodsDao goodsDao = new GoodsDao(); // 创建GoodsDao对象
        List<Goods> shopping = goodsDao.shopping(); // 调用查找所有商品方法,返回查询结果列表
        System.out.println(shopping);
        HttpSession httpSession = request.getSession(); // 获取Session对象
        httpSession.setAttribute("shopping",shopping); // 将查询结果存储到Session中
        response.sendRedirect("goods.jsp"); // 重定向到商品列表页面
    }
}

This class implements the HttpServlet interface and provides the function of finding all commodities. In the doPost() method, first create a GoodsDao object and call the method of finding all products to obtain the product list; then store the product list in the Session object, and finally redirect to the product list page. When implementing the Servlet, you need to pay attention to processing information such as the query result list and the Session object. 

package com.liu.servlet;

import com.liu.Bean.Goods;
import com.liu.dao.impl.GoodsDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/shanchu")
public class Shanchu extends HttpServlet {
    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int gid = Integer.parseInt(request.getParameter("gid")); // 获取商品ID
        GoodsDao goodsDao =new GoodsDao(); // 创建GoodsDao对象
        int i = goodsDao.shanchu(gid); // 调用删除商品方法,返回受影响行数
        if (i>0){ // 如果删除成功,则重定向到商品列表Servlet
            request.getRequestDispatcher("ServletAllGoods").forward(request,response);
        }else { // 否则转发到错误页面并输出错误信息
            request.setAttribute("error_msg","删除失败!!!");
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }
}

This class implements the HttpServlet interface and provides the function of commodity deletion. In the doPost() method, first obtain the product ID, create a GoodsDao object and call the delete product method, and return the number of affected rows. If the deletion is successful, redirect to the product list Servlet; otherwise, forward to the error page and output the error message. When implementing the Servlet, you need to pay attention to processing information such as product ID and deletion result, and redirecting or forwarding to the correct page. 

package com.liu.servlet;

import com.liu.Bean.Goods;
import com.liu.dao.impl.GoodsDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/Tianjia")
public class Tianjia extends HttpServlet {
    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8"); // 设置响应编码
        request.setCharacterEncoding("utf-8"); // 设置请求编码
        response.setContentType("text/html;charset = utf-8"); // 设置响应类型

        Goods goods = new Goods(); // 创建Goods对象
        goods.setGname(request.getParameter("gname")); // 获取商品名称并设置到Goods对象中
        goods.setPrice(Double.parseDouble(request.getParameter("price"))); // 获取商品价格并设置到Goods对象中
        goods.setMark(request.getParameter("mark")); // 获取商品描述并设置到Goods对象中

        GoodsDao goodsDao = new GoodsDao(); // 创建GoodsDao对象
        int row = goodsDao.tianjia(goods); // 调用添加商品方法,返回受影响行数

        if (row>0){ // 如果添加成功,则重定向到商品列表Servlet
            request.getRequestDispatcher("ServletAllGoods").forward(request,response);
        }else{ // 否则转发到错误页面并输出错误信息
            request.setAttribute("error_msg","添加失败!!!");
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }
}

This class implements the HttpServlet interface and provides the function of adding products. In the doPost() method, first set the response code, request code and response type, then create a Goods object and obtain product name, price and description information, and set these information into the Goods object. Then create a GoodsDao object and call the method of adding goods to return the number of affected rows. If the addition is successful, redirect to the product list Servlet; otherwise, forward to the error page and output the error message. When implementing the Servlet, you need to pay attention to processing request parameters, adding information such as results, and redirecting or forwarding to the correct page. 

package com.liu.servlet;

import com.liu.Bean.Goods;
import com.liu.dao.impl.GoodsDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/xiugai")
public class Xiugai extends HttpServlet {
    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8"); // 设置响应编码
        request.setCharacterEncoding("utf-8"); // 设置请求编码
        int gid = Integer.parseInt(request.getParameter("gid")); // 获取商品ID并转换为整型

        GoodsDao goodsDao = new GoodsDao(); // 创建GoodsDao对象
        Goods goods = goodsDao.xiugai1(gid); // 调用查找商品方法,返回查询结果对象

        if (goods!=null){ // 如果查询结果不为空,则将查询结果存储到request中,并转发到修改页面
            request.setAttribute("goods",goods);
            request.getRequestDispatcher("xiugai.jsp").forward(request,response);
        }else { // 否则转发到错误页面并输出错误信息
            request.setAttribute("error_msg","修改错误!!!");
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }
}

This class implements the HttpServlet interface and provides the function of searching product information. In the doPost() method, first set the response code, request code and obtain the product ID, and convert the product ID to an integer. Then create a GoodsDao object and call the find product method to return the query result object. If the query result is not empty, store the query result in the request and forward to the modification page; otherwise, forward to the error page and output the error message. When implementing the Servlet, attention should be paid to processing information such as request parameters and query results, and redirecting or forwarding to the correct page. 

package com.liu.servlet;

import com.liu.Bean.Goods;
import com.liu.dao.impl.GoodsDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/xiugai2")
public class Xiugai2 extends HttpServlet {
    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8"); // 设置响应编码
        request.setCharacterEncoding("utf-8"); // 设置请求编码

        Goods goods = new Goods(); // 创建Goods对象
        goods.setGid(Integer.parseInt(request.getParameter("gid"))); // 获取商品ID并设置到Goods对象中
        goods.setGname(request.getParameter("gname")); // 获取商品名称并设置到Goods对象中
        goods.setPrice(Double.parseDouble(request.getParameter("price"))); // 获取商品价格并设置到Goods对象中
        goods.setMark(request.getParameter("mark")); // 获取商品描述并设置到Goods对象中

        GoodsDao goodsDao = new GoodsDao(); // 创建GoodsDao对象
        int row = goodsDao.xiugai2(goods); // 调用修改商品方法,返回受影响行数

        if (row > 0 ){ // 如果修改成功,则重定向到商品列表Servlet
            request.getRequestDispatcher("ServletAllGoods").forward(request,response);
        }else { // 否则转发到错误页面并输出错误信息
            request.setAttribute("error_msg","修改错误!!!");
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }
}

This class implements the HttpServlet interface and provides the product modification function. In the doPost() method, first set the response code and request code, then create a Goods object and get the product ID, name, price and description information, and set these information into the Goods object. Then create a GoodsDao object and call the modify product method to return the number of affected rows. If the modification is successful, redirect to the product list Servlet; otherwise, forward to the error page and output the error message. When implementing the Servlet, it is necessary to pay attention to information such as processing request parameters, modifying results, and redirecting or forwarding to the correct page.

page code

web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>com.liu.servlet.Login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
</web-app>

paging file

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>欢迎光临</title>
</head>
<body>
    <h2>${error_msg}</h2>
    <a href="login.jsp">返回重试</a>
</body>
</html>
<%@ page import="com.liu.Bean.Goods" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: pai'meng
  Date: 2023/2/22
  Time: 11:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri ="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>购物</title>
</head>
<body>
    <h2>欢迎来自${user.address}的${user.username}访问主页</h2>

        <table>
            <form action="mohu" method="get">
                <input type="text" name="sousuo" value="" >
                <input type="submit" name="搜索2" value="搜索">
            </form>
            <thead>
                <tr>
                    <th>商品编号</th>
                    <th>商品名字</th>
                    <th>商品价格</th>
                    <th>商品介绍</th>
                </tr>
            </thead>
            <tbody id="list">
            <c:forEach items="${shopping}" var="sho">
                <tr>
                    <td>${sho.gid}</td>
                    <td>${sho.gname}</td>
                    <td>${sho.price}</td>
                    <td>${sho.mark}</td>
                    <td><a href="shanchu?gid=${sho.gid}">删除</a></td>
                    <td><a href="xiugai?gid=${sho.gid}">修改</a></td>
                </tr>

            </c:forEach>
            <a href="tianjia.jsp">添加</a>
            </tbody>
</table>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>主页</title>
  </head>
  <body>
  <h2>欢迎来到主页</h2>
  <a href="login.jsp">登录</a>
  <a href="register.jsp">注册</a>
  </body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
    <form action="login" method="get">
        请输入账号:<input type="text" name="username"><br>
        请输入密码:<input type="password" name="password"><br>

        <input type="submit" value="确定">
        <a href="register.jsp">没有账户?点击注册</a>

    </form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
<form action="register" method="post">
    请输入注册账号:<input type="text" name="username"><br>
    请输入注册密码:<input type="password" name="password"><br>
    请输入电话:<input type="text" name="phone"><br>
    请输入地址:<input type="text" name="address"><br>
    <input type="submit" value="确定">
    <a href="login.jsp">已有账号?点击登录</a>
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加商品</title>
</head>
<body>
<form action="Tianjia" method="post">
  请输入商品名称:<input type="text" name="gname"><br>
  请输入商品价格:<input type="number" name="price"><br>
  请输入商品介绍:<input type="text" name="mark"><br>
  <input type="submit" value="添加">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>修改页面</title>
</head>
<body>
    <form action="xiugai2" method="post">
<%--        <c:forEach items="goods" var="goods"></c:forEach>--%>
        商品编号:<input type="text" name="gid" value="${goods.gid}" placeholder="商品编号" readonly = readonly><br>
        商品名称:<input type="text" name="gname" value="${goods.gname}" placeholder="商品名称"><br>
        商品价格:<input type="number" name="price" value="${goods.price}" placeholder="商品价格"><br>
        商品介绍:<input type="text" name="mark" value="${goods.mark}" placeholder="商品介绍"><br>
        <input type="submit" value="确定">
    </form>
</body>
</html>

Show results 

 

Guess you like

Origin blog.csdn.net/weixin_69420643/article/details/129756959