java day32 Servlet案例应用(登陆、注册、获取数据、重置密码、注销、免登陆)

1、案例知识点

  1. 免登陆
    1.1 登陆页面添加勾选免登陆的按钮选项
    1.2 后台获取免登陆按钮的勾选状态,判断时候已被勾选,若是被勾选,则创建cookie保存到response中
    1.3 login.jsp页面获取免登陆状态的cookie值,判断是否保存id,如果存在id则重定向到userindex.jsp(用户首页)中

  2. 注销
    2.1 用户首页添加注销按钮
    2.2 后天添加注销的case,清除id的cookie,然后重定向到index.jsp

1.1 后端代码:

DB.java

模拟数据库,存储用户数据

package db;

import entity.User;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author wzy
 * @Date 0028 2020-12-28 10:47
 * @Version 1.0
 */
public class DB {
    //用户表
    public static List<User> list = new ArrayList<>();
    public static String code;
    static{
        list.add(new User(1,"zs","123","男",new String[]{"play","drink"},"guangxi"));
        list.add(new User(2,"ls","123","女",new String[]{"eat","drink"},"guangxi"));
        list.add(new User(3,"ww","123","男",new String[]{"play","drink","happy"},"guangdong"));
    }
}

User.java

用户实体类,封装用户的属性和方法

package entity;

import java.util.Arrays;

/**
 * @Author wzy
 * @Date 0028 2020-12-28 10:47
 * @Version 1.0
 */
public class User {
    private int id;
    private String name;
    private String password;
    private String sex;
    private String[] hobbies;
    private String addrs;

    public User() {
    }

    public User(int id, String name, String password, String sex, String[] hobbies, String addrs) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.sex = sex;
        this.hobbies = hobbies;
        this.addrs = addrs;
    }
    public User(String name, String password, String sex, String[] hobbies, String addrs) {
        this.name = name;
        this.password = password;
        this.sex = sex;
        this.hobbies = hobbies;
        this.addrs = addrs;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String[] getHobbies() {
        return hobbies;
    }

    public void setHobbies(String[] hobbies) {
        this.hobbies = hobbies;
    }

    public String getAddrs() {
        return addrs;
    }

    public void setAddrs(String addrs) {
        this.addrs = addrs;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", sex=" + sex +
                ", hobbies=" + Arrays.toString(hobbies) +
                ", addrs='" + addrs + '\'' +
                '}';
    }
}

CheckServlet.java

封装生成前端页面的验证码的方法

package servlet;

import javax.imageio.ImageIO;
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.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author wzy
 * @Date 0028 2020-12-28 10:48
 * @Version 1.0
 */
@WebServlet("/CheckServlet")
public class CheckServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 100;
        int height = 50;
        //1.创建带缓冲区的图片对象
        BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2.通过图片对象获取画笔
        Graphics graphics = bImage.getGraphics();
        //3.设置画笔颜色
        graphics.setColor(Color.LIGHT_GRAY);
        //4.填充背景颜色
        graphics.fillRect(0,0,width,height);
        //5.再次设置画笔颜色
        graphics.setColor(Color.RED);
        //6.设置字体样式
        graphics.setFont(new Font("黑体",Font.BOLD,20));
        //7.生成随机数当成验证码
        Random ran = new Random();
        int code;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            code = ran.nextInt(10);
            graphics.drawString(code+"",15+20*i,30);
            sb.append(code+"");
        }

        //把验证码存储到数据库中   --  不可行
        //DB.code = sb.toString();
        //存储数据在请求中  --  不可行
        //req.setAttribute("code",sb.toString());

        //存储数据在ServletContext中  --  不可行
        //ServletContext servletContext = getServletContext();
        //servletContext.setAttribute("code",sb.toString());

        //存储数据到session中
        HttpSession session = req.getSession();
        session.setAttribute("code",sb.toString());

        //8.再次更改画笔颜色
        graphics.setColor(Color.cyan);
        //9.绘制干扰线
        for (int i = 0; i < 10; i++) {
            //x的起点,y的起点,x的终点,y的终点
            graphics.drawLine(ran.nextInt(width),ran.nextInt(height),ran.nextInt(width),ran.nextInt(height));
        }
        //10.把绘制好的图片对象响应回给请求的客户端
        ImageIO.write(bImage,"jpg",resp.getOutputStream());
    }
}

UserServlet.java (核心代码)

封装前端页面登陆、注册、注销、获取展示数据、修改密码等方法

package servlet;

import db.DB;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String action = request.getParameter("action");
        switch (action){
            case "register":
                toRegister(request,response);
                break;
            case "login":
                toLogin(request,response);
                break;
            case "logout":
                toLogout(request,response);
                break;
            case "rePassword":
                toRePassword(request,response);
                break;
            case "getList":
                toGetList(request,response);
                break;
            default:
                System.out.println("请求的action有误,请查找");
                break;
        }
    }

    //获取所有数据响应前端
    private void toGetList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将数据库DB里的list集合存储到请求里,使用请求而不是session的原因是,
        //若是多人请求,session的数据会是全部人都一致,而请求则是发起一次请求,就展示一次
        request.setAttribute("list", DB.list);
        request.getRequestDispatcher("userList.jsp").forward(request,response);
    }

    private void toRePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端提交的原密码和新密码
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        //2.获取用户对象
        String str = request.getSession().getAttribute("id").toString();//获取登陆是存储在session里的id
        int id = Integer.parseInt(str); //因为存储在session里的数据是string类型,数据里的id是int类型的,所以需要进行数据类型转换
        User user=null;
        for (User u:DB.list) {
            if (u.getId()==id){
                user=u;//获取这个对象
            }
        }

        //3.判断原密码和数据库中的密码是否一致
        if (!user.getPassword().equals(oldPassword)){
            request.setAttribute("msg","原密码错误");
            request.getRequestDispatcher("rePassword.jsp").forward(request,response);
            return;
        }
        //4.修改密码
        user.setPassword(newPassword);

        //5.注销登陆,让用户重新登陆
        toLogout(request,response);
    }

    //注销
    private void toLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //删除cookie
        Cookie cookie = new Cookie("id", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        //删除session中用户的id
        request.getSession().removeAttribute("id");

        //页面跳转
        response.sendRedirect("index.jsp");
    }

    //登录功能
    private void toLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //1.获取前端发送的请求数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //先校验验证码
        String code = request.getParameter("code");

        //获取session中的数据
        String code1 = (String)request.getSession().getAttribute("code");
        if(!code1.equals(code)){
            //把验证码错误提示存储到请求作用域中
            request.setAttribute("msg","验证码有误");
            //跳转页面  --  转发
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        }

        boolean flag = false;
        int id = 0;
        //2.判断用户名和密码是否正确
        for (User u:DB.list) {
            if(u.getName().equals(username) && u.getPassword().equals(password)){
                flag = true;
                //获取数据库中的用户id;
                id = u.getId();
            }
        }

        if(flag){
            //3.保存cookie
            String remember = request.getParameter("remember");
            if(remember != null){
                //设置cookie内容
                //Cookie cookie = new Cookie("username", URLEncoder.encode(username,"utf-8"));
                Cookie cookie = new Cookie("id", id+"");
                //设置cookie有效时间  --  单位为秒
                cookie.setMaxAge(60*60);
                //在响应中设置cookie
                response.addCookie(cookie);
            }
            //保存用户id到session中
            request.getSession().setAttribute("id",id);

            //跳转页面  --  重定向
            response.sendRedirect("userIndex.jsp");
        }else{
            //存储信息到请求中
            request.setAttribute("msg","用户名或者密码错误");
            //转发
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }

    }

    private void toRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //1.获取前端发送的请求数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        //String hobbies = request.getParameter("hobbies");
        String[] hobbies = request.getParameterValues("hobbies");
        String addrs = request.getParameter("addrs");
        User user = new User(username, password, sex, hobbies, addrs);
        //2.检验用户名是否存在,如果存在则告诉用户,用户名已存在
        for (User u:DB.list) {
            if(u.getName().equals(username)){
                request.setAttribute("msg","用户名已存在,请重新输入");
                request.getRequestDispatcher("register.jsp").forward(request,response);
                return;
            }
        }
        //3.添加用户进数据库的表中
        user.setId(DB.list.size()+1);
        if(sex.equals("man")){
            user.setSex("男");
        }else{
            user.setSex("女");
        }
        DB.list.add(user);
        //4.响应前端
        response.sendRedirect("login.jsp");
    }
}

1.2 前端代码

首页
index.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0028 2020-12-28
  Time: 10:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="login.jsp">登录</a>
<a href="register.jsp">注册</a>
</body>
</html>

login.jsp

登陆页

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0028 2020-12-28
  Time: 10:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <script>
        //点击验证码图片刷新验证码
        function btn1(obj) {
            obj.src="CheckServlet?date="+new Date();
        }

        //点击换一换刷新验证码
        function btn2() {
            var img = document.getElementsByTagName("img")[0];
            img.src="CheckServlet?date="+new Date();
        }
    </script>
</head>
<body>

