第一步 我们先MySQL创建数据库,写数据
这两个是写数据库的软件。
启动MySQL对应的版本型号。
user表
1.判断存在(有没有login的数据库,有就删掉)即删除。
DROP DATABASE IF EXISTS login;
2.创建数据库,使用数据库
#创建数据库
CREATE DATABASE login;
#使用数据库
use login;
3.创建一个表我们这定义叫user,给表增添3条数据
#创建表
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.查询表
SELECT * FROM user;
goods表
1.创建另一个表叫goods,给表增添3条数据
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.查询表
select * from goods;
整体代码如下:
#判断存在即删除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 = " /> 第二步 在IDEA中写出这两个表对应的Java实体类
MySQL的表名要跟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;}@Overridepublic 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() {}@Overridepublic 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.首页
这是一个web项目 登录注册
2.登录页面
登录页 账号:
密码:
没有账号" />错误页 出错啦
返回登录
4.注册页面
zhuce 账号:
密码:
手机号:
地址:
确认密码:
已有账号" />服务器端代码 %>
获取后台的变量值
session在网络应用中称为“会话控制”,是服务器为了保存用户状态而创建的一个特殊的对象。简而言之,session就是一个对象,用于存储信息。
主页 欢迎来自${user.address}的${user.uname}访问项目主页
添加商品商品编号 商品名称 商品价格 商品说明 ${goods.gid} ${goods.gname} ${goods.price} ${goods.mark} 修改删除
6.添加页面
商品信息的添加 商品名称:
商品价格:
商品说明:
7.修改页面
商品信息的修改 商品修改
商品编号:
商品名称:
商品价格:
商品说明:
第四步 JDBC操作层面
1.在src里建三个包 Dao,httpServlet,Util
2.在Dao中先创建两个接口 这里起名叫UserDao,GoodsDao
UserDao
login登录页面有两个参数
register 返回一个user对象
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 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" />
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; //增删改受影响的行数//全查@Overridepublic List slectAll() {List 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 seach(String keyword) {List 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;}//添加数据@Overridepublic 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;}//删除@Overridepublic int selectDelete(int gid) {System.out.println("selectDelete");try {conn = JDBCUtil.getCon();//3.sql语句String sql = "deletefrom 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;}//修改@Overridepublic 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;}}
第五步 业务处理层面
httpServlet中写的三个类是处理:
1.设置请求和响应的编码格式2.获取请求的参数3.执行业务处理
Login
1.映射地址
@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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("Login-get");doPost(request,response);}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("register-get");doPost(request,response);}@Overrideprotected 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 {@Overrideprotected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("SelectAllGoods..dopost");//查询所有商品信息GoodsDaoImpl goodsDao = new GoodsDaoImpl();List 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 {@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.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 {@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 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 {@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"));//根据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 {@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"));//执行数据库的修改操作 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 {@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");String keyword = req.getParameter("keyword");//根据关键词执行JDBC的模糊查询GoodsDao goodsDao = new GoodsDaoImpl();List goodsList = goodsDao.seach(keyword);//把数据传递到前端页面//通过request获取session对象,该对象可以向前端传递传输数据的容器HttpSession session = req.getSession();//向session 中存入商品信息集合session.setAttribute("goodsList", goodsList);//登录成功,跳转到主页resp.sendRedirect("zhuye.jsp");//指定的跳转页面}}
到这里代码就结束了,数据库原本的三条数据,正确的账号密码。
如果注册,注册的信息就存在后台的数据库里,如果注册成功就可以登录成功,在后台数据库里添加商品信息,通过session在主页页面中就能看到商品信息。增删改查操作。
不能随意访问网址就能进入注册、添加、主页页面中,所以我们要写个过滤器,防止外来人员直接访问。
第六步 Filter过滤器
1、filter简介
Filter中文意思为过滤器。顾名思义,过滤器可在浏览器以及目标资源之间起到一个过滤的作用。例如:水净化器,可以看成是生活中的一个过滤器,他可以将污水中的杂质过滤,从而使进入的污水变成净水。对于WEB应用来说,过滤器是一个驻留在服务器中的WEB组件,他可以截取客户端和WEB资源之间的请求和响应信息。WEB资源可能包括ServletJSPHTML页面等。
Filter是Tomcat容器内的过滤器,在请求到达容器是先会调用过滤器,再调用我们的servlet或者jsp。
当服务器收到特定的请求后,会先将请求交给过滤器,程序员可以在过滤器中对请求信息进行读取修改等操作,然后将请求信息再发送给目标资源。目标资源作出响应后,服务器会再次将响应转交给过滤器,在过滤器中同样可以对响应信息做一些操作,然后再将响应发送给浏览器。
也就是说过滤器可以在WEB资源收到请求之前,浏览器收到响应之前,对请求和响应信息做一些相应的操作。
在一个WEB应用中可以部署多个过滤器,多个过滤器就组成了一个过滤器链,请求和响应必须在经过多个过滤器后才能到达目标。
过滤器不是必须将请求传送到下一个过滤器(或WEB资源),也可以自己来处理请求,发送响应。
2、filter的实现
Filter接口,实现Filter需要实现该接口
1、init()方法用于初始化Filter。
2、doFilter()作用和service()方法类似,是过滤请求和响应的主要方法。
3、destroy0用于在Filter对象被销毁前做一些收尾工作。如:释放资源等
3、filter的生命周期
Filter的生命周期和Servlet类似
构造器:创建Filter实例是调用,Filter实例服务器一旦启动就会被创建
init():实例创建后马上被调用,用来对Filter做一些初始化的操作
doFilter():Filter的主要方法,用来完成过滤器主要功能的方法,每次访问目标资源时都会调用。
destroy():服务器停止时调用,用来释放资源
首先
映射所有
@WebFilter("/*")
实现filter接口
因为要登录(+登录的映射地址),没有账号的要注册(+注册的映射地址),登陆失败跳转错误页面,这些页面都需要放行,直接访问主页会回到登录页面。
具体代码如下:
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 {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("初始化..");}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {//1.在过滤器中把servletRequest、servletResponse转换为HttpServletRequest、HttpServletResponseHttpServletRequest 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");}}@Overridepublic void destroy() {System.out.println("销毁..");}}
项目效果如下: