第一步 我们先MySQL创建数据库,写数据
user表
DROP DATABASE IF EXISTS login;
#创建表
CREATE TABLE user(
uid int PRIMARY KEY AUTO_INCREMENT,
uname VARCHAR(32),
password VARCHAR(32),
phone VARCHAR(11),
address VARCHAR(64)
);
INSERT INTO user(uname,password,phone,address) VALUES(‘张三’,’666′,’18965423548′,’南阳’);
INSERT INTO user(uname,password,phone,address) VALUES(‘李四’,’333′,’18754263548′,’许昌’);
INSERT INTO user(uname,password,phone,address) VALUES(‘小美’,’123′,’18565234759′,’信阳’);
4.查询表
create table goods(
gid int PRIMARY KEY AUTO_INCREMENT,
gname VARCHAR(32),
price DOUBLE,
mark VARCHAR(128)
);
INSERT INTO goods(gname,price,mark) VALUES(‘泡面’,4.5,’够香够辣就是这个味!’);
INSERT INTO goods(gname,price,mark) VALUES(‘火腿’,8.5,’肉质细腻Q弹!’);
INSERT INTO goods(gname,price,mark) VALUES(‘雪碧’,3.5,’清爽冰凉随心爽!’);
2.查询表
#判断存在即删除
DROP DATABASE IF EXISTS login;
#创建数据库
CREATE DATABASE login;
#使用数据库
use login;
#创建表
CREATE TABLE user(
uid int PRIMARY KEY AUTO_INCREMENT,
uname VARCHAR(32),
password VARCHAR(32),
phone VARCHAR(11),
address VARCHAR(64)
);
INSERT INTO user(uname,password,phone,address) VALUES('张三','666','18965423548','南阳');
INSERT INTO user(uname,password,phone,address) VALUES('李四','333','18754263548','许昌');
INSERT INTO user(uname,password,phone,address) VALUES('小美','123','18565234759','信阳');
SELECT * FROM user WHERE uname = ? AND password = ?;
SELECT * FROM user;
create table goods(
gid int PRIMARY KEY AUTO_INCREMENT,
gname VARCHAR(32),
price DOUBLE,
mark VARCHAR(128)
);
INSERT INTO goods(gname,price,mark) VALUES('泡面',4.5,'够香够辣就是这个味!');
INSERT INTO goods(gname,price,mark) VALUES('火腿',8.5,'肉质细腻Q弹!');
INSERT INTO goods(gname,price,mark) VALUES('雪碧',3.5,'清爽冰凉随心爽!');
select * from goods;
第二步 在IDEA中写出这两个表对应的Java实体类
User类
package com.chen.bean;
public class User {
private Integer id;
private String uname;
private String password;
private String phone;
private String address;
public User() {
}
public User(Integer id, String uname, String password, String phone, String address) {
this.id = id;
this.uname = uname;
this.password = password;
this.phone = phone;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", uname='" + uname + ''' +
", password='" + password + ''' +
", phone='" + phone + ''' +
", address='" + address + ''' +
'}';
}
}
Goods类
package com.chen.bean;
class Goods {
private Integer gid;
private String gname;
private Double price;
private String mark;
public Goods(Integer gid, String gname, Double price, String mark) {
this.gid = gid;
this.gname = gname;
this.price = price;
this.mark = mark;
}
public Goods() {
}
@Override
public String toString() {
return "zhuye{" +
"gid=" + gid +
", gname='" + gname + ''' +
", price=" + price +
", mark='" + mark + ''' +
'}';
}
public Integer getGid() {
return gid;
}
public void setGid(Integer gid) {
this.gid = gid;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
}
第三步 在web下的.jsp中写出 首页(index.jsp) ,登录失败页面(error.jsp) ,登录页面(login.jsp), 注册页面(register.jsp),主页(zhuye.jsp),添加页面(addGoods.jsp),修改页面(showGoods)。
1.首页
<%--
Created by IntelliJ IDEA.
User: chenge
Date: 2023/2/13
Time: 19:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>这是一个web项目</title>
</head>
<body style ="background-image: url(img/01.jpg); background-size: 100% 100%">
<div align="center" style="width: 80px; height: 80px; margin:250px auto ; fbacground-color: rgba(170,223,255,70%)">
<a href="login.jsp" style="font-size: 30px">登录</a>
<a href="register.jsp" style="font-size: 30px">注册</a>
</div>
</body>
</html>
2.登录页面
<%--
Created by IntelliJ IDEA.
User: chenge
Date: 2023/2/14
Time: 10:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页</title>
</head>
<body>
<form action="login" method="post">
账号:<input type="text" name="uname" value=""><br>
密码:<input type="password" name="password" value=""><br>
<input type="submit" value="登录">&nbsp;&nbsp;&nbsp;
<a href="register.jsp">没有账号?请注册</a>
</form>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: chenge
Date: 2023/2/17
Time: 19:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误页</title>
</head>
<body style="margin:200px auto">
<h1>出错啦</h1>
<a href="login.jsp">返回登录</a>
</body>
</html>
4.注册页面
<%--
Created by IntelliJ IDEA.
User: chenge
Date: 2023/2/14
Time: 10:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>zhuce</title>
</head>
<body>
<form action="register" method="post">
账号:<input type="text" name="uname" value=""><br>
密码:<input type="password" name="password" value=""><br>
手机号:<input type="text" name="phone" value=""><br>
地址:<input type="text" name="address" value=""><br>
确认密码:<input type="password" name="password1" value=""><br>
<input type="submit" value="注册页面">&nbsp;&nbsp;&nbsp;
<a href="login.jsp">已有账号?请登录</a>
</form>
</body>
</html>
<%
%>
session在网络应用中称为“会话控制”,是服务器为了保存用户状态而创建的一个特殊的对象。简而言之,session就是一个对象,用于存储信息。
<%--
Created by IntelliJ IDEA.
User: chenge
Date: 2023/2/17
Time: 19:35
To change this template use File | Settings | File Templates.
--%>
<%@taglib prefix="a" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body style="background-image: url(img/01.jpg); background-size: 100% 100% ">
<!-- EL 表达式 通过 $ { }从作用域对象中获取数据,如果该数据库是对象,则可以通过是对象名,属性名获取其数值-->
<h2>欢迎来自${user.address}的${user.uname}访问项目主页</h2>
<form action="seach" method="post">
<input type="text" name="keyword" value="">
<input type="submit" value="搜索">
</form>
<a href="addGoods.jsp">添加商品</a>
<table >
<thead>
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品说明</th>
</tr>
</thead>
<tbody id="list" >
<!--items:要遍历的集合对象 var:集合中对应的临时对象-->
<a: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="del?gid=${goods.gid}" onclick="return confirm('确定将此条数据删除?')">删除</a>
</td>
</tr>
</a:forEach>
</tbody>
</table>
</body>
</html>
6.添加页面
<%--
Created by IntelliJ IDEA.
User: chenge
Date: 2023/2/25
Time: 13:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>商品信息的添加</title>
</head>
<body>
<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="text" name="mark" value="" placeholder="商品说明"><br>
<input type="submit" value="添加商品">
</form>
</body>
</html>
7.修改页面
<%--
Created by IntelliJ IDEA.
User: chenge
Date: 2023/2/27
Time: 8:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>商品信息的修改</title>
</head>
<body>
<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="text" name="mark" value="${goods.mark}" placeholder="商品说明"><br>
<input type="submit" value="修改商品">
</form>
</body>
</body>
</html>
第四步 JDBC操作层面
1.在src里建三个包 Dao,httpServlet,Util
2.在Dao中先创建两个接口 这里起名叫UserDao,GoodsDao
UserDao
package com.chen.Dao;
import com.chen.bean.User;
public interface UserDao {
/**
* 完成登陆操作
* @param uname 用户名
* @param password 密码
* @return 数据库查询的用户信息对象
*/
User login(String uname,String password);
/**
* 注册用户
* @param user 封装的注册信息
* @return 受影响的行数
*/
int register(User user);
}
GoodsDao
这里我们写方法,在impl里GoodsDaoImpl中调用方法。
package com.chen.Dao;
import com.chen.bean.Goods;
import java.util.List;
public interface GoodsDao {
//全查
public List<Goods> slectAll();
public Goods selectById(int gid);
//增
public int selectInsert(Goods goods);
//删
public int selectDelete(int gid);
//改
public int selectUpdate(Goods goods);
}
3.再在Dao.impl中创建UserDaoImpl类,用这个类去继承UserDao接口,这里面写登录、注册JDBC的操作,用了分层操作,JDBC驱动、连接、调用方法、关闭资源 都在Util包中,httpservlet里写。
util包-JDBCUtil类
package com.chen.Util;
import com.chen.bean.User;
import java.security.PublicKey;
import java.sql.*;
public class JDBCUtil {
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1:3306/login?useSSL=false&serverTimezone=UTC";
private static String user = "root";
private static String password = "root";
private static Connection conn = null;
public static Connection getCon() {
try {
//1.加载数据库驱动
Class.forName(driver);
//2.获取数据库连接
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//JDBCUtil.getCon()方法
public static void main(String[] args) {
System.out.println(JDBCUtil.getCon());
}
//登录的关闭资源
public static void close(ResultSet rs,PreparedStatement pstm,Connection conn) {
try {
if (rs!=null){
rs.close();
}
if (pstm!=null){
pstm.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
//注册的关闭资源
public static void close(PreparedStatement pstm, Connection conn) {
try {
if (pstm!=null){
pstm.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
UserDaoImpl
package com.chen.Dao.imlp;
import com.chen.Dao.UserDao;
import com.chen.Util.JDBCUtil;
import com.chen.bean.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao {
User login = null;
Connection conn = null; //数据库连接对象
PreparedStatement pstm = null; //预处理对象
ResultSet rs = null; //结果集对象
int i = 0;
//登录
public User login (String uname, String password){
try{
conn = JDBCUtil.getCon();
//3.sql语句
String sql = "select * from user where uname=? and password=?";
//4.获取预处理对象
pstm = conn.prepareStatement(sql);
//5.传参
pstm.setObject(1,uname);
pstm.setObject(2,password);
//6.执行查询
rs = pstm.executeQuery();
//7.解析结果集
if (rs.next()){
login = new User();
//从结果集中获取数据,封装到实体类对象中
int uid = rs.getInt("uid");
login.setId(uid);
login.setUname(rs.getString("uname"));
login.setPassword(rs.getString("password"));
login.setPhone(rs.getString("phone"));
login.setAddress(rs.getString("address"));
}
} catch (Exception throwables) {
throwables.printStackTrace();
}finally {
//8.关闭资源
JDBCUtil.close(rs,pstm,conn);
}
return login;
}
@Override
//注册
public int register(User user) {
try {
conn = JDBCUtil.getCon();
String sql = "insert into user(uname,password,phone,address) values(?,?,?,?)";
pstm = conn.prepareStatement(sql);
pstm.setObject(1,user.getUname());
pstm.setObject(2,user.getPassword());
pstm.setObject(3,user.getPhone());
pstm.setObject(4,user.getAddress());
i = pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(pstm,conn);
}
return i;
}
}
GoodsDaoImpl
在这里面就要完成全查的操作、添加操作、删除操作、修改操作根据id查找那条数据展现在页面中,再去写sql的修改代码操作。
package com.chen.Dao.imlp;
import com.chen.Dao.GoodsDao;
import com.chen.Util.JDBCUtil;
import com.chen.bean.Goods;
import com.chen.bean.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class GoodsDaoImpl implements GoodsDao {
private User login = null;
private Connection conn = null; //数据库连接对象
private PreparedStatement pstm = null; //预处理对象
private ResultSet rs = null; //结果集对象
private int i = 0; //增删改受影响的行数
//全查
@Override
public List<Goods> slectAll() {
List<Goods> goodslist = new ArrayList<>();
try {
conn = JDBCUtil.getCon();
//3.sql语句
String sql = "select * from goods";
//4.获取预处理对象
pstm = conn.prepareStatement(sql);
//5.执行查询
rs = pstm.executeQuery();
Goods goods=null;
//6.解析结果集
while (rs.next()){
goods = new 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){
pstm.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return goodslist;
}
//模糊查询
public List<Goods> seach(String keyword) {
List<Goods> goodslist = new ArrayList<>();
try {
conn = JDBCUtil.getCon();
//3.sql语句
String sql = "select * from goods where gname like concat('%',?,'%')";
//4.获取预处理对象
pstm = conn.prepareStatement(sql);
pstm.setObject(1,keyword);
//5.执行查询
rs = pstm.executeQuery();
//6.解析结果集
while (rs.next()){
goods = new 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){
pstm.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return goodslist;
}
//id查询
public Goods selectById(int gid){
Goods goods = null;
try {
conn = JDBCUtil.getCon();
//3.sql语句
String sql = "select * from goods where gid=?";
//4.获取预处理对象
pstm = conn.prepareStatement(sql);
pstm.setObject(1,gid);
//5.执行查询
rs = pstm.executeQuery();
//6.解析结果集
if (rs.next()){
goods = new Goods();
goods.setGid(rs.getInt("gid"));
goods.setGname(rs.getString("gname"));
goods.setPrice(rs.getDouble("price"));
goods.setMark(rs.getString("mark"));
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (rs!=null){
rs.close();
}
if (pstm!=null){
pstm.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return goods;
}
//添加数据
@Override
public int selectInsert(Goods goods) {
try {
conn = JDBCUtil.getCon();
//3.sql语句
String sql = "insert into goods(gname,price,mark) values (?,?,?)";
//4.获取预处理对象
pstm = conn.prepareStatement(sql);
pstm.setObject(1,goods.getGname());
pstm.setObject(2,goods.getPrice());
pstm.setObject(3,goods.getMark());
//5.执行查询
i = pstm.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (pstm!=null){
pstm.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return i;
}
//删除
@Override
public int selectDelete(int gid) {
System.out.println("selectDelete");
try {
conn = JDBCUtil.getCon();
//3.sql语句
String sql = "delete from goods where gid=?";
//4.获取预处理对象
pstm = conn.prepareStatement(sql);
pstm.setObject(1,gid);
//5.执行查询
i = pstm.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (pstm!=null){
pstm.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return i;
}
//修改
@Override
public int selectUpdate(Goods goods) {
try {
conn = JDBCUtil.getCon();
//3.sql语句
String sql = "update goods set gname=?,price=?,mark=? where gid=?";
//4.获取预处理对象
pstm = conn.prepareStatement(sql);
pstm.setObject(1,goods.getGname());
pstm.setObject(2,goods.getPrice());
pstm.setObject(3,goods.getMark());
pstm.setObject(4,goods.getGid());
//5.执行查询
i = pstm.executeUpdate();
System.out.println("i="+i);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (pstm!=null){
pstm.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return i;
}
}
第五步 业务处理层面
1.设置请求和响应的编码格式 2.获取请求的参数 3.执行业务处理
Login
@WebServlet(“/login”)
请求:
request.getRequestDispatcher(” “).forward(request,response);//请求别的地址
package com.chen.httpServlet;
import com.chen.Dao.UserDao;
import com.chen.Dao.imlp.UserDaoImpl;
import com.chen.bean.User;
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("/login")
public class Login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Login-get");
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Login-post");
//前端请求(request),后端处理后,最后给前端做出响应(response)
//1.设置请求和响应的编码格式,以及响应的格式
request.setCharacterEncoding("utf-8"); //设置请求的编码格式为中文
response.setCharacterEncoding("utf-8"); //设置响应的编码格式
response.setContentType("text/html;charset=UTF-8"); //以什么样的格式 (文本/网页)响应
//2.获取请求的参数
String uname = request.getParameter("uname"); //根据表单的name属性获取用户输入的值
String password = request.getParameter("password");
//3.执行业务处理
UserDao userDao = new UserDaoImpl();
User login = userDao.login(uname,password);
//判断登录的用户信息是否为空
if (login!=null) {
System.out.println("登录成功!");
//登录成功,当前servlet的业务处理完毕----后续执行查询商品的操作应该由别人来完成---请求转发给别的servlet处理
request.getRequestDispatcher("selectAllGoods").forward(request,response);//请求别的地址
} else {
//登录失败,跳转到错误页
response.sendRedirect("error.jsp");
}
}
}
Register
1.映射地址
@WebServlet(“/register“)
package com.chen.httpServlet;
import com.chen.Dao.UserDao;
import com.chen.Dao.imlp.UserDaoImpl;
import com.chen.bean.User;
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;
import java.sql.*;
@WebServlet("/register")
public class Register extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("register-get");
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("register-post");
//1.设置请求和响应的编码格式,以及响应的格式
request.setCharacterEncoding("utf-8"); //设置请求的编码格式为中文
response.setCharacterEncoding("utf-8"); //设置响应的编码格式
//2.获取请求的参数
String uname = request.getParameter("uname"); //根据表单的name属性获取用户输入的值
String password = request.getParameter("password");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
//封装:把上面所有的变量装载到User对象中
User user = new User();
user.setUname(uname);
user.setPassword(password);
user.setPhone(phone);
user.setAddress(address);
System.out.println(user);
//3.执行业务处理
UserDao userDao = new UserDaoImpl();
int i = userDao.register(user);
//判断登录的用户信息是否为空
if (i > 0) {
//注册成功,跳转到登录页面
response.sendRedirect("login.jsp");//指定跳转的页面
} else {
//登录失败,跳转到错误页
response.sendRedirect("register.jsp");
}
}
}
SelectAllGoods
1.映射地址
@WebServlet(“/selectAllGoods”)
//通过request获取session对象,该对象可以向前端传递传输数据的容器HttpSession session = req.getSession();
package com.chen.httpServlet;
import com.chen.Dao.imlp.GoodsDaoImpl;
import com.chen.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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/selectAllGoods")
public class SelectAllGoods extends HttpServlet {
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("SelectAllGoods..dopost");
//查询所有商品信息
GoodsDaoImpl goodsDao = new GoodsDaoImpl();
List<Goods> goodsList = goodsDao.slectAll();
System.out.println(goodsList);
//把数据传递到前端页面
//通过request获取session对象,该对象可以向前端传递传输数据的容器
HttpSession session = req.getSession();
//向session 中存入商品信息集合
session.setAttribute("goodsList", goodsList);
//登录成功,跳转到主页
resp.sendRedirect("zhuye.jsp");//指定的跳转页面
}
}
InsertGoods
1.映射地址
@WebServlet(“/addGoods”)
package com.chen.httpServlet;
import com.chen.Dao.GoodsDao;
import com.chen.Dao.imlp.GoodsDaoImpl;
import com.chen.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("/addGoods")
public class InsertGoods 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.setGname(req.getParameter("gname"));
//使用Double包装类把req.getParameter获取到字符串数字 转换为 double类型的数据
goods.setPrice(Double.parseDouble(req.getParameter("price")));
goods.setMark(req.getParameter("mark"));
//执行JDBC的添加操作
GoodsDao goodsDao = new GoodsDaoImpl();
int i = goodsDao.selectInsert(goods);
if (i > 0) {
//添加成功
req.getRequestDispatcher("selectAllGoods").forward(req, resp);
} else {
//添加失败
req.setAttribute("error_msg", "添加商品出错了!");
req.getRequestDispatcher("error.jsp").forward(req, resp);
}
}
}
DeleteGoods
1.映射地址
@WebServlet(“/del”)
package com.chen.httpServlet;
import com.chen.Dao.GoodsDao;
import com.chen.Dao.imlp.GoodsDaoImpl;
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("/del")
public class DeleteGoods 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 GoodsDaoImpl();
int i = goodsDao.selectDelete(gid);
if (i>0){
//请求转发,查讯所有商品信息(刷新)
req.getRequestDispatcher("selectAllGoods").forward(req,resp);
}else {
req.setAttribute("error_msg","删除出现了问题!");
req.getRequestDispatcher("error.jsp").forward(req,resp);
}
}
}
FindByIdGoods
1.映射地址
@WebServlet(“/findById”)
package com.chen.httpServlet;
import com.chen.Dao.GoodsDao;
import com.chen.Dao.imlp.GoodsDaoImpl;
import com.chen.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("/findById")
public class FindByIdGoods 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"));
//根据gid查询商品信息
GoodsDao goodsDao = new GoodsDaoImpl();
Goods goods = goodsDao.selectById(gid);
if (goods!= null){
//把数据存储到req域对象中,然后请求转发到页面
req.setAttribute("goods",goods);
req.getRequestDispatcher("showGoods.jsp").forward(req,resp);
}else {
//登录失败,跳转到错误页
req.setAttribute("error_msg","修改出现异常!");
req.getRequestDispatcher("error.jsp").forward(req,resp);
}
}
}
UpdateGoods
1.映射地址
@WebServlet(“/updateGoods”)
package com.chen.httpServlet;
import com.chen.Dao.GoodsDao;
import com.chen.Dao.UserDao;
import com.chen.Dao.imlp.GoodsDaoImpl;
import com.chen.Dao.imlp.UserDaoImpl;
import com.chen.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"));
//执行数据库的修改操作
GoodsDao goodsDao = new GoodsDaoImpl();
goodsDao.selectUpdate(goods)
if (i>0){
//请求转发,查讯所有商品信息(刷新)
req.getRequestDispatcher("selectAllGoods").forward(req,resp);
}else {
req.setAttribute("error_msg","修改失败,请重新尝试!");
req.getRequestDispatcher("error.jsp").forward(req,resp);
}
}
}
Seach
@WebServlet(“/seach“)
package com.chen.httpServlet;
import com.chen.Dao.GoodsDao;
import com.chen.Dao.imlp.GoodsDaoImpl;
import com.chen.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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/seach")
public class Seach 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");
String keyword = req.getParameter("keyword");
//根据关键词执行JDBC的模糊查询
GoodsDao goodsDao = new GoodsDaoImpl();
List<Goods> goodsList = goodsDao.seach(keyword);
//把数据传递到前端页面
//通过request获取session对象,该对象可以向前端传递传输数据的容器
HttpSession session = req.getSession();
//向session 中存入商品信息集合
session.setAttribute("goodsList", goodsList);
//登录成功,跳转到主页
resp.sendRedirect("zhuye.jsp");//指定的跳转页面
}
}
如果注册,注册的信息就存在后台的数据库里,如果注册成功就可以登录成功,在后台数据库里添加商品信息,通过session在主页页面中就能看到商品信息。增删改查操作。
不能随意访问网址就能进入注册、添加、主页页面中,所以我们要写个过滤器,防止外来人员直接访问。
第六步 Filter过滤器
Filter中文意思为过滤器。顾名思义,过滤器可在浏览器以及目标资源之间起到一个过滤的作用。例如:水净化器,可以看成是生活中的一个过滤器,他可以将污水中的杂质过滤,从而使进入的污水变成净水。对于WEB应用来说,过滤器是一个驻留在服务器中的WEB组件,他可以截取客户端和WEB资源之间的请求和响应信息。WEB资源可能包括ServletJSPHTML页面等。
Filter是Tomcat容器内的过滤器,在请求到达容器是先会调用过滤器,再调用我们的servlet或者jsp。
当服务器收到特定的请求后,会先将请求交给过滤器,程序员可以在过滤器中对请求信息进行读取修改等操作,然后将请求信息再发送给目标资源。目标资源作出响应后,服务器会再次将响应转交给过滤器,在过滤器中同样可以对响应信息做一些操作,然后再将响应发送给浏览器。
也就是说过滤器可以在WEB资源收到请求之前,浏览器收到响应之前,对请求和响应信息做一些相应的操作。
在一个WEB应用中可以部署多个过滤器,多个过滤器就组成了一个过滤器链,请求和响应必须在经过多个过滤器后才能到达目标。
过滤器不是必须将请求传送到下一个过滤器(或WEB资源),也可以自己来处理请求,发送响应。
Filter接口,实现Filter需要实现该接口
1、init()方法用于初始化Filter。
2、doFilter()作用和service()方法类似,是过滤请求和响应的主要方法。
3、destroy0用于在Filter对象被销毁前做一些收尾工作。如:释放资源等
Filter的生命周期和Servlet类似
构造器:创建Filter实例是调用,Filter实例服务器一旦启动就会被创建
init():实例创建后马上被调用,用来对Filter做一些初始化的操作
doFilter():Filter的主要方法,用来完成过滤器主要功能的方法,每次访问目标资源时都会调用。
destroy():服务器停止时调用,用来释放资源
首先
映射所有
@WebFilter(“/*”)
因为要登录(+登录的映射地址),没有账号的要注册(+注册的映射地址),登陆失败跳转错误页面,这些页面都需要放行,直接访问主页会回到登录页面。
package com.chen.filter;
import com.chen.bean.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化..");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//1.在过滤器中把servletRequest、servletResponse转换为HttpServletRequest、HttpServletResponse
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//2.获取请求的资源路径
String servletPath = request.getServletPath();
//3.获取session储存的用户对象
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
//4.1如果请求index.jsp、login.jsp、login、register.jsp、register、error.jsp则放行
if (servletPath.equals("/index.jsp") ||servletPath.equals("/login.jsp") ||servletPath.equals("/login") ||servletPath.equals("/register.jsp") ||servletPath.equals("/register") ||servletPath.equals("/error.jsp")){
filterChain.doFilter(servletRequest,servletResponse);//放行
}else if (user!=null){
filterChain.doFilter(servletRequest,servletResponse);//放行
}else {
response.sendRedirect("login.jsp");
}
}
@Override
public void destroy() {
System.out.println("销毁..");
}
}
原文地址:https://blog.csdn.net/weixin_67224308/article/details/129114921
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_39332.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!