<%
    //免登陆
    Cookie[] cookies = request.getCookies();        //获取后端存储的id的cookie
    if (cookies!=null){
        for (Cookie cookie:cookies) {
            if ("id".equals(cookie.getName())){     //根据id去查找用户,成功则直接进入userIndex.jsp
                response.sendRedirect("userIndex.jsp");
            }
        }
    }
%>

<form action="UserServlet">
    <input type="hidden" value="login" name="action">
    账户:<input type="text" name="username"><span style="color: red">${msg_username}</span><br/>
    密码:<input type="text" name="password"><span style="color: red">${msg_password}</span><br/>

    <img src="CheckServlet" onclick="btn1(this)">
    <a href="#" onclick="btn2()">换一换</a><br>

    <input type="text" name="code"> <span style="color: red">${msg}</span> <br/>

    <input type="checkbox" name="remember">免登陆<br>

    <input type="submit" value="登录">
</form>
</body>
</html>

register.jsp

注册页

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0028 2020-12-28
  Time: 10:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<!--
    表单如果填写不完善,不允许提交表单信息,并提示用户对应的选项未填写
-->
${msg}
<form action="UserServlet?action=register" method="post">
    用户名:<input type="text" name="username"><br/>
    密码:<input type="text" name="password"><br/>
    性别:<input type="radio" name="sex" value="man"><input type="radio" name="sex" value="women"><br/>
    爱好:<input type="checkbox" name="hobbies" value="eat"><input type="checkbox" name="hobbies" value="drink"><input type="checkbox" name="hobbies" value="play"><input type="checkbox" name="hobbies" value="happy"><br/>
    地址:<select name="addrs">
    <option value="guangdong">广东</option>
    <option value="guangxi">广西</option>
</select><br/>
    <input type="submit" value="注册"/>
</form>
</body>
</html>

rePassword.jsp

密码重置

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0028 2020-12-28
  Time: 16:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script>
        function btn() {
            //获取原密码、新密码和确认密码
            var oldPassword = document.getElementById("oldPassword").value;
            var newPassword = document.getElementById("newPassword").value;
            var rePassword = document.getElementById("rePassword").value;

            //获取span标签对象
            var span = document.getElementsByTagName("span");

            //非空判断
            if (oldPassword==""||newPassword==""||rePassword==""){
                span.innerHTML="<h1 style='color: red'>不能为空</h1>"
                return false;
            }

            //原密码和新密码不能一致
            if (oldPassword==newPassword){
                span.innerHTML="<h1 style='color: red'>原密码和新密码不能一致</h1>"
                return false;
            }
            
            //新密码和确认密码必须一致
            if (newPassword!=rePassword){
                span.innerHTML="<h1 style='color: red'>新密码和确认密码必须一致</h1>"
                return false;
            }
            return true;
        }

    </script>
</head>
<body>
    <span>
    <form action="UserServlet?action=rePassword" method="post" onsubmit="return btn()">
        原密码<input type="text" name="oldPassword" id="oldPassword"><br>
        新密码<input type="text" name="newPassword" id="newPassword"><br>
        确认密码<input type="text" id="rePassword"><br>
        <input type="submit" value="确定修改">

    </form>
</body>
</html>

userIndex.jsp

用户个人页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0028 2020-12-28
  Time: 10:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script>
        function btn() {
            location.href="UserServlet?action=logout";
        }
    </script>

</head>
<body>
<%--<input type="button" value="注销" onclick="btn()">--%>
<a href="UserServlet?action=getList">展示所有数据</a>
<input type="button" value="注销" onclick="btn()"><br>
<a href="rePassword.jsp">修改密码</a><br>
欢迎登录个人中心

</body>
</html>

userList.jsp

展示用户数据页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0028 2020-12-28
  Time: 16:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--使用JSTL标签库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1" cellspacing="0">
    <tr>
        <td>ID</td>
        <td>姓名</td>
        <td>密码</td>
        <td>性别</td>
        <td>爱好</td>
        <td>地址</td>
        <td>操作</td>
    </tr>

    <c:forEach items="${list}" var="user">
        <tr>

            <td>${user.id}</td>
            <td>${user.name}</td>
            <td>${user.password}</td>
            <td>${user.sex}</td>
            <td>
                <c:forEach items="${user.hobbies}" var="hobbies">
                    ${hobbies}
                </c:forEach>
            </td>
            <td>${user.addrs}</td>
            <td>
                <a href="#">编辑</a>/
                <a href="#">删除</a>
            </td>
        </tr>
    </c:forEach>

    <tr>
        <td colspan="7">
            <a href="#">添加</a>
        </td>
    </tr>
</table>


</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值