第五阶段项目

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: apiDaoUserDaoImplServiceControlerpom文件

api

数据库连接池配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!-- 阿里 druid 数据库连接池 -->
<bean id = "dataSource" class = "com.alibaba.druid.pool.DruidDataSource" destroy-method = "close" >
    <!-- 数据库基本信息配置 -->
    <property name = "url" value = "${url}" />
    <property name = "username" value = "${username}" />
    <property name = "password" value = "${password}" />
    <property name = "driverClassName" value = "${driverClassName}" />
    <property name = "filters" value = "${filters}" />
    <!-- 最大并发连接数 -->
    <property name = "maxActive" value = "${maxActive}" />
    <!-- 初始化连接数量 -->
    <property name = "initialSize" value = "${initialSize}" />
    <!-- 配置获取连接等待超时的时间 -->
    <property name = "maxWait" value = "${maxWait}" />
    <!-- 最小空闲连接数 -->
    <property name = "minIdle" value = "${minIdle}" />
    <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    <property name = "timeBetweenEvictionRunsMillis" value ="${timeBetweenEvictionRunsMillis}" />
    <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    <property name = "minEvictableIdleTimeMillis" value ="${minEvictableIdleTimeMillis}" />
    <property name = "validationQuery" value = "${validationQuery}" />
    <property name = "testWhileIdle" value = "${testWhileIdle}" />
    <property name = "testOnBorrow" value = "${testOnBorrow}" />
    <property name = "testOnReturn" value = "${testOnReturn}" />
    <property name = "maxOpenPreparedStatements" value ="${maxOpenPreparedStatements}" />
    <!-- 打开 removeAbandoned 功能 -->
    <property name = "removeAbandoned" value = "${removeAbandoned}" />
    <!-- 1800 秒,也就是 30 分钟 -->
    <property name = "removeAbandonedTimeout" value ="${removeAbandonedTimeout}" />
    <!-- 关闭 abanded 连接时输出错误日志 -->
    <property name = "logAbandoned" value = "${logAbandoned}" />
</ bean >
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/taobao?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
username=root
password=666
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200


DbPoolConnection


package org.ljh.taobao.api.config;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
 * @Author: Mo
 * @Date: 2021/3/26 14:10
 */
public class DbPoolConnection {
    private static DbPoolConnection databasePool = null;
    private static DataSource dataSource = null;
    static {
        Properties properties = new Properties();
        try {
            InputStream inputStream=DbPoolConnection.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private DbPoolConnection() {
    }
    public static synchronized DbPoolConnection getInstance() {
        if (null == databasePool) {
            databasePool = new DbPoolConnection();
        }
        return databasePool;
    }
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}


日志配置文件


<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL-->
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration status="INFO" monitorInterval="30">
    <!--先定义所有的appender-->
    <appenders>
        <!--这个输出控制台的配置-->
        <console name="Console" target="SYSTEM_OUT">
            <!--输出日志的格式-->
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </console>
        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
        <File name="log" fileName="${sys:user.home}/logs/test.log" append="false">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>
        <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
        <RollingFile name="RollingFileInfo"
                     fileName="${sys:user.home}/logs/info.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
        <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/warn.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
        <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/error.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
    </appenders>
    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
    <loggers>
        <!--        &lt;!&ndash;过滤掉spring和mybatis的一些无用的DEBUG信息&ndash;&gt;-->
        <!--        <logger name="org.springframework" level="INFO"></logger>-->
        <!--        <logger name="org.mybatis" level="INFO"></logger>-->
        <root level="INFO">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileInfo"/>
            <appender-ref ref="RollingFileWarn"/>
            <appender-ref ref="RollingFileError"/>
        </root>
    </loggers>
</configuration>


Dao

GoodsDaoImpl

package org.ljh.taobao.dao.impl;
import org.ljh.taobao.api.entity.Goods;
import org.ljh.taobao.api.utils.DruidConnectionUtils;
import org.ljh.taobao.dao.IGoodsDao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * @Author: Mo
 * @Date: 2021/4/16 11:46
 */
public class GoodsDaoImpl implements IGoodsDao {
    DruidConnectionUtils druidConnectionUtils= new DruidConnectionUtils();
    @Override
    public List<Goods> listGoods(Connection connection) {
        List<Goods> listGoods = new ArrayList<>();
        Goods good1 = null;
        String sql = "select * from goods;";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Integer goodId = resultSet.getInt("goodID");
                String goodsName = resultSet.getString("goodsName");
                Integer prices = resultSet.getInt("price");
                good1 = new Goods(goodId, goodsName, prices);
                listGoods.add(good1);
            }
            return listGoods;
        } catch (SQLException e) {
            System.out.println("商品查询失败");
            e.printStackTrace();
            return null;
        } finally {
                druidConnectionUtils.closeConnection(connection, preparedStatement, null);
            }
    }
    @Override
    public Goods getgood(List listgoods) {
        return null;
    }
}


OrderDaoImpl


package org.ljh.taobao.dao.impl;
import org.ljh.taobao.api.entity.Order;
import org.ljh.taobao.api.utils.DruidConnectionUtils;
import org.ljh.taobao.dao.IOrderDao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * @Author: Mo
 * @Date: 2021/4/13 21:05
 */
public class OrderDaoImpl implements IOrderDao {
    DruidConnectionUtils druidConnectionUtils = new DruidConnectionUtils();
    @Override
    public boolean insertOrder(Connection connection, Order order) {
        String sql = "insert into `order` (userId,goods,numb) values(?,?,?);";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, order.getUserId());
            preparedStatement.setString(2, order.getGoods());
            preparedStatement.setString(3, order.getNumb());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            System.out.println("订单添加失败");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                System.out.println("资源关闭失败");
                e.printStackTrace();
                return false;
            } finally {
                druidConnectionUtils.closeConnection(connection, preparedStatement, null);
                return true;
            }
        }
    }
    @Override
    public Order getOrder(Connection connection, List order) {
        return null;
    }
    @Override
    public List<Order> listOrder(Connection connection, String userId) {
        List<Order> listOrder = new ArrayList<>();
        Order order1 = null;
        ResultSet resultSet = null;
        String sql = "select * from `order` where userId = ? ;";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userId);
            resultSet = preparedStatement.executeQuery();
            System.out.println("try执行了");
            while (resultSet.next()) {
                String good = resultSet.getString("goods");
                String numb = resultSet.getString("numb");
                order1 = new Order(userId, good, numb);
                listOrder.add(order1);
            }
            return listOrder;
        } catch (SQLException e) {
            System.out.println("传入的用户名为"+userId+sql);
            System.out.println("购物车查询失败");
            e.printStackTrace();
            return null;
        } finally {
            druidConnectionUtils.closeConnection(connection, preparedStatement, null);
        }
    }
    @Override
    public boolean deleteOrder(Connection connection, String userId, String goods) {
        String sql = "delete from `order` where userId = ? and goods = ? ;";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,userId);
            preparedStatement.setString(1,goods);
            preparedStatement.executeUpdate();
            return true;
        } catch (SQLException e) {
            System.out.println("订单删除失败");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                System.out.println("资源关闭失败");
                e.printStackTrace();
                return false;
            } finally {
                druidConnectionUtils.closeConnection(connection, preparedStatement, null);
            }
        }
    }
}


UserDaoImpl


package org.ljh.taobao.dao.impl;
import org.ljh.taobao.api.entity.User;
import org.ljh.taobao.api.utils.DruidConnectionUtils;
import org.ljh.taobao.dao.IUserDao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * @Author: Re
 * @Date: 2021/3/26 14:15
 */
public class UserDaoImpl implements IUserDao {
    DruidConnectionUtils druidConnectionUtils = new DruidConnectionUtils();
    @Override
    public boolean insertUser(Connection connection, User user) {
        String sql = "insert into `user` (userName,userPassword) values(?,?);";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, user.getUserName());
            preparedStatement.setString(2, user.getUserPassword());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            System.out.println("用户添加失败");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                System.out.println("资源关闭失败");
                e.printStackTrace();
                return false;
            } finally {
                druidConnectionUtils.closeConnection(connection, preparedStatement, null);
                return true;
            }
        }
    }
    @Override
    public User loginUser(Connection connection, User user) {
        String sql = "select * from `user` where username = ? and userPassword = ? ;";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User user2 = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, user.getUserName());
            preparedStatement.setString(2, user.getUserPassword());
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                String userId = String.valueOf(resultSet.getInt("id"));
                String userName = resultSet.getString("userName");
                String userPassword = resultSet.getString("userPassword");
                user2 = new User(resultSet.getInt("id"),resultSet.getString("userName"),resultSet.getString("userPassword"));
                System.out.println(userName+"使用密码"+userPassword+"登录");
                return user2;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            druidConnectionUtils.closeConnection(connection,preparedStatement,resultSet);
        }
        return null;
    }
    @Override
    public boolean deleteUser(Connection connection, String myusername) {
        String sql = "delete from `user` where userName = ? ;";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,myusername);
            preparedStatement.executeUpdate();
            return true;
        } catch (SQLException e) {
            System.out.println("用户删除失败");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                System.out.println("资源关闭失败");
                e.printStackTrace();
                return false;
            } finally {
                druidConnectionUtils.closeConnection(connection, preparedStatement, null);
            }
        }
    }
}


