端口映射 设计模式 wxRuby performance selenium flash browser 抖音 playframework flexbox scope nosql vue源码下载 vue组件开发 java并发编程视频 多店版微信商城 python查看数据类型 coreldraw学习 hbase端口 数据库学习 mysql入门 网页设计公司 python的安装 java开发教程 java数组扩容 java的基本类型 java当前时间 java时间格式化 linuxsleep linux内核编程 黑白照片一键变彩色 bash命令 字幕提取 java获取时间戳 pr蒙版 txplatform widcomm g4560配什么显卡 易语言皮肤模块 ps怎么p人脸
当前位置: 首页 > 学习教程  > 编程语言

java day31 Servlet案例应用(简单登陆和注册)

2020/12/28 19:41:12 文章标签:

1、案例知识点 注册功能 1.1 数据库:DB类 1.2 实体类:User类 1.3 UserServlet WebServlet("/UserServlet"),通过注解完成配置信息根据action值调用对应的方法 1.4 register.html action“UserServlet?actionregister” method“post” 登录功能 2.1 login.html act…

1、案例知识点

  1. 注册功能
    1.1 数据库:DB类
    1.2 实体类:User类
    1.3 UserServlet

    • @WebServlet("/UserServlet"),通过注解完成配置信息
    • 根据action值调用对应的方法

    1.4 register.html

    • action=“UserServlet?action=register” method=“post”
  2. 登录功能
    2.1 login.html

    • action=“UserServlet”
    • <input type=“hidden” name=“action” value=“login”>

    2.2 UserServlet

    • 添加一个login的case
  3. 三大作用域
    request:请求级别的作用域 – 请求不改变数据不丢失
    session:会话级别的作用域 – 会话不关闭数据不丢失
    servletContext:服务器级别的作用域 --服务器不关闭数据不丢失

  4. jsp
    4.1 可以再html页面上编写java代码 – 本质是 Servlet
    4.2 <% 编写java代码 %>
    4.2 <%= 展示java数据 %>
    4.3 EL 表达式 ${key} – 直接在作用域中获取数据

  5. 跳转
    转发:请求不变

    • request.getRequestDispatcher(“转发的页面”).forward(request,response);

重定向:二次请求
- response.sendRedirect(“重定向的页面”);

DB.java

  • 模拟数据库,并存储用户数据
package db;

import entity.User;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author wzy
 * @Date 0026 2020-12-26 14:16
 * @Version 1.0
 */
public class DB {
    //用户表
    public static List<User> list = new ArrayList<>();

    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 0026 2020-12-26 14:14
 * @Version 1.0
 */
public class User {
    private int id;
    private String name;
    private String password;
    private String sex;
    private String[] hobbies;
    private String addres;

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

    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 getAddres() {
        return addres;
    }

    public void setAddres(String addres) {
        this.addres = addres;
    }

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

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 0026 2020-12-26 16:34
 * @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.CYAN);
        //4.填充背景颜色
        graphics.fillRect(0,0,width,height);
        //5.再次设置画笔颜色
        graphics.setColor(Color.red);
        //6.设置字体颜色
        graphics.setFont(new Font("微软雅黑",Font.BOLD,30));
        //7.生成随意数字,用作验证码
        Random random = new Random();
        int code;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            code = random.nextInt(10);
            graphics.drawString(code+"",15+20*i,30);
            sb.append(code+"");
        }

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

        //8.再次设置画笔颜色
        graphics.setColor(Color.orange);
        //9.绘制干扰线
        for (int i = 0; i < 20; i++) {
            //x的起点,y的起点,x的终点,y的终点
            graphics.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));
        }
        ImageIO.write(bimage,"png",resp.getOutputStream());
    }
}

UserServlet.java

处理前端请求的类,包括用户登陆校验、用户注册等方法

package servlet;

import db.DB;
import entity.User;

import javax.jws.WebService;
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;

/**
 * @Author wzy
 * @Date 0026 2020-12-26 14:06
 * @Version 1.0
 */
@WebServlet("/UserServlet")     //有WebServlet注解,就无需配置web.xml文件
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;
            default:
                System.out.println("请求错误,请自行检查");
                break;
        }
    }

    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)){
//            System.out.println("验证码错误,重新输入");
            request.setAttribute("msg","验证码错误,重新输入");
            //跳转页面      --转发
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        }

        //2.判断用户名与账号是否正确
        for (User u: DB.list) {
            if (u.getName().equals(username)&&u.getPassword().equals(password)){
                response.getWriter().write("<script>location.href='userIndex.jsp'</script>");
                return;
            }else {
//                response.getWriter().write("<h1>密码错误</h1>");
                request.setAttribute("password_msg","密码错误,重新输入");
                request.getRequestDispatcher("login.jsp").forward(request,response);
                return;
            }
        }
        response.getWriter().write("用户名或者密码错误,请重新输入!!!");
    }

    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.getParameterValues("hobbies");
        String addres = request.getParameter("addres");

        User user = new User(username, password, sex, hobbies, addres);

        //检验用户名是否存在
        for (User u:DB.list) {
            if (u.getName().equals(username)){
                //开启session,以key-value的形式存储信息,register_msg是key,用户名已存在,请重新注册是value
                request.setAttribute("register_msg","用户名已存在,请重新注册");
                request.getRequestDispatcher("register.jsp").forward(request,response);
//                response.getWriter().write("用户名已存在");
                return;
            }
        }

        //3.将注册成功的用户数据存储到数据表里
        user.setId(DB.list.size()+1);
        if (sex.equals("man")){
            user.setSex("男");
        }else {
            user.setSex("女");
        }
        DB.list.add(user);

        response.getWriter().write("注册成功,请点击<a href='login.jsp'>登录</a>进行登录");
    }
}

index.html

首页

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0026 2020-12-26
  Time: 17:29
  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: 2020/12/26 0026
  Time: 下午 4:04
  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>
<!--
    表单提交方式为get
    action属性值携带的数据会被表单覆盖
-->
<%--<%
    //编码java代码
    String msg = (String)request.getAttribute("msg");
%>
<%=
    //展示java代码
    msg == null?"":msg
%>--%>
<%--自动从作用域中获取代码 request-> session --%>

<form action="UserServlet">
    <input type="hidden" value="login" name="action">
    账户:<input type="text" name="username"><br/>
    密码:<input type="text" name="password"> <span style="color: red">${password_msg}</span> <br/>
    <img src="CheckServlet"><br>
    <input type="text" name="code"> <span style="color: red">${msg}</span> <br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

register.html

注册页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0026 2020-12-26
  Time: 17:29
  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>
<!--
    表单如果填写不完善,不允许提交表单信息,并提示用户对应的选项未填写
-->
<form action="UserServlet?action=register" method="post">
    账户:<input type="text" name="username"> <span style="color: red"> ${register_msg} </span> <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="addres">
    <option value="guangdong">广东</option>
    <option value="guangxi">广西</option>
</select><br/>
    <input type="submit" value="注册"/>
</form>
</body>
</html>

userIndex.html

用户中心页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 0026 2020-12-26
  Time: 17:30
  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>
用户首页
</body>
</html>


本文链接: http://www.dtmao.cc/news_show_550351.shtml

附件下载

上一篇:C与C++的区别-2020-12-28

下一篇:毕设日记1

相关教程

    暂无相关的数据...

共有条评论 网友评论

验证码: 看不清楚?