MySQL部分
#创建数据库create database 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','信阳');create table t_goods(gid int primary key auto_increment,gname varchar(20),price double,mark varchar(100));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,'清爽冰凉随心爽!');
Java部分
在idea中创建有关类
web中写jsp页面,index.jsp是首页布局
<html><head><title>这是JavaWeb项目</title></head><body><h2>开始学习JavaWeb吧!</h2><a href="login.jsp">登录</a><a href="zhuce.jsp">注册</a></body></html>
运行效果如下:
登录页面
<html><head><title>登录</title></head><body><h2>登录</h2><form action="login" method="post">账号:<input type="text" name="username" value=""/><br/>密码:<input type="password" name="password" value=""/><br/><input type="submit" value="登录"> <a href="zhuce.jsp">没有账号?请注册</a></form></body></html>
运行效果如下:
注册页面
<html><head><title>注册</title></head><body><form action="zhuce" method="post">账号:<input type="text" name="username" value=""><br>密码:<input type="password" name="password" value=""><br>电话:<input type="text" name="phone"><br>地址:<input type="text" name="address"><input type="submit" value="注册"><a href="login.jsp">已有帐号?请登录</a></form></body></html>
运行效果如下:
登陆正确时跳转到zhuye.jsp主页页面(使用Java脚本获取集合中对象的元素,放html标签中)
<%@ page import="java.util.List" %><%@ page import="com.shi.bean.Goods" %><%--Created by IntelliJ IDEA.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>登录</title></head><body><h2>登陆成功!</h2><h3>欢迎来到项目主页</h3><table><thead><tr><th>商品编号</th><th>商品名称</th><th>商品价格</th><th>商品说明</th></tr></thead><tbody id="list"><%//获取sessionHttpSession session1 = request.getSession();//从session中取出数据List<Goods> goodsList = (List<Goods>) session1.getAttribute("goodsList");//遍历集合元素for (Goods goods : goodsList) {%><!--使用Java脚本获取集合中对象的元素,放html标签中--><tr><td><%=goods.getGid()%></td><td><%=goods.getGname()%></td><td><%=goods.getPrice()%></td><td><%=goods.getMark()%></td></tr><%}%></tbody></table></body></html>
运行效果如下:
在登陆页面,密码或用户名输入错误时跳转到error.jsp再返回login.jsp登陆页面
<html><head><title>错误页</title></head><body><h2>出错啦!</h2><a href="login.jsp">返回登陆</a></body></html>
效果如图所示:
用户实体类代码如下:
package com.shi.bean;public class User {private int uid;private String username;private String password;private String phone;private String address;public int getUid() {return uid;}public String getUsername() {return username;}public String getPassword() {return password;}public String getPhone() {return phone;}public String getAddress() {return address;}public void setUid(int uid) {this.uid = uid;}public void setUsername(String username) {this.username = username;}public void setPassword(String password) {this.password = password;}public void setPhone(String phone) {this.phone = phone;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "User{" +"uid=" + uid +", username='" + username + '\'' +", password='" + password + '\'' +", phone='" + phone + '\'' +", address='" + address + '\'' +'}';}}package com.shi.bean;public class Goods {private int gid;private String gname;private Double price;private String mark;public int getGid() {return gid;}public void setGid(int 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;}@Overridepublic String toString() {return "Goods{" +"gid=" + gid +", gname='" + gname + '\'' +", price=" + price +", mark='" + mark + '\'' +'}';}}
功能逻辑类UserDao
package com.shi.dao;import com.shi.bean.User;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;public class UserDao {private static String jdbcDriver = "com.mysql.jdbc.Driver";private static String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";private static String jdbcUser = "root";private static String jdbcPwd = "root";private Connection con = null; //数据库连接对象private PreparedStatement pstm = null; //预处理对象private ResultSet rs = null; //结果集对象private int row = 0; //增删改受影响的行数public User login(String username, String password) {User login = null;try {Class.forName(jdbcDriver);con = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd);String sql = "select * from t_user where username=? and password=?";pstm = con.prepareStatement(sql);pstm.setObject(1, username);pstm.setObject(2, password);rs = pstm.executeQuery();if (rs.next()) {//从结果集中取出数据,封装到User对象中login = new User();login.setUid(rs.getInt("uid"));login.setUsername(rs.getString("username"));login.setPassword(rs.getString("password"));login.setPhone(rs.getString("phone"));login.setAddress(rs.getString("Address"));}} catch (Exception e) {e.printStackTrace();} finally {try {if (rs != null) {rs.close();}if (pstm != null) {rs.close();}if (con != null) {rs.close();}} catch (Exception e) {e.printStackTrace();}}return login;}public int add(User user) {try {Class.forName(jdbcDriver);con = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd);String sql = "insert into t_user(username,password,phone,address) values(?,?,?,?)";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 {if (rs != null) {rs.close();}if (pstm != null) {rs.close();}if (con != null) {rs.close();}} catch (Exception e) {e.printStackTrace();}}return row;}}
功能逻辑类GoodsDao
package com.shi.dao;import com.shi.bean.Goods;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;public class GoodsDao {//连接数据库的四大参数private static String jdbcDriver = "com.mysql.jdbc.Driver";private static String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";private static String jdbcUser = "root";private static String jdbcPwd = "root";private Connection con = null; //数据库连接对象private PreparedStatement pstm = null; //预处理对象private ResultSet rs = null; //结果集对象public List<Goods> selectAll() {List<Goods> goodsList = new ArrayList<>();try {Class.forName(jdbcDriver);con = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd);String sql = "select*from t_goods";pstm = con.prepareStatement(sql);rs = pstm.executeQuery();while (rs.next()) {Goods goods = new Goods();//从结果集中获取数据,封装到Goods对象中goods.setGid(rs.getInt("gid"));goods.setGname(rs.getString("gname"));goods.setPrice(rs.getDouble("price"));goods.setMark(rs.getString("mark"));//把当前行对应的对象存储到集合中goodsList.add(goods);}} catch (Exception e) {e.printStackTrace();} finally {try {if (rs != null) {rs.close();}if (pstm != null) {rs.close();}if (con != null) {rs.close();}} catch (Exception e) {e.printStackTrace();}}return goodsList;}}
Login逻辑代码
package com.shi.dao;import com.shi.bean.Goods;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;/*** @author 史佳宁 /2/20 16:36* @version 1.0*/public class GoodsDao {//连接数据库的四大参数private static String jdbcDriver = "com.mysql.jdbc.Driver";private static String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";private static String jdbcUser = "root";private static String jdbcPwd = "root";private Connection con = null; //数据库连接对象private PreparedStatement pstm = null; //预处理对象private ResultSet rs = null; //结果集对象public List<Goods> selectAll() {List<Goods> goodsList = new ArrayList<>();try {Class.forName(jdbcDriver);con = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd);String sql = "select*from t_goods";pstm = con.prepareStatement(sql);rs = pstm.executeQuery();while (rs.next()) {Goods goods = new Goods();//从结果集中获取数据,封装到Goods对象中goods.setGid(rs.getInt("gid"));goods.setGname(rs.getString("gname"));goods.setPrice(rs.getDouble("price"));goods.setMark(rs.getString("mark"));//把当前行对应的对象存储到集合中goodsList.add(goods);}} catch (Exception e) {e.printStackTrace();} finally {try {if (rs != null) {rs.close();}if (pstm != null) {rs.close();}if (con != null) {rs.close();}} catch (Exception e) {e.printStackTrace();}}return goodsList;}}
Zhuce逻辑代码
package com.shi.servlet;import com.shi.bean.User;import com.shi.dao.UserDao;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;//设置当前类用来处理/register的请求@WebServlet("/zhuce")public class Zhuce extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1.设置编码req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=UTF-8");//2.获取请求参数String username=req.getParameter("username");String password=req.getParameter("password");String phone=req.getParameter("phone");String address=req.getParameter("address");//封装:把上面所有的变量装载到User对象中User user=new User();user.setUsername(username);user.setPassword(password);user.setPhone(phone);user.setAddress(address);//3:执行业务处理---jdbc的操作UserDao userDao=new UserDao();int row = userDao.add(user);if(row>0){resp.sendRedirect("login.jsp");//指定跳转的页面}else {resp.sendRedirect("error.jsp");}}}
SelectAllGoods逻辑代码
package com.shi.servlet;import com.shi.bean.Goods;import com.shi.dao.GoodsDao;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.util.List;@WebServlet("/selectAllGoods")public class SelectAllGoods extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//查询所有商品信息GoodsDao goodsDao=new GoodsDao();List<Goods> goodsList=goodsDao.selectAll();System.out.println(goodsList);//把数据传递到前端页面//通过request获取session对象,该对象可以向前端传输数据内容HttpSession session = req.getSession();//向session中存入商品信息集合session.setAttribute("goodsList",goodsList);//登陆成功,跳转到主页resp.sendRedirect("zhuye.jsp");//跳转到指定页面}}
登录成功后跳转到主页并展示数据库的商品信息效果如下:
重新查看展示数据,请求转发给SelectAllGoods
package com.shi.servlet;import com.shi.bean.Goods;import com.shi.dao.GoodsDao;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.util.List;@WebServlet("/selectAllGoods")public class SelectAllGoods extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//查询所有商品信息GoodsDao goodsDao=new GoodsDao();List<Goods> goodsList=goodsDao.selectAll();System.out.println(goodsList);//把数据传递到前端页面//通过request获取session对象,该对象可以向前端传输数据内容HttpSession session = req.getSession();//向session中存入商品信息集合session.setAttribute("goodsList",goodsList);//登陆成功,跳转到主页resp.sendRedirect("zhuye.jsp");//跳转到指定页面}}
主页代码
<%@ page import="java.util.List" %><%@ page import="com.shi.bean.Goods" %><%--Created by IntelliJ IDEA.User: ssDate: /2/20Time: 14:46To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><!--导入JSTL的核心类库--><%@ taglib prefix="c" uri="/jsp/jstl/core" %><html><head><title>主页</title></head><body><h2>欢迎来自${user.address}的${user.username}访问项目主页</h2><a href="addGoods.jsp">添加商品</a><table><thead><tr><th>商品编号</th><th>商品名称</th><th>商品价格</th><th>商品说明</th></tr></thead><tbody id="list"><!--items:要遍历的集合对象(写EL表达式)--><c:forEach items="${goodsList}" var="goods"><tr><td>${goods.gid}</td><td>${goods.gname}</td><td>${goods.price}</td><td>${goods.mark}</td><td><a href="findById?gid=${goods.gid}">修改</a><a href="dell?gid=${goods.gid}">删除</a></td></tr></c:forEach></tbody></table></body></html>
返回到登录页面登录商品页面
商品添加
添加时跳转的页面,代码如下
<%--Created by IntelliJ IDEA.User: ssDate: /2/24Time: 11:52To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>商品信息添加</title></head><body><h2>商品信息录入</h2><form action="addGoods" method="post">商品名称:<input type="text"name="gname" value="" placeholder="商品名称"><br/>商品价格:<input type="number" step="0.01" name="price" value="" placeholder="商品价格"><br/>商品说明:<input type="textr" name="mark" value="" placeholder="商品说明"><br/><input type="submit" value="添加"></form></body></html>
效果如图
功能代码
package com.shi.servlet;import com.shi.bean.Goods;import com.shi.dao.GoodsDao;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet("/addGoods")public class AddGoods extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");Goods goods=new Goods();goods.setGname(req.getParameter("gname"));goods.setPrice(Double.parseDouble(req.getParameter("price"))); //获取字符串数字转化为double数据goods.setMark(req.getParameter("mark"));GoodsDao goodsDao=new GoodsDao();int row=goodsDao.add(goods);if (row>0){req.getRequestDispatcher("selectAllGoods").forward(req,resp);}else {req.setAttribute("error_msg","添加商品信息失败!");req.getRequestDispatcher("error.jsp").forward(req,resp);}}}
商品修改
页面代码如下
<%--Created by IntelliJ IDEA.User: \ssDate: /2/25Time: 15:14To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>商品信息修改</title></head><body><h2>商品信息录入</h2><form action="updateGoods" method="post">商品编号:<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" step="0.01" name="price" value="${goods.price}" placeholder="商品价格"><br/>商品说明:<input type="textr" name="mark" value="${goods.mark}" placeholder="商品说明"><br/><input type="submit" value="修改"></form></body></html>
获取当前点击修改商品信息的id,向页面传输id
package com.shi.servlet; import com.shi.bean.Goods;import com.shi.dao.GoodsDao;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;@WebServlet("/findById")public class FindGoodsById extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int gid=Integer.parseInt(request.getParameter("gid"));//根据gid查询商品信息GoodsDao goodsDao=new GoodsDao();Goods goods = goodsDao.selectById(gid);if (goods!=null){//把数据存储到request域对象中,然后请求转发到页面request.setAttribute("goods",goods);request.getRequestDispatcher("showGoods.jsp").forward(request,response);}else {//登陆失败,跳转到错误页面request.setAttribute("error_msg","修改页面出现异常!");request.getRequestDispatcher("error.jsp").forward(request,response);}}}
实现代码如下
package com.shi.servlet;import com.shi.bean.Goods;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet("/updateGoods")public class UpdateGoods extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");//获取表单去哦那个球的数据,封装到goods对象中Goods goods=new Goods();goods.setGid(Integer.parseInt(req.getParameter("gid")));goods.setGname(req.getParameter("gname"));goods.setPrice(Double.parseDouble(req.getParameter("price")));goods.setMark(req.getParameter("mark"));System.out.println(goods);}}
逻辑代码
public int add(Goods goods) {try {Class.forName(jdbcDriver);con = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd);String sql = "insert into t_goods(gname,price,mark) values(?,?,?)";pstm = con.prepareStatement(sql);pstm.setObject(1, goods.getGname());pstm.setObject(2, goods.getPrice());pstm.setObject(3, goods.getMark());row = pstm.executeUpdate();} catch (Exception e) {e.printStackTrace();}try {if (rs != null) {rs.close();}if (pstm != null) {rs.close();}if (con != null) {rs.close();}} catch (Exception e) {e.printStackTrace();}return row;}
商品删除
也是获取当前商品id,根据id进行修改操作
GoodsDao逻辑代码
public int deleteById(int gid) {try {Class.forName(jdbcDriver);con = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd);String sql = "delete from t_goods where gid=?";pstm = con.prepareStatement(sql);pstm.setObject(1, gid);row=pstm.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {try {} catch (Exception e) {e.printStackTrace();}}return row;}
select实现功能代码
package com.shi.servlet;import com.shi.dao.GoodsDao;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet("/dell")public class DellGoods extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {int gid=Integer.parseInt(req.getParameter("gid"));//根据id执行数据库的删除GoodsDao goodsDao=new GoodsDao();int row=goodsDao.deleteById(gid);if (row>0){req.getRequestDispatcher("selectAllGoods").forward(req,resp);}else {//请求转发,查询所有商品信息(刷新)req.setAttribute("error_msg","删除出现了问题!");req.getRequestDispatcher("error.jsp").forward(req,resp);}}}