#创建数据库
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,'清爽冰凉随心爽!');
在idea中创建有关类
web中写jsp页面,index.jsp是首页布局
这是JavaWeb项目
开始学习JavaWeb吧!
登录
注册
运行效果如下:
登录页面
登录
登录
运行效果如下:
注册页面
注册
运行效果如下:
登陆正确时跳转到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" %>
登录
登陆成功!
欢迎来到项目主页
商品编号
商品名称
商品价格
商品说明
<%
//获取session
HttpSession session1 = request.getSession();
//从session中取出数据
List goodsList = (List) session1.getAttribute("goodsList");
//遍历集合元素
for (Goods goods : goodsList) {
%>
<%=goods.getGid()%>
<%=goods.getGname()%>
<%=goods.getPrice()%>
<%=goods.getMark()%>
<%
}
%>
运行效果如下:
在登陆页面,密码或用户名输入错误时跳转到error.jsp再返回login.jsp登陆页面
错误页
出错啦!
返回登陆
效果如图所示:
用户实体类代码如下:
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;
}
@Override
public 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;
}
@Override
public 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 selectAll() {
List 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;
}
}
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 史佳宁 2023/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 selectAll() {
List 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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected 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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//查询所有商品信息
GoodsDao goodsDao=new GoodsDao();
List 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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//查询所有商品信息
GoodsDao goodsDao=new GoodsDao();
List 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: ss
Date: 2023/2/20
Time: 14:46
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" %>
主页
欢迎来自${user.address}的${user.username}访问项目主页
添加商品
商品编号
商品名称
商品价格
商品说明
${goods.gid}
${goods.gname}
${goods.price}
${goods.mark}
修改
删除
返回到登录页面登录商品页面
添加时跳转的页面,代码如下
<%--
Created by IntelliJ IDEA.
User: ss
Date: 2023/2/24
Time: 11:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
商品信息添加
商品信息录入
效果如图
功能代码
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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected 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: \ss
Date: 2023/2/25
Time: 15:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
商品信息修改
商品信息录入
获取当前点击修改商品信息的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 {
@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 {
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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected 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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected 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);
}
}
}