编写代码要实现的业务:
登录:完成连接数据库判断登陆信息是否有误
注册:将信息填写完毕后点击注册,跳转到登陆页面
主页:展示项目信息并且可以在页面内进行增删改操作
完整文件目录如下:
文件目录:
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文件)
首页 欢迎学习WEB!
去登陆
去注册
给客户两个选项(登陆/注册)—完成页面如下
1.1登陆页面
登陆页面 登陆页面
欢迎学习WEB!
账号:
密码:
没有账号?点击注册
1.2注册页面
注册页面 注册页面
账号:
密码:
再次输入密码:
手机号:
地址:
已有账号?点击登录
1.3项目页面
由后台数据库传递过来的商品数据:
a:
获取后台的变量值
session在网络应用中称为“会话控制”,是服务器为了保存用户状态而创建的一个特殊的对象。 session就是一个对象,用于存储信息
(这段代码可以不写)
<%// 获取sessionHttpSession session1 = request.getSession();// 从session中取出数据List goodsList = (List) session1.getAttribute("goodsList");// 遍历集合中的元素for (Goods goods : goodsList) {%>
b:
现在导入JSTL包后
可以使用 ${} 直接获取数据 注意:在${}的括号中不能出现空格
主页 欢迎来自${user.address}的${user.username}登录项目主页
主页信息展示
添加商品商品编号 商品名称 商品价格 商品介绍 操作 ${goods.gid} ${goods.gname} ${goods.price} ${goods.mark} 修改删除
1.4错误页面
${error_msg}可以获取每次页面中的不同信息
错误页 ${error_msg}
回到登录页
1.5添加数据页面
添加商品页面 添加商品
商品名称 : 商品价格 : 商品介绍 :
1.6修改数据页面
修改商品页面 修改商品
商品编号 :
商品名称 :
商品价格 :
商品介绍 :
2.Java代码编写
A.登陆页面编写
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;}@Overridepublic String toString() {return "User{" +"uid=" + uid +", username='" + username + '\'' +", password='" + password + '\'' +", phone='" + phone + '\'' +", address='" + address + '\'' +'}';}}
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;}@Overridepublic String toString() {return "Goods{" +"gid=" + gid +", gname='" + gname + '\'' +", price=" + price +", mark='" + mark + '\'' +'}';}}
2.编写登录java代码
2.1编写访问数据库代码(dao包)
GoodsDao:
package com.man.dao;import com.man.bean.Goods;import com.man.bean.User;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 selectAllGoods() {List 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=" />
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;}}
2.2 完成页面请求登录操作
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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("Login-doGet...");doPost(request, response);}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("SelectAllGoods-doGet...");doPost(request,response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 1.执行查询业务// 2.查询所有商品信息GoodsDao goodsDao = new GoodsDao();List 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");}}
2.3工具类文件
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" />
输入正确信息,数据库比对过后进入主页面
反之则进入错误页
B.注册页面
注册页面 注册页面
账号:
密码:
再次输入密码:
手机号:
地址:
已有账号?点击登录
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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("register-doGet...");doPost(request, response);}@Overrideprotected 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 文件中
@Overridepublic int register(User user) {try{// 1.获取数据库连接con = JDBCUtil.getCon();// 2.定义注册的新增sql语句String sql = "insert into t_user(username,password,phone,address) values(" />
输入信息点击 注册,自动跳转登录页
将刚刚注册的账号密码输入,登录进入项目主页
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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 1.获取页面中要删除数据的idint 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int gid = Integer.parseInt(request.getParameter("gid"));// 根据gid查询商品数据GoodsDao goodsDao = new GoodsDao();Goods goods = goodsDao.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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected 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 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处理完后,返回给前端之前.
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 {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("初始化...");}/** * 拦截所有的请求或页面,需要放行index.jsp,login.jsp,login */@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("执行过滤...");// 1.在过滤器中把servletRequest,servletResponse转换为HttpservletRequest,HttpservletResponseHttpServletRequest 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");}}@Overridepublic void destroy() {System.out.println("销毁...");}}
4.完成servlet映射关系配置
4.1映射方法一(弃用)
logincom.man.servlet.Loginlogin/loginzhucecom.man.servlet.Zhucezhuce/zhuce
4.2映射方法二
将@WebServlet("/想跳转的页面")写在代码最外层,即可完成映射