Service

GoodsServiceImpl


package org.ljh.taobao.service;
import org.ljh.taobao.api.IGoodsService;
import org.ljh.taobao.api.entity.Goods;
import org.ljh.taobao.api.utils.DruidConnectionUtils;
import org.ljh.taobao.dao.IGoodsDao;
import org.ljh.taobao.dao.impl.GoodsDaoImpl;
import java.sql.Connection;
import java.util.List;
/**
 * @Author: Mo
 * @Date: 2021/4/15 23:03
 */
public class GoodsServiceImpl implements IGoodsService {
    IGoodsDao iGoodsDao = new GoodsDaoImpl();
    DruidConnectionUtils druidConnectionUtils=new DruidConnectionUtils();
    public List<Goods> listGoods() {
        return iGoodsDao.listGoods(druidConnectionUtils.getConnection());
    }
    public Goods getGood(List Listgoods) {
        return iGoodsDao.getgood(Listgoods);
    }
}


OrderServiceImpl


package org.ljh.taobao.service;
import org.ljh.taobao.api.IOrderService;
import org.ljh.taobao.api.entity.Order;
import org.ljh.taobao.api.entity.User;
import org.ljh.taobao.api.utils.DruidConnectionUtils;
import org.ljh.taobao.dao.IOrderDao;
import org.ljh.taobao.dao.IUserDao;
import org.ljh.taobao.dao.impl.OrderDaoImpl;
import org.ljh.taobao.dao.impl.UserDaoImpl;
import java.util.List;
/**
 * @Author: Mo
 * @Date: 2021/4/13 21:17
 */
public class OrderServiceImpl implements IOrderService {
    IOrderDao iOrderDao=new OrderDaoImpl();
    DruidConnectionUtils druidConnectionUtils=new DruidConnectionUtils();
    public boolean insertOrder(Order order) {
        return iOrderDao.insertOrder(druidConnectionUtils.getConnection(),order);
    }
    public List<Order> listOrder(String userId) {
        return iOrderDao.listOrder(druidConnectionUtils.getConnection(),userId);
    }
    public boolean deleteOrder(String userId, String goods) {
        return iOrderDao.deleteOrder(druidConnectionUtils.getConnection(),userId,goods);
    }
    public Order order(Order order) {
        return null;
    }
    public Order Order(List orders) {
        return iOrderDao.getOrder(druidConnectionUtils.getConnection(),orders);
    }
}


UserServiceImpl


package org.ljh.taobao.service;
import org.ljh.taobao.api.IUserService;
import org.ljh.taobao.api.entity.User;
import org.ljh.taobao.api.utils.DruidConnectionUtils;
import org.ljh.taobao.dao.IUserDao;
import org.ljh.taobao.dao.impl.UserDaoImpl;
/**
 * @Author: Re
 * @Date: 2021/3/26 19:15
 */
public class UserServiceImpl implements IUserService {
    IUserDao iUserDao=new UserDaoImpl();
    DruidConnectionUtils druidConnectionUtils=new DruidConnectionUtils();
    public boolean insertUser(User user) {
        return iUserDao.insertUser(druidConnectionUtils.getConnection(),user);
    }
    public User loginUser(User user) {
        return iUserDao.loginUser(druidConnectionUtils.getConnection(),user);
    }
    public boolean deleteUser(String myusername) {
        return iUserDao.deleteUser(druidConnectionUtils.getConnection(),myusername);
    }
}


Controler

DeleteUserServlet


package org.ljh.taobao.controller;
import org.ljh.taobao.api.IUserService;
import org.ljh.taobao.api.entity.User;
import org.ljh.taobao.service.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
/**
 * @Author: Mo
 * @Date: 2021/4/14 23:57
 */
@WebServlet("/deleteUser")
public class DeleteUserServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(DeleteUserServlet.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        HttpSession session = req.getSession();
        String myusername = (String) session.getAttribute("myusername");
        IUserService iUserService = new UserServiceImpl();
        boolean judgment=iUserService.deleteUser(myusername);
        if (judgment == true){
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }
        else {
            req.setAttribute("zx","注销失败");
        }
    }
}


ListGoodsServlet


package org.ljh.taobao.controller;
import org.ljh.taobao.api.IGoodsService;
import org.ljh.taobao.api.entity.Goods;
import org.ljh.taobao.service.GoodsServiceImpl;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
/**
 * @Author: Mo
 * @Date: 2021/4/15 19:15
 */
@WebServlet("/listGoods")
public class ListGoodsServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        IGoodsService iGoodsService=new GoodsServiceImpl();
        List <Goods> goodsList = iGoodsService.listGoods();
        HttpSession session = req.getSession();
        session.setAttribute("goodsList",goodsList);
        req.getRequestDispatcher("shopping.jsp").forward(req, resp);
    }
}


InsertOrderServlet


package org.ljh.taobao.controller;
import org.ljh.taobao.api.IOrderService;
import org.ljh.taobao.api.IUserService;
import org.ljh.taobao.api.entity.Order;
import org.ljh.taobao.api.entity.User;
import org.ljh.taobao.service.OrderServiceImpl;
import org.ljh.taobao.service.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
/**
 * @Author: Mo
 * @Date: 2021/4/13 21:42
 */
@WebServlet("/insertOrder")
public class InsertOrderServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(InsertUserServlet.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        HttpSession session = req.getSession();
        String userId = (String) session.getAttribute("myusername");
        String goods = req.getParameter("goods");
        String numb = req.getParameter("numb");
        Order order = new Order(userId,goods,numb);
        logger.info(order.toString());
        if (goods == "") {
            req.setAttribute("msg","请输入商品名");
        }
        else if (numb == null) {
            req.setAttribute("msg", "请输入购买数量");
        }
        else {
            IOrderService iOrderService=new OrderServiceImpl();
            boolean judgment=iOrderService.insertOrder(order);
            if (judgment) {
                req.setAttribute("msg", "购买成功");
                req.getRequestDispatcher("shoppingSuccess.jsp").forward(req,resp);
            }
            else {
                req.setAttribute("msg", "购买失败");
            }
        }
        req.getRequestDispatcher("shopping.jsp").forward(req,resp);
    }
}


InsertUserServlet


package org.ljh.taobao.controller;
import org.ljh.taobao.api.IUserService;
import org.ljh.taobao.api.entity.User;
import org.ljh.taobao.service.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
/**
 * @Author: Mo
 * @Date: 2021/3/26 19:24
 */
@WebServlet("/insertUser")
public class InsertUserServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(InsertUserServlet.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        User user = new User(userName,userPassword);
        logger.info(user.toString());
        if (userName == "") {
            req.setAttribute("msg","请输入用户名");
        }
        else if (userPassword == "") {
            req.setAttribute("msg", "请输入密码");
        }
        else {
            IUserService iUserService=new UserServiceImpl();
            boolean judgment=iUserService.insertUser(user);
            if (judgment) {
                req.setAttribute("msg", "注册成功");
                req.getRequestDispatcher("insertSuccess.jsp").forward(req,resp);
            }
            else {
                req.setAttribute("msg", "注册失败");
            }
        }
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}

LoginUserServlet


package org.ljh.taobao.controller;
import com.sun.org.apache.bcel.internal.generic.Select;
import org.ljh.taobao.api.IUserService;
import org.ljh.taobao.api.entity.User;
import org.ljh.taobao.service.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
/**
 * @Author: Mo
 * @Date: 2021/3/26 19:24
 */
@WebServlet("/loginUser")
public class LoginUserServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(LoginUserServlet.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        User user = new User(userName,userPassword);
        logger.info(user.toString());
        IUserService iUserService=new UserServiceImpl();
        User judgment2=iUserService.loginUser(user);
        if (userName == "") {
            req.setAttribute("msg","请输入用户名");
        }
        else if (userPassword == "") {
            req.setAttribute("msg", "请输入密码");
        }
        else if (judgment2 != null){
            HttpSession session = req.getSession();
            session.setAttribute("myusername",judgment2.getUserName());
            req.setAttribute("msg","登录成功");
            req.getRequestDispatcher("loginSuccess.jsp").forward(req,resp);
            return;
        }
        else {
            req.setAttribute("msg","登录失败");
        }
        req.getRequestDispatcher("denglu.jsp").forward(req,resp);
    }
}

Webapp

deletUser.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%--
  Created by IntelliJ IDEA.
  User: HP
  Date: 2021/4/14
  Time: 18:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注意</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="banner"><h1>账号注销后不可恢复,是否确认注销?</h1>
<form action="/deleteUser" method="post" >
<div><button type="submit">确认注销</button></div>
</form>
<a href="index.jsp"> <button>退出登录</button></a>
<span style="color: red; font-size: 15px">${zx}</span>
</div>
</body>
</html>

denglu.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<title></title>
<link href="index.css" rel="stylesheet" type="text/css" />
<head>
    <title>登录</title>
</head>
<body>
  <div id="banner">
  <form action="/loginUser" method="post" >
    <h4 id="denglu">登录栏</h4>
    <input type="text" name="userName">姓名<br>
    <input type="text" name="userPassword">密码<br>
    <button type="submit">提交</button>
    <span style="color: red; font-size: 15px">${msg}</span>
  </form>
  </div>
</body>
</html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<title>注册</title>
<link href="index.css" rel="stylesheet" type="text/css" />
<body>
</body>
<div id="banner">
    <div>
<form action="/insertUser" method="post" >
    <h4 id="zhuce">注册栏</h4>
    <input type="text" name="userName">姓名<br>
    <input type="text" name="userPassword">密码<br>
    <button type="submit">提交</button>
    <span style="color: red; font-size: 15px">${msg}</span>
</form>
    </div><a href="denglu.jsp" >
    <button>登录</button >
</a>
</div>
</html>


insertSuccess.jsp

<%--
    Created by IntelliJ IDEA.
    User: Re
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>注册成功</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
</head >
<body>
<div id="banner">
<h1>${msg}</h1>
<a href="denglu.jsp"><button>点击登录</button></a>
</div>
</body>
</html>

loginSuccess.jsp


<%--
  Created by IntelliJ IDEA.
  User: HP
  Date: 2021/4/11
  Time: 17:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><html>
<head>
    <title>登录成功</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="banner">
<div>${msg}</div>
<form action="/listGoods"  method="post">
    <button type="submit">荣耀商店</button>
</form>
<form action="/listOrders"  method="post">
    <button type="submit">购物车</button>
</form>
<a href="deletUser.jsp"><button>注销账号</button></a>
</div>
</body>
</html>

order.jsp


<%--
  Created by IntelliJ IDEA.
  User: HP
  Date: 2021/4/15
  Time: 10:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><html>
<html>
<html>
<head>
    <title>购物车</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="banner">
<form action="/listOrders" method="post">
    <table>
        <tr height="50">
            <td colspan="3" align="center" ><h1>订单列表</h1></td>
        </tr>
        <tr align="center" height="30" bgcolor="lightgrey">
            <th>商品名称</th>
            <th>数量</th>
            <th>移出购物车</th>
        </tr>
        <c:forEach items="${ordersList}" var="orders">
            <tr>
                <td>${orders.goods}</td>
                <td>${orders.numb}</td>
                <td><button type="submit" name="out" value="${orders.userId}">移出购物车</button> </td>
            </tr>
        </c:forEach>
    </table>
</form>
</div>
</body>
</html>

shopping.jsp

<%@ page import="org.ljh.taobao.api.entity.Goods" %>
<%@ page import="java.util.ArrayList" %><%--
  Created by IntelliJ IDEA.
  User: HP
  Date: 2021/4/12
  Time: 20:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>购物</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="banner">
<form action="/listGoods" method="post">
<table>
    <tr height="50">
        <td colspan="3" align="center" ><h1 id=>商品列表</h1></td>
    </tr>
    <tr align="center" height="30" bgcolor="lightgrey">
        <th>名称</th>
        <th>价格</th>
        <th>加入购物车</th>
    </tr>
<c:forEach items="${goodsList}" var="good">
<tr>
    <td>${good.goodsName}</td>
    <td>${good.price}</td>
    <td><button type="submit" name="collect" value="${good.goodID}">加入购物车</button> </td>
</tr>
</c:forEach>
</table>
</form>
<form action="/insertOrder" method="post">
    <h4 id="buying"></h4>
    <input type="text" name="goods">商品名<br>
    <input type="text" name="numb">数量<br>
    <button type="submit">提交</button>
    <span style="color: red; font-size: 15px">${msg}</span>
</form>
</div>
</body>
</html>

shoppingSuccess.jsp

<%--
  Created by IntelliJ IDEA.
  User: HP
  Date: 2021/4/14
  Time: 12:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><html>
<html>
<head>
    <title>请合理消费</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="banner">
<div><h1>购买成功</h1></div>
<a href="shopping.jsp"><button>继续购买</button></a>
</div>
</body>
</html>

CSS文件

body{font-size: large;
    font-color:#919892;
    background: white url(/images/back.png) no-repeat center;
    ext-align:center;
}
#banner{
    color:#919892;
    margin-top: 240px;
        margin-left: 350px;
}
#denglu{margin-bottom: 0}
#zhuce{margin-bottom: 0}


pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.lyl</groupId>
    <artifactId>taobao</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>taobao-api</module>
        <module>taobao-dao</module>
        <module>taobao-service</module>
        <module>taobao-controller</module>
    </modules>
    <repositories>
        <!--阿里云仓库-->
        <repository>
            <id>aliyun</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
    <properties>
        <!-- jar包版本设置 -->
        <slf4j.version>1.7.21</slf4j.version>
        <log4j.version>2.8.2</log4j.version>
    </properties>
    <dependencies>
        <!-- 导入slf4j的接口包以及对应日志框架的驱动包 -->
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!--用于slf4j与log4j2保持桥接 -->
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <scope>runtime</scope>
            <version>${log4j.version}</version>
        </dependency>
        <!-- 导入日志框架核心包与接口包 -->
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <scope>runtime</scope>
            <version>${log4j.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <!--用于解决web环境下关闭服务器时可能出现的log4j线程无法及时关闭的warn,web工程需要包含log4j-web,非web工程不需要 -->
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-web -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <scope>runtime</scope>
            <version>${log4j.version}</version>
        </dependency>
        <!--使用log4j2的AsyncLogger时需要包含disruptor -->
        <!-- https://mvnrepository.com/artifact/com.lmax/disruptor -->
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <scope>runtime</scope>
            <version>3.4.2</version>
        </dependency>
    </dependencies>
</project>


相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
2月前
|
人工智能 数据可视化 安全
瀑布模型是什么?在软件开发中有哪些主要阶段和步骤?
瀑布模型是一种经典的软件开发方法,将开发过程划分为需求分析、设计、编码、测试和维护等顺序阶段,强调阶段性和文档化。适用于需求明确、稳定且对安全性和可靠性要求高的项目。尽管存在局限性,但在特定场景下仍具重要价值。未来,瀑布模型可能与其他开发模型结合,更加灵活高效。
瀑布模型是什么?在软件开发中有哪些主要阶段和步骤?
|
2月前
|
监控 数据可视化 安全
软件生命周期是什么?包括哪些阶段?各阶段的目标和任务是什么?
在数字化时代,软件如同空气般无处不在,其生命周期涵盖从需求分析到退役的多个阶段,如同生物的成长过程。本文详细介绍了软件生命周期各阶段的目标与任务,并探讨了瀑布模型、迭代模型和敏捷模型等常见生命周期模型。未来,随着技术和业务的不断演变,软件生命周期管理将面临更多挑战与机遇,需不断学习先进方法和技术,以满足用户需求。
|
监控 数据挖掘 测试技术
冲刺阶段-最终题(三)
冲刺阶段-最终题(三)
178 0
|
人工智能 监控 算法
冲刺阶段-最终题(四)
冲刺阶段-最终题(四)
86 0
|
监控 新制造 项目管理
冲刺阶段-最终题(二)
冲刺阶段-最终题(二)
149 0
|
数据挖掘 项目管理
冲刺阶段-最终题(五)
冲刺阶段-最终题(五)
46 0
|
敏捷开发 安全 项目管理
冲刺阶段-最终题(一)
冲刺阶段-最终题
127 0
|
编译器
一个hello文件的四个阶段
一个hello文件的四个阶段
84 0
|
数据采集 消息中间件 大数据
第五阶段总结|学习笔记
快速学习第五阶段总结。
102 0
第五阶段总结|学习笔记
|
数据采集 消息中间件 分布式计算
项目七个阶段总体介绍|学习笔记
快速学习项目七个阶段总体介绍
项目七个阶段总体介绍|学习笔记