一个简单的超市项目,拥有最基础的登录注册对商品的增删改查
Java EE三层框架
代码操作
1.先创建用户的数据库和表
CREATE DATABASE `supermarket`
CREATE TABLE `t_user` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`email` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
)
2 编写数据库表对应的JavaBean对象
在pojo包下面创建User类
package pojo; public class User { private Integer id; private String username; private String password; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } public User() { } public User(Integer id, String username, String password, String email) { this.id = id; this.username = username; this.password = password; this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + '}'; } }
3 编写工具类JdbcUtils
jdbc.properties配置文件
username=csy password=111111 url=jdbc:mysql://localhost:3306/supermarket driverClassName=com.mysql.cj.jdbc.Driver initialSize=5 maxActive=10
在utils包下面创建JdbcUtils类
package Utils; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; public class JdbcUtils { private static DruidDataSource dataSource; static { try { Properties properties = new Properties(); // 读取 jdbc.properties属性配置文件 InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"); // 从流中加载数据 properties.load(inputStream); // 创建 数据库连接 池 dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } /** * 获取数据库连接池中的连接 * @return 如果返回null,说明获取连接失败<br/>有值就是获取连接成功 */ public static Connection getConnection(){ Connection conn = null; try { conn = dataSource.getConnection(); } catch (Exception e) { e.printStackTrace(); } return conn; } /** * 关闭连接,放回数据库连接池 * @param conn */ public static void close(Connection conn){ if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
测试JdbaUtils类
@Test void getConnection() { Connection conn= JdbcUtils.getConnection(); System.out.println(conn); }
在utils包下面创建WebUtils类
package Utils; import org.apache.commons.beanutils.BeanUtils; import java.util.Map; public class WebUtils { public static <T> T copyParamToBean(Map value,T bean){ try{ BeanUtils.populate(bean,value); }catch(Exception e){ e.printStackTrace(); } return bean; } /** * 将字符串转换成为int类型的数据 */ public static int parseInt(String strIng,int defaultValue){ try{ return Integer.parseInt(strIng); }catch(Exception e){ e.printStackTrace(); } return defaultValue; } }
4 编写BaseDao
在dao.impl包下面创建一个抽象类,写一些表的通用操作(其他某种类可以继承使用里面的方法)
package Dao; import Utils.JdbcUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public abstract class BaseDao { private QueryRunner queryRunner=new QueryRunner(); /** * 修改一个表的数据 * @param sql sql操作 * @param args sql对应的参数 * @return */ public int update(String sql,Object...args){ Connection connection= JdbcUtils.getConnection(); try{ return queryRunner.update(connection, sql, args); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); }finally { JdbcUtils.close(connection); } } /** * 查询返回一个javaBean的sql语句 * @param type 返回的对象类型 * @param sql 执行的sql语句 * @param args sql对应的参数值 * @param <T> 返回的类型的泛型 * @return */ public <T> T queryForOne(Class<T> type,String sql,Object...args){ Connection connection=JdbcUtils.getConnection(); try{ return queryRunner.query(connection,sql,new BeanHandler<T>(type),args); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); }finally { JdbcUtils.close(connection); } } /** * 查询返回多个javaBean的sql语句 * @param type 返回对象的类型 * @param sql 执行的sql语句 * @param args sql对应的参数 * @param <T> 返回的类型的泛型 * @return */ public <T> List<T> queryForList(Class<T>type, String sql, Object...args){ Connection connection=JdbcUtils.getConnection(); try{ return queryRunner.query(connection,sql,new BeanListHandler<T>(type),args); }catch (SQLException e){ e.printStackTrace(); throw new RuntimeException(e); }finally { JdbcUtils.close(connection); } } /** * 查询一些特殊的数据 * 比如一些聚合函数Count Avg * @param sql 执行的sql语句 * @param args sql对应的参数值 * @return */ public Object queryForSingleValue(String sql,Object...args){ Connection connection=JdbcUtils.getConnection(); try{ return queryRunner.query(connection,sql, new ScalarHandler(),args); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); }finally { JdbcUtils.close(connection); } } }
5 编写UserDao
接口UserDao
package Dao; import pojo.User; public interface UserDao { /** * 根据用户名查询 * @param username(注册页面) * @return 返回null说明用户名不存在 */ public User queryUserByUsername(String username); /** * 根据用户名和密码查询(登录页面) * @param username * @param password * @return 返回null说明用户不存在 */ public User queryUserByUsernameandPassword(String username,String password); /** * 保存用户信息 * @param user * @return 返回-1表示执行失败,返回其他表示sql语句影响的行数 */ public int saveUser(User user); }
UserDaoImpl实现类
package DaoImpl; import Dao.BaseDao; import Dao.UserDao; import pojo.User; public class UserDaoImpl extends BaseDao implements UserDao { @Override public User queryUserByUsername(String username) { String sql = "select `id`, `username`,`password`,`email` from t_user where username=?"; return queryForOne(User.class, sql, username); } @Override public User queryUserByUsernameandPassword(String username, String password) { String sql = "select `id`, `username`,`password`,`email` from t_user where username=? and password=?"; return queryForOne(User.class, sql, username, password); } @Override public int saveUser(User user) { String sql = "insert into t_user(`username`,`password`,`email`)value(?,?,?)"; return update(sql, user.getUsername(), user.getPassword(), user.getEmail()); } }
测试类UserDaoTest
快捷键,在UserDao接口中:Ctrl+Shift+t,在test包下面创建测试类
package Test; import Dao.UserDao; import DaoImpl.UserDaoImpl; import org.junit.jupiter.api.Test; import pojo.User; import static org.junit.jupiter.api.Assertions.*; class UserDaoImplTest { @Test void queryUserByUsername() { UserDao userDao=new UserDaoImpl(); User user= userDao.queryUserByUsername("Lisi"); System.out.println(user); } @Test void queryUserByUsernameandPassword() { UserDao userDao=new UserDaoImpl(); User user= userDao.queryUserByUsernameandPassword("csy","111111"); System.out.println(user); } @Test void saveUser() { UserDao userDao=new UserDaoImpl(); int user= userDao.saveUser(new User(null,"zy","111111","zyn@qq.com")); System.out.println(user); } }
6 编写UserService
UserService接口
package Service; import pojo.User; public interface UserService { /** * 登录 * @param user */ public User login(User user); /** * 注册 * @param user */ public void regist(User user); /** * 检查用户名是否可用 * @param name * @return 返回false表明可用,返回true表明用户名已存在 */ public boolean existsUsername(String name); }
UserServiceImpl实现类
package Service; import Dao.UserDao; import DaoImpl.UserDaoImpl; import pojo.User; public class UserServiceImpl implements UserService { UserDao userDao=new UserDaoImpl(); @Override public User login(User user) { return userDao.queryUserByUsernameandPassword(user.getUsername(),user.getPassword()); } @Override public void regist(User user) { userDao.saveUser(user); } @Override public boolean existsUsername(String username) { if(userDao.queryUserByUsername(username)!=null){ return true; } return false; } }
创建BaseServlet
package web; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; import java.lang.reflect.Method; public class BaseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html,charset=UTF-8"); String action=request.getParameter("action"); try{ Method method=this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class); method.invoke(this,request,response); }catch(Exception e){ e.printStackTrace(); } } }
创建UserServlet
package web; import Service.UserService; import Service.UserServiceImpl; import Utils.JdbcUtils; import Utils.WebUtils; import com.google.gson.Gson; import pojo.User; import javax.servlet.*; import javax.servlet.http.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY; public class UserServlet extends BaseServlet { private UserService userService = new UserServiceImpl(); /** * 登录 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求参数 String username = request.getParameter("username"); String password = request.getParameter("password"); User loginUser = userService.login(new User(null, username, password, null)); if (loginUser == null) { request.setAttribute("msg", "用户名或密码错误"); request.setAttribute("username", username); request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response); } else { request.getSession().setAttribute("user", loginUser); request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request, response); } } /** * 处理注册功能 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取session域中的验证码 String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY); request.getSession().removeAttribute(KAPTCHA_SESSION_KEY); //1.获取请求参数 String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); String code = request.getParameter("code"); User user = WebUtils.copyParamToBean(request.getParameterMap(), new User()); if (token.equalsIgnoreCase(code)) { //检查用户名是否存在 if (userService.existsUsername(username)) { request.setAttribute("msg", "用户名已存在!"); request.setAttribute("username", username); request.setAttribute("email", email); request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response); } else { userService.regist(new User(null, username, password, email)); request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response); } }else{ request.setAttribute("msg", "验证码不正确!"); request.setAttribute("username", username); request.setAttribute("email", email); request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response); } } /** * 注销 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void loginout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().invalidate(); response.setContentType(request.getContextPath() + "/");//重定向到首页 } protected void ajaxExistsUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求的参数 String username = request.getParameter("username"); boolean existUsername = userService.existsUsername(username); Map<String, Object> resultMap = new HashMap<>(); resultMap.put("existsUsername", existUsername); Gson gson = new Gson(); String json = gson.toJson(resultMap); response.getWriter().write(json); } }
登录页面
<%-- Created by IntelliJ IDEA. User: 29231 Date: 2022/4/28 Time: 16:23 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta charset="UTF-8"> <title>山河之恋登录页面</title> <%@include file="/pages/common/head.jsp"%> </head> <body> <div class="img1"> <div class="login_banner"> <div id="l_content"> <span class="wel_word">欢迎登陆</span> </div> <div id="content"> <div class="login_form"> <div class="login_box"> <div class="tit"> <h1>山河之恋用户账号</h1> <a href="pages/user/regist.jsp">立即注册</a> </div> <div class="msg_cont"> <b></b> <span class="errorMsg"> ${empty requestScope.msg?请输入用户名和密码:requestScope.msg} </span> </div> <div class="form"> <form action="userServlet"method="post"> <input type="hidden" name="action" value="login"/> <lable>用户名称:</lable> <input class="itxt" type="text" placeholder="请输入用户名" autocomplete="off" tabindex="1" name="username" value="${requestScope.username}"/> <br/> <br/> <label>用户密码:</label> <input class="itxt" type="password" placeholder="请输入密码" autocomplete="off" tabindex="1" name="password"/> <br/> <br/> <input type="submit"value="登录"id="sub_btn"/> </form> </div> </div> </div> </div> </div> <%@include file="/pages/common/footer.jsp"%> </div> </body> </html>
注册页面
<%-- Created by IntelliJ IDEA. User: 29231 Date: 2022/4/28 Time: 16:21 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>山河之恋用户注册页面</title> <%@include file="/pages/common/head.jsp"%> <script type="text/javascript"> $(function (){ $("#username").blur(function (){ var username=this.value;//value是js的,val()是jquery $.getJSON("http://localhost:8080/Supermarket/userServlet","action=ajaxExistsUsername&username="+username,function (data){ if(data.existsUsername){ $("span.errorMsg").text("用户名已存在"); }else { $("span.errorMsg").text("用户名可用"); } }); }); //给验证码的图片,绑定单击事件 $("#code_img").click(function (){ //在事件响应的function函数中有一个this 对象,这个this对象,是当前正在响应事件的dom 对象 //src属性表示验证码img标签的图片路径,它可读,可写 this.src="${basePath}kaptcha.jpg?d="+new Date(); }); //给注册绑定单击事件 $("#sub_btn").click(function (){ //验证用户名:必须由字母,数字下划线组成,并且长度为5到12位之间 //获取用户名输入框里的内容 var usernameText=$("#username").val(); //2.创建正则表达式对象 var usernamePatt=/^\w{5,12}$/; //3.使用test方法验证 if(!usernamePatt.test(usernameText)){ //4.提示用户结果 $("span.errorMsg").text("用户名不合法"); return false; } //验证密码:必须由字母,数字下划线组成,并且长度位5到12位之间 //1.获取密码输入框里的内容 var passwordText=$("#password").val(); //2.创建正则表达式对象 var passwordPatt=/^\w{5,12}$/; //3,使用test方法验证 if(!passwordPatt.test(passwordText)){ //4.提示验证结果 $("span.errorMsg").text("密码不合格"); return false; } //验证确认密码,和密码相同 //1.获取确认密码 var repwdText=$("#repwd").val(); //2.和密码相比较 if(repwdText!=passwordText){ //3.提示用户 $("span.errorMsg").text("确认密码和密码不一致"); return false; } //邮箱验证 xxxxxx@xxx.com //1,获取邮箱里的内容 var emailText=$("#email").val(); //2,创建正则表达式对象 var emailPatt=/^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/; //3.使用test方法验证 if(!emailPatt.test(emailText)) { $("span.errorMsg").text("邮箱格式不合法!"); return false; } //去掉验证码前后空格 codeText = $.trim(codeText); if (codeText == null || codeText == "") { //提示用户 $("span.errorMsg").text("验证码不能为空!"); return false; } //去掉错误信息 $("span.errorMsg").text(""); }); }); </script> <style type="text/css"> .login_form{ height: 420px; margin-top: 25px; } </style> </head> <body> <div class="img1"> <div class="login_banner"> <div id="l_content"> <span>欢迎注册</span> </div> <div id="content"> <div class="login_form"> <div class="login_box"> <div class="tit"> <h1>注册用户</h1> <span class="errorMsg"> ${requestScope.msg} </span> </div> <div class="form"> <form action="userServlet" method="post"> <input type="hidden" name="action" value="regist"/> <label for="username">用户名称:</label> <input class="itxt" type="text"placeholder="请输入用户名" autocomplete="off"tabindex="1"name="username" value="${requestScope.username}" id="username" /> <br/> <br/> <label for="password">用户密码:</label> <input class="itxt" type="password"placeholder="请输入用户密码" autocomplete="off"tabindex="1"name="password"id="password"/> <br/> <br/> <label for="repwd">确认密码:</label> <input class="itxt" type="password"placeholder="确认密码" autocomplete="off"tabindex="1"name="repwd"id="repwd"/> <br/> <br/> <label for="email">电子邮箱:</label> <input class="itxt"type="email"placeholder="请输入邮箱地址" autocomplete="off"tabindex="1"name="email" value="${requestScope.email}" id="email"/> <br/> <br/> <label>验证码:</label> <input class="itxt"type="text"name="code"style="width:80px;"id="code"/> <img id="code_img" alt=""src="kaptcha.jpg" style="float:right;margin-right: 40px;width:110px;height: 30px;"> <br/> <br/> <input type="submit"value="注册"id="sub_btn"/> </form> </div> </div> </div> </div> </div> <%@include file="/pages/common/footer.jsp"%> </div> </body> </html>
公共部分
脚尾 footer.jsp
<%-- Created by IntelliJ IDEA. User: 29231 Date: 2022/4/28 Time: 17:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <div id="bottom"> <span> 山河之恋.csy@2022 </span> </div>
头部head.jsp base标签 css标签 jquery标签
<%-- Created by IntelliJ IDEA. User: 29231 Date: 2022/4/28 Time: 16:43 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String basePath=request.getScheme()+"://" +request.getServerName() +":" +request.getServerPort() +request.getContextPath() +"/"; pageContext.setAttribute("basePath",basePath); %> <base href="<%=basePath%>"> <link type="text/css"rel="stylesheet"href="static/css/style.css"> <script type="text/javascript"src="static/script/jquery-1.7.2.js"></script>
web.xml部分
<servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>web.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/userServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>KaptchaServlet</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>KaptchaServlet</servlet-name> <url-pattern>/kaptcha.jpg</url-pattern> </servlet-mapping> <servlet>
创建商品表
CREATE TABLE `t_snacks` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`price` decimal(20,0) NOT NULL,
`sales` int DEFAULT NULL,
`stock` int DEFAULT NULL,
`img_path` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
)
创建snacksDao
package Dao; import pojo.Snacks; import java.util.List; public interface SnacksDao { /** * 添加零食 * @param snacks * @return */ public int add(Snacks snacks); /** * 删除零食 * @param id * @return */ public int delete(Integer id); /** * 修改零食 * @param snacks * @return */ public int update(Snacks snacks); /** * 根据id查询 * @param id * @return */ public Snacks querySnacksById(Integer id); /** * 查询全部零食 * @return */ public List<Snacks> querySnacks(); /** * 求价格区间的数据 * @param min * @param max * @return */ public List<Snacks> querySnacksByprice(Integer min,Integer max ); }
snacksDaoImpl实现类
package DaoImpl; import Dao.BaseDao; import Dao.SnacksDao; import pojo.Snacks; import java.util.List; public class SnacksDaoImpl extends BaseDao implements SnacksDao { @Override public int add(Snacks snacks) { String sql="insert into t_snacks(`name`,`price`,`sales`,`stock`,`img_path` )value(?,?,?,?,?)"; return update(sql,snacks.getName(),snacks.getPrice(),snacks.getSales(),snacks.getStock(),snacks.getImgPath()); } @Override public int delete(Integer id) { String sql="delete from t_snacks where id=?"; return update(sql,id); } @Override public int update(Snacks snacks) { String sql="update t_snacks set `name`=?,`price`=?,`sales`=?,`stock`=?,`img_path`=?where `id`=?"; return update(sql,snacks.getName(),snacks.getPrice(),snacks.getSales(),snacks.getStock(),snacks.getImgPath(),snacks.getId()); } @Override public Snacks querySnacksById(Integer id) { String sql="select `id`,`name`,`price`,`sales`,`stock`,`img_path` as imgPath from t_snacks where id=?"; return queryForOne(Snacks.class,sql,id); } @Override public List<Snacks> querySnacks() { String sql="select `id`,`name`,`price`,`sales`,`stock`,`img_path` as imgPath from t_snacks "; return queryForList(Snacks.class,sql); } @Override public List<Snacks> querySnacksByprice(Integer min, Integer max) { String sql="select `id`,`name`,`price`,`sales`,`stock`,`img_path` as imgPth from t_snacks where `price` between ? and ? order by `price` ASC"; return queryForList(Snacks.class,sql,min,max); } }
service
package Service; import pojo.Snacks; import java.util.List; public interface SnacksService { /** * 添加零食 * @param snacks * @return */ public int add(Snacks snacks); /** * 修改零食 * @param snacks * @return */ public int update(Snacks snacks); /** * 删除零食 * @param id * @return */ public int delete(Integer id); /** * 根据id查询零食 * @param id * @return */ public Snacks querySnacksById(Integer id); /** * 查询所有零食商品 * @return */ public List<Snacks>querySnacks(); /** *求价格区间的数据 * @param min * @param max * @return */ public List<Snacks> querySnacksByPrice(Integer min,Integer max); }
serviceImpl实现类
package Service; import Dao.SnacksDao; import DaoImpl.SnacksDaoImpl; import pojo.Snacks; import java.util.List; public class SnacksServiceImpl implements SnacksService { SnacksDao snacksDao = new SnacksDaoImpl(); @Override public int add(Snacks snacks) { return snacksDao.add(snacks); } @Override public int update(Snacks snacks) { return snacksDao.update(snacks); } @Override public int delete(Integer id) { return snacksDao.delete(id); } @Override public Snacks querySnacksById(Integer id) { return snacksDao.querySnacksById(id); } @Override public List<Snacks> querySnacks() { return snacksDao.querySnacks(); } @Override public List<Snacks> querySnacksByPrice(Integer min, Integer max) { return snacksDao.querySnacksByprice(min, max); } }
SnacksServlet
package web; import Service.SnacksService; import Service.SnacksServiceImpl; import Utils.WebUtils; import pojo.Snacks; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; import java.util.List; public class SnacksServlet extends BaseServlet { SnacksService snacksService = new SnacksServiceImpl(); protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //把添加的零食封装成一个零食对象 Snacks snacks = WebUtils.copyParamToBean(request.getParameterMap(), new Snacks()); //添加零食 snacksService.add(snacks); response.sendRedirect(request.getContextPath() + "/snacksServlet?action=list"); } protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Snacks snacks = WebUtils.copyParamToBean(request.getParameterMap(), new Snacks()); snacksService.update(snacks); response.sendRedirect(request.getContextPath() +"/snacksServlet?action=list"); } protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id = WebUtils.parseInt(request.getParameter("id"), 0); snacksService.delete(id); response.sendRedirect(request.getContextPath() + "/snacksServlet?action=list"); } protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Snacks> snacks = snacksService.querySnacks(); request.setAttribute("snacks", snacks); request.getRequestDispatcher("/pages/snacks/snacks.jsp").forward(request, response); } protected void getSnacks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求参数 int id = WebUtils.parseInt(request.getParameter("id"), 0); Snacks snacks = snacksService.querySnacksById(id); request.setAttribute("snacks", snacks); request.getRequestDispatcher("/pages/snacks/snacks_edit.jsp").forward(request, response); } protected void querySnacksByprice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求参数 int min=WebUtils.parseInt(request.getParameter("min"),0); int max=WebUtils.parseInt(request.getParameter("max"),0); List<Snacks>snacks= snacksService.querySnacksByPrice(min,max); request.setAttribute("min",min); request.setAttribute("max",max); request.setAttribute("snacks",snacks); request.getRequestDispatcher("/pages/snacks/snacks.jsp").forward(request,response); } }
商品首页展示snacks.jsp <%-- Created by IntelliJ IDEA. User: 29231 Date: 2022/4/30 Time: 16:03 To change this template use File | Settings | File Templates. --%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta charset="UTF-8"> <title>山河之恋零食商架</title> <%@include file="/pages/common/head.jsp"%> <script type="text/javascript"> $(function (){ $("a.deleteClass").click(function (){ return confirm("你确定要删除【"+$(this).parent().parent().find("td:first").text()+"】吗?"); }); }); </script> <style type="text/css"> #cc{ text-align: center; color: blue; font-size: 30px; } </style> </head> <body> <div class="img2"> <div id="main"> <td><a id="cc" href="pages/snacks/snacks_f.jsp">查询</a></td> <table> <tr> <td>名称</td> <td>价格</td> <td>销量</td> <td>库存</td> <td colspan="2">操作</td> </tr> <c:forEach items="${requestScope.snacks}" var="snacks"> <tr> <td>${snacks.name}</td> <td>${snacks.price}</td> <td>${snacks.sales}</td> <td>${snacks.stock}</td> <td><a href="snacksServlet?action=getSnacks&id=${snacks.id}">修改</a></td> <td><a class="deleteClass" href="snacksServlet?action=delete&id=${snacks.id}">删除</a></td> </tr> </c:forEach> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td><a href="pages/snacks/snacks_edit.jsp">添加</a></td> </tr> </table> </div> <%@include file="/pages/common/footer.jsp"%> </div> </body> </html>
添加或修改商品操作snacks_edit.jsp
<%-- Created by IntelliJ IDEA. User: 29231 Date: 2022/4/30 Time: 20:16 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>编辑商品</title> <%@include file="/pages/common/head.jsp"%> <style type="text/css"> input{ text-align: center; } #submit{ color: darkred; } </style> </head> <body> <div class="img2"> <form action="snacksServlet" method="post"> <input type="hidden" name="action" value="${empty param.id?"add":"update"}"/> <input type="hidden"name="id" value="${requestScope.snacks.id}"/> <table> <tr> <td>名称</td> <td>价格</td> <td>销量</td> <td>库存</td> <td colspan="2">操作</td> </tr> <tr> <td> <input type="text"name="name" value="${requestScope.snacks.name}"/></td> <td><input type="text"name="price" value="${requestScope.snacks.price}"/></td> <td><input type="text"name="sales"value="${requestScope.snacks.sales}"/></td> <td><input type="text"name="stock"value="${requestScope.snacks.stock}"/></td> <td><input id="submit" type="submit"value="提交"/></td> </tr> </table> </form> <%@include file="/pages/common/footer.jsp"%> </div> </body> </html>
查询操作snacks_f.jsp
<%-- Created by IntelliJ IDEA. User: 29231 Date: 2022/5/1 Time: 1:19 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>查询</title> <%@include file="/pages/common/head.jsp"%> </head> <body> <div class="img2"> <div id="main"> <div id="book"> <div class="book_cond"> <form action="snacksServlet" method="post"> <input type="hidden"name="action" value="querySnacksByprice"/> <label for="m">价格</label> <input id="m" type="text"name="min" value="${requestScope.min}">元- <input type="text" name="max"value="${requestScope.max}">元 <input type="submit" value="查询"/> </form> </div> </div> </div> <br/> <br/> <%@include file="/pages/common/footer.jsp"%> </body> </div> </html>
web.xml
<servlet> <servlet-name>SnacksServlet</servlet-name> <servlet-class>web.SnacksServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SnacksServlet</servlet-name> <url-pattern>/snacksServlet</url-pattern> </servlet-mapping>
首页index.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <jsp:forward page="/pages/user/login.jsp"></jsp:forward>
页面展示
首页(登录页面)、
注册页面
登录成功后商品功能页面
所需要的jar包
在运行项目中可能会出现jdbcUtils连接失败;可能原因是mysql.jar导入失败 重新导入;
在运行项目中还可能会出现Servlet页面跳转不进去,可能是Servlet.jar导入失败 重新导入
总结,在写项目时一般不会出现啥问题,需要注意的地方就是包的导入