编写代码要实现的业务:
登录:完成连接数据库判断登陆信息是否有误
注册:将信息填写完毕后点击注册,跳转到登陆页面
主页:展示项目信息并且可以在页面内进行增删改操作
完整文件目录如下:
文件目录:
bean包中填写的代码为实体类
dao模型就是写一个类,把访问数据库的代码封装起来
servlet包是Java编写的服务器端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容
Util是一个多功能、基于工具的包
代码中易出现的问题:
1.中文乱码问题
中文乱码就是值在请求信息或者响应信息中包含的中文字符不能正常显示。产生原因无非就是客户端与服务器采用的编码方式不同导致的。
根据请求方式的不同,请求一般可以被分为两种:GET请求和POST请求,
POST请求
乱码的原因:POST 提交的数据在请求体中,其所使用的编码格式时页面一致(即utf-8)。request 对象接收到数据之后,会将数据放到request缓冲区,缓冲区的默认字符集是SO-8859-1(该字符集不支持中文),两者使用的字符集不一致导致乱码。
解决方案:在获取请求参数之前设置request缓冲区字符集为utf-8。
// 设置获取数据的格式
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
GET请求和POST请求的区别: 1、 get是从服务器上获取数据,post是向服务器传送数据。 2、 get请求时通过URL直接请求数据,数据信息可以在URL中直接看到,比如浏览器访问;而post请求是放在请求头中的,用户无法直接看到。
所以一般不会使用GET请求
MYSQL代码部分
#判断存在即删除数据库
drop database if exists mydb;
#创建数据库
create database mydb;
#使用数据库
use 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','信阳');
select * from t_user;
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,'清爽冰凉随心爽!');
select * from t_goods;
首页的编写(.jsp文件)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<h1>欢迎学习WEB!</h1>
<a href="login.jsp">去登陆</a><br>
<a href="register.jsp">去注册</a>
</body>
</html>
给客户两个选项(登陆/注册)---完成页面如下
1.1登陆页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陆页面</title>
</head>
<body>
<h1>登陆页面</h1>
<h2>欢迎学习WEB!</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="register.jsp">没有账号?点击注册</a>
</form>
</body>
</html>
1.2注册页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册页面</title>
</head>
<body>
<h1>注册页面</h1>
<form action="register" method="post">
账号:<input type="text" name="username" value=""> <br>
密码:<input type="password" name="password" 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="submit" value="注册">
<a href="login.jsp">已有账号?点击登录</a>
</form>
</body>
</html>
1.3项目页面
由后台数据库传递过来的商品数据:
a:<%之间可以写服务器端代码%>
<%=%>获取后台的变量值
session在网络应用中称为“会话控制”,是服务器为了保存用户状态而创建的一个特殊的对象。 session就是一个对象,用于存储信息
(这段代码可以不写)
<%
// 获取session
HttpSession 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>
<%
}
%>
b: <%--导入JSTL包--%>
<%@taglib prefix="m" uri="http://java.sun.com/jsp/jstl/core" %>
现在导入JSTL包后
可以使用 ${} 直接获取数据 注意:在${}的括号中不能出现空格
<%@ page import="java.util.List" %>
<%@ page import="com.man.bean.Goods" %><%--
Created by IntelliJ IDEA.
User: 小m
Date: 2023/2/16
Time: 12:21
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入JSTL包--%>
<%@taglib prefix="m" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>欢迎来自${user.address}的${user.username}登录项目主页</h1>
<h2>主页信息展示</h2>
<table>
<form action="seach" method="post">
<input type="text" name="keyword" value="">
<input type="submit" value="搜索">
</form>
<br>
<a href="addgoods.jsp">添加商品</a>
<thead>
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品介绍</th>
<th>操作</th>
</tr>
</thead>
<tbody id="list">
<%-- items:要遍历的对象(写EL表达式) var:集合中对应的临时对象 --%>
<m: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}">删除</a>
</td>
</tr>
</m:forEach>
</tbody>
</table>
</body>
</html>
1.4错误页面
${error_msg}可以获取每次页面中的不同信息
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误页</title>
</head>
<body>
<h1>${error_msg}</h1>
<a href="login.jsp">回到登录页</a>
</body>
</html>
1.5添加数据页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加商品页面</title>
</head>
<body>
<h1 >添加商品</h1>
<form action="addGoods" method="post">
商品名称 : <input name="gname" type="text" placeholder="商品名称" value="" >
商品价格 : <input name="price" type="number" step="0.01" placeholder="商品价格" value="" >
商品介绍 : <input name="mark" type="text" placeholder="商品介绍" value="" >
<input type="submit" value="添加">
</form>
</body>
</html>
1.6修改数据页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改商品页面</title>
</head>
<body>
<h1 >修改商品</h1>
<form action="updateGoods" method="post">
商品编号 : <input name="gid" type="number" placeholder="商品编号" value="${goods.gid}" readonly="readonly"><br>
商品名称 : <input name="gname" type="text" placeholder="商品名称" value="${goods.gname}" ><br>
商品价格 : <input name="price" type="number" step="0.01" placeholder="商品价格" value="${goods.price}" ><br>
商品介绍 : <input name="mark" type="text" placeholder="商品介绍" value="${goods.mark}" ><br>
<input type="submit" value="修改">
</form>
</body>
</html>
2.Java代码编写
A.登陆页面后端代码编写
A1.实体类Bean
A1.1 User 类
package com.man.dao;
public class User {
private Integer uid;
private String username;
private String password;
private String phone;
private String address;
public User() {
}
public User(Integer uid, String username, String password, String phone, String address) {
this.uid = uid;
this.username = username;
this.password = password;
this.phone = phone;
this.address = address;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
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 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{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
'}';
}
}
A1.2 Goods 类
package com.man.bean;
public class Goods {
private Integer gid;
private String gname;
private Double price;
private String 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;
}
@Override
public String toString() {
return "Goods{" +
"gid=" + gid +
", gname='" + gname + '\'' +
", price=" + price +
", mark='" + mark + '\'' +
'}';
}
}
A2.dao包
A2.1 GoodsDao:
package com.man.dao;
import com.man.bean.Goods;
import com.man.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class GoodsDao {
Connection con = null;
ResultSet rs = null;
PreparedStatement pstm = null;
int row = 0;
public List<Goods> selectAllGoods() {
List<Goods> goodsList = new ArrayList<>();
try {
// 1.获取链接
con = JDBCUtil.getCon();
// 2.编写sql语句
String sql = "select * from t_goods";
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.执行查询
rs = pstm.executeQuery();
// 5.获取结果集
while (rs.next()) {
Goods 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 {
JDBCUtil.close(rs, con, pstm);
}
return goodsList;
}
public Goods findGoodsById(int gid){
Goods goods = null;
try {
// 1.获取链接
con = JDBCUtil.getCon();
// 2.编写sql语句
String sql = "select * from t_goods where gid=?";
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.传参
pstm.setObject(1,gid);
// 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"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.close(rs, con, pstm);
}
return goods;
}
public int addGoods(Goods goods){
try {
// 1.获取链接
con = JDBCUtil.getCon();
// 2.编写sql语句
String sql = "insert into t_goods(gname,price,mark) values(?,?,?)";
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.传参
pstm.setObject(1,goods.getGname());
pstm.setObject(2,goods.getPrice());
pstm.setObject(3,goods.getMark());
// 5.执行新增
row = pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.close(con, pstm);
}
return row;
}
public int delGoods(int gid){
try {
// 1.获取链接
con = JDBCUtil.getCon();
// 2.编写sql语句
String sql = "delete from t_goods where gid=?";
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.传参
pstm.setObject(1,gid);
// 5.执行新增
row = pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.close(con, pstm);
}
return row;
}
public int updateGoods(Goods goods){
try {
// 1.获取链接
con = JDBCUtil.getCon();
// 2.编写sql语句
String sql = "update t_goods set gname=?,price=?,mark=? WHERE gid = ?";
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.传参
pstm.setObject(1,goods.getGname());
pstm.setObject(2,goods.getPrice());
pstm.setObject(3,goods.getMark());
pstm.setObject(4,goods.getGid());
// 5.执行修改
row = pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.close(con, pstm);
}
return row;
}
public List<Goods> seachGoods(String keyword){
List<Goods> goodsList = new ArrayList<>();
try {
// 1.获取链接
con = JDBCUtil.getCon();
// 2.编写sql语句
String sql = "select * from t_goods where gname like concat('%',?,'%')";
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.传参
pstm.setObject(1,keyword);
// 5.执行查询
rs = pstm.executeQuery();
// 6.获取结果集
while (rs.next()) {
Goods 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 {
JDBCUtil.close(rs, con, pstm);
}
return goodsList;
}
}
A2.2 UserDao 类
package com.man.dao;
import com.man.bean.User;
import com.man.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UserDao {
Connection con = null;
ResultSet rs = null;
PreparedStatement pstm = null;
User login = null;
int row = 0;
public User login(String username, String password) {
try{
// 1.获取数据库连接
con = JDBCUtil.getCon();
// 2.定义登陆的sql语句
String sql = "select * from t_user where username=? and password=?" ;
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.传参
pstm.setObject(1,username);
pstm.setObject(2,password);
// 5.执行查询
rs = pstm.executeQuery();
// 6.解析结果集
if (rs.next()){
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();
}
return login;
}
public int register(User user) {
try{
// 1.获取数据库连接
con = JDBCUtil.getCon();
// 2.定义注册的新增sql语句
String sql = "insert into t_user(username,password,phone,address) values(?,?,?,?)" ;
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.传参
pstm.setObject(1,user.getUsername());
pstm.setObject(2,user.getPassword());
pstm.setObject(3,user.getPhone());
pstm.setObject(4,user.getAddress());
// 5.执行更新(增删改)
row = pstm.executeUpdate();
}catch (Exception e){
e.printStackTrace();
} finally {
JDBCUtil.close(con,pstm);
}
return row;
}
}
A3. servlet包(请求处理)
Login 代码:
package com.man.servlet;
import com.man.bean.User;
import com.man.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 javax.servlet.http.HttpSession;
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-doGet...");
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.设置请求和响应的编码格式,以及响应的格式
request.setCharacterEncoding("utf-8"); // 设置获取数据的格式
response.setCharacterEncoding("utf-8");
// 2.获取请求的参数
String username = request.getParameter("username"); //根据表单的name属性获取用户输入的账号密码
String password = request.getParameter("password");
System.out.println(username);
System.out.println(password);
// 3.执行业务处理
UserDao userDao = new UserDao();
User login = userDao.login(username, password);
// 4.判断登陆信息是否为空
if (login != null) {
HttpSession session = request.getSession();
session.setAttribute("user", login);
// 登陆成功,当前servlet业务处理完毕---后续操作由别人完成---请求别的地址
request.getRequestDispatcher("selectAllGoods").forward(request, response);
} else {
// 登陆失败,传入错误信息并跳转页面
request.setAttribute("error_msg","登陆失败!请重新输入账号或密码!");
request.getRequestDispatcher("error.jsp").forward(request,response);
}
}
}
SelectAllGoods 类:查询所有商品信息
package com.man.servlet;
import com.man.bean.Goods;
import com.man.dao.GoodsDao;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
@WebServlet("/selectAllGoods")
public class SelectAllGoods extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("SelectAllGoods-doGet...");
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.执行查询业务
// 2.查询所有商品信息
GoodsDao goodsDao = new GoodsDao();
List<Goods> goodsList = goodsDao.selectAllGoods();
System.out.println(goodsList);
// 3.把数据传递到前端页面
// 3.1通过request获取session对象,该对象可以向前端传输数据的容器
HttpSession session = request.getSession();
// 4.向session中存入商品信息集合
session.setAttribute("goodsList",goodsList);
// 4.登录成功,跳转到登录页
response.sendRedirect("zhuye.jsp");
}
}
A4. util(工具类文件)
package com.man.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JDBCUtil {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";
private static String user = "root";
private static String psw = "root";
int row = 0;
static Connection con = null;
public static Connection getCon(){
try{
// 1.加载数据库驱动
Class.forName(driver);
// 2.获取数据库连接
con = DriverManager.getConnection(url, user, psw);
} catch (Exception e){
e.printStackTrace();
}
return con;
}
public static void close(ResultSet rs,Connection con,PreparedStatement pstm){
// 关闭资源
try{
if (rs!=null){
rs.close();
}
if (pstm!=null){
pstm.close();
}
if (con!=null){
con.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void close(Connection con,PreparedStatement pstm){
// 关闭资源
try{
if (pstm!=null){
pstm.close();
}
if (con!=null){
con.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
输入正确信息,数据库比对过后进入主页面
反之则进入错误页
B.注册页面
<html>
<head>
<title>注册页面</title>
</head>
<body>
<h1>注册页面</h1>
<form action="register" method="post">
账号:<input type="text" name="username" value=""> <br>
密码:<input type="password" name="password" 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="submit" value="注册">
<a href="login.jsp">已有账号?点击登录</a>
</form>
</body>
</html>
B1.编写注册java代码
package com.man.servlet;
import com.man.bean.User;
import com.man.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;
@WebServlet("/register")
public class Register extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("register-doGet...");
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.设置请求和响应的编码格式,以及响应的格式
request.setCharacterEncoding("utf-8"); // 设置获取数据的格式
response.setCharacterEncoding("utf-8");
// 2.获取请求的参数
String username = request.getParameter("username"); //根据表单的name属性获取用户输入的账号密码
String password = request.getParameter("password");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
System.out.println(username);
System.out.println(password);
System.out.println(phone);
System.out.println(address);
// 封装:把上面所有变量装载到User对象中
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setPhone(phone);
user.setAddress(address);
// 3.执行业务处理
UserDao userDao = new UserDao();
int row = userDao.register(user);
// 4.做出响应
if (row > 0) {
// 注册成功,跳转到登录页
response.sendRedirect("Login.jsp");
} else {
// 注册失败,传入错误信息并跳转页面
request.setAttribute("error_msg","注册失败!请刷新页面或重新打开浏览器!");
request.getRequestDispatcher("error.jsp").forward(request,response);
}
}
}
// 执行业务处理部分用到的代码与登录业务代码在同一 .java 文件中
@Override
public int register(User user) {
try{
// 1.获取数据库连接
con = JDBCUtil.getCon();
// 2.定义注册的新增sql语句
String sql = "insert into t_user(username,password,phone,address) values(?,?,?,?)" ;
// 3.获取预处理对象
pstm = con.prepareStatement(sql);
// 4.传参
pstm.setObject(1,user.getUsername());
pstm.setObject(2,user.getPassword());
pstm.setObject(3,user.getPhone());
pstm.setObject(4,user.getAddress());
// 5.执行更新(增删改)
row = pstm.executeUpdate();
}catch (Exception e){
e.printStackTrace();
} finally {
JDBCUtil.close(con,pstm);
}
return row;
}
输入信息点击 注册,自动跳转登录页
将刚刚注册的账号密码输入,登录进入项目主页
C.主页信息的增,删,改
C1.增
addGoods :
package com.man.servlet;
import com.man.bean.Goods;
import com.man.dao.GoodsDao;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/addGoods")
public class addGoods 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 {
// 1.设置请求和响应的编码格式,以及响应的格式
request.setCharacterEncoding("utf-8"); // 设置获取数据的格式
response.setCharacterEncoding("utf-8");
// 2.实例化对象,存入数据
Goods goods = new Goods();
goods.setGname(request.getParameter("gname"));
goods.setPrice(Double.parseDouble(request.getParameter("price")));
goods.setMark(request.getParameter("mark"));
// 3.执行数据库插入操作
GoodsDao goodsDao = new GoodsDao();
int row = goodsDao.addGoods(goods);
// 4.判断信息
if (row >0){
// 添加成功,请求页面重新查询数据库
request.getRequestDispatcher("selectAllGoods").forward(request,response);
}else {
// 添加失败,传入错误信息并跳转页面
request.setAttribute("error_msg","添加商品信息失败!");
request.getRequestDispatcher("error.jsp").forward(request,response);
}
}
}
点击添加后自动跳转展示页面
C2.删
delGoods :
package com.man.servlet;
import com.man.dao.GoodsDao;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/del")
public class delGoods 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 {
// 1.获取页面中要删除数据的id
int gid = Integer.parseInt(request.getParameter("gid"));
// 2.执行业务删除操作
GoodsDao goodsDao = new GoodsDao();
int i = goodsDao.delGoods(gid);
// 3.判断是否删除
if (i>0){
// 请求转发,查询所有商品信息
request.getRequestDispatcher("selectAllGoods").forward(request,response);
}else {
// 删除失败,传入错误信息并跳转页面
request.setAttribute("error_msg","删除操作出现了问题!");
request.getRequestDispatcher("error.jsp").forward(request,response);
}
}
}
点击删除自动刷新页面,并删除点击行
C3.改
FindGoodsById 类
package com.man.servlet;
import com.man.bean.Goods;
import com.man.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.findGoodsById(gid);
// 判断数据是否为空
if (goods!=null){
request.setAttribute("goods",goods);
request.getRequestDispatcher("showGoods.jsp").forward(request,response);
}else {
request.setAttribute("error_msg","查询出现错误!");
request.getRequestDispatcher("error.jsp").forward(request,response);
}
}
}
UpdateGoods 类
package com.man.servlet;
import com.man.bean.Goods;
import com.man.dao.GoodsDao;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/updateGoods")
public class UpdateGoods 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 {
// 1.设置请求和响应的编码格式,以及响应的格式
request.setCharacterEncoding("utf-8"); // 设置获取数据的格式
response.setCharacterEncoding("utf-8");
Goods goods = new Goods();
goods.setGid(Integer.parseInt(request.getParameter("gid")));
goods.setGname(request.getParameter("gname"));
goods.setPrice(Double.parseDouble(request.getParameter("price")));
goods.setMark(request.getParameter("mark"));
GoodsDao goodsDao =new GoodsDao();
int row = goodsDao.updateGoods(goods);
// 4.判断登陆信息是否为空
if (row >0) {
// 登陆成功,当前servlet业务处理完毕---后续操作由别人完成---请求别的地址
request.getRequestDispatcher("selectAllGoods").forward(request, response);
} else {
// 登陆失败,传入错误信息并跳转页面
request.setAttribute("error_msg","修改操作失败!");
request.getRequestDispatcher("error.jsp").forward(request,response);
}
}
}
D.模糊查询
Seach 类
package com.man.servlet;
import com.man.bean.Goods;
import com.man.dao.GoodsDao;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
@WebServlet("/seach")
public class Seach 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 {
System.out.println("Seach-doPost============");
// 设置页面编码格式
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// 接收页面数据
String keyword = request.getParameter("keyword");
// 执行业务处理
GoodsDao goodsDao = new GoodsDao();
List<Goods> goodsList = goodsDao.seachGoods(keyword);
// 把数据传递到前端页面
// 通过request获取session对象,该对象可以向前端传输数据的容器
HttpSession session = request.getSession();
// 向session中存入商品信息集合
session.setAttribute("goodsList", goodsList);
// 登录成功,跳转到登录页
response.sendRedirect("zhuye.jsp");
}
}
3.过滤器
过滤器(Filter)
filter是对客户端访问资源的过滤,符合条件放行,不符合条件不放行,并且可以对目 标资源访问前后进行逻辑处理
过滤器,是在java web中将你传入的request、response提前过滤掉一些信息,或者提前设置一些参数。然后再传入Servlet或Struts2的 action进行业务逻辑处理。比如过滤掉非法url(不是login.do的地址请求,如果用户没有登陆都过滤掉),或者在传入Servlet或Struts2的action前统一设置字符集,或者去除掉一些非法字符。
通俗理解:
过滤器(Filter):当你有一堆东西的时候,你只希望选择符合你要求的某一些东西。定义这些要求的工具,就是过滤器。(理解:就是一堆字母中取一个B)
过滤器是在请求进入容器后,但请求进入servlet之前进行预处理的。请求结束返回也是,是在servlet处理完后,返回给前端之前.文章来源:https://www.toymoban.com/news/detail-421341.html
package com.man.Filter;
import com.man.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("初始化...");
}
/**
* 拦截所有的请求或页面,需要放行index.jsp,login.jsp,login
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("执行过滤...");
// 1.在过滤器中把servletRequest,servletResponse转换为HttpservletRequest,HttpservletResponse
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 2.获取请求资源路径
String servletPath = request.getServletPath();
System.out.println("servletPath");
// 3.获取session中储存的用户对象
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
System.out.println(user);
// 4.1如果请求index.jsp,login.jsp,login则放行
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("销毁...");
}
}
4.完成servlet映射关系配置
4.1映射方法一(弃用)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置servlet类 -->
<servlet>
<!-- 起别名 -->
<servlet-name>login</servlet-name>
<servlet-class>com.man.servlet.Login</servlet-class>
<!-- servlet类所在的位置:类的全类名就是 包名.类名 -->
</servlet>
<!-- Servlet类的映射:Servlet用来处理哪个请求 -->
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>zhuce</servlet-name>
<servlet-class>com.man.servlet.Zhuce</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>zhuce</servlet-name>
<url-pattern>/zhuce</url-pattern>
</servlet-mapping>
</web-app>
4.2映射方法二
将@WebServlet("/想跳转的页面")写在代码最外层,即可完成映射文章来源地址https://www.toymoban.com/news/detail-421341.html
到了这里,关于(代码注释超详细)JavaWeb连接Mysql数据库完成登录注册业务的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!