首页 前端知识 前端jQuery AJAX和后端Servlet技术完成异步登录注册程序

前端jQuery AJAX和后端Servlet技术完成异步登录注册程序

2024-06-08 22:06:40 前端知识 前端哥 819 907 我要收藏

一、实验要求

1. 使用jQuery进行数据验证

2. 使用jQuery AJAX实现数据请求与提交

3. 使用Servlet接收数据和访问数据库

二、实验内容

1. 创建登录注册页面,以及对应的Web接口

2. 以jQuery AJAX实现数据请求与提交

3. 在Web接口中实现数据库的读写

4. 完成应用程序的发布

三、实验步骤

设计登录和注册页面(美观即可,不要求按设计图精确布局)

(1)创建网页,创建网页文件login.html或使用课堂练习3的login.jsp,对应的servlet接口文件verify.java或使用课堂练习3的verify.java,以及接口消息所使用的消息类message.java,

使用div+css按图1进行布局,点击“登录”按钮发起AJAX执行登录,具体功能和验证方式参见课堂练习2和3,登录成功后跳转到main.html;点击“注册”按钮链接到regist.html

(2)创建网页,创建网页文件regist.html,和对应的servlet接口文件registVerify.java。

使用div+css按图2进行布局,点击“注册”按钮发起AJAX提交注册,由于需要上传文件,所以需要,提交之前先做数据验证,确保用户名、密码、确认密码必填, Email如果填写了,要符合Email格式(由于同时要提交图片,此处须使用DataForm进行提交)。

填写用户名后(用户名文本框的change事件)可以将用户名提交到loginVerify接口,以验证用户名是否已存在,如果用户名已存在,则报错。

数据提交到registVerify接口后,经过服务端验证,将数据写入数据库中,完毕之后返回成功信息;regist.html收到成功消息后,再跳转到login.html;点击“已有账号”按钮链接到login.html。

(3)创建网页,创建网页文件main.html,和对应的servlet接口文件main.java。

当main.html就绪时(jQuery的$().ready()事件),异步请求main接口;

main接口读取session中的user信息,根据此信息查询数据库,读取用户的详细信息,包括头像文件的文件名。main.html获取到main接口的数据后,将数据及图片显示出来,图片通过图片名构造URL即可显示。

四、代码实现:

1、login.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 小侣呀
  Date: 2023/5/24
  Time: 19:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录界面</title>
   <script src="jquery-3.1.1.min.js"></script>
    <script>
        $().ready(function (){
            //点击登录事件
            $("#login_btn").click(function (){
                //获取用户输入
                var user_email = $("#user_email").val();
                var user_pwd = $("#user_pwd").val();
                var msg = "";

                //验证邮箱密码有没有
                if(user_email == "" ||  user_pwd == ""){
                    msg = "邮箱或密码不能为空";
                }//验证邮箱长度
                else  if(user_email.length > 20){
                    msg = "邮箱不能大于20个字符";
                }//验证邮箱格式
                else if(!/[^@\.]+@[^@\.]+\.[^@\.]{1,2}/.test(user_email)){
                    msg = "邮箱格式不对";
                }//验证密码长度
                else if (user_pwd.length < 8 || user_pwd.length > 20) {
                    msg = "密码必须再8~20个字符之间";
                }//验证密码格式
                else if (/^([0-9]+|[A-Za-z]+)$/.test(user_pwd)) {
                    msg = "密码不能为纯数字或纯字母";
                }
                //显示信息
                if(msg != ""){
                    $("#infoArea").html(msg);
                    $("#infoArea").show();
                }
                else{
                    $.ajax({
                        url:"loginVerify",
                        data:{user_email:user_email,user_pwd:user_pwd},
                        type:"POST",
                        dataType: "JSON",
                        success:function (jData){
                            if(jData.state =="SUC"){
                                $.ajax({
                                    url:"main",
                                    data:{user_email:user_email},
                                    type:"POST",
                                    dataType: "JSON",
                                });
                                document.location.href="main.jsp";
                            }else{
                                $("#infoArea").html(jData.msg);
                                $("#infoArea").show();
                            }
                        }

                    });
                }
            });
            //点击注册按钮跳转到注册界面
            $("#register_btn").click(function (){
                document.location.href="register.jsp";
            });

        });
    </script>
</head>
<body>
    <div class="login">
        <h1>登录</h1>
        <div class="login_form">
            <span>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱:</span>
            <input type="text" id="user_email" placeholder="请输入邮箱">
            <br>
            <span>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:</span>
            <input type="password" id="user_pwd" placeholder="请输入密码">
        </div>
        <div>
            <button class="login_Btn" id="login_btn">登 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 录</button> <br>
            <button class="login_Btn" id="register_btn">注 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 册</button> <br>
            <div class="infoArea" id="infoArea" ></div>
        </div>
    </div>
</body>
<style>
    body{
        padding: 0;
        margin: 0;
        height: 100vh;
        display: flex;
        justify-content: center;
        background-image: linear-gradient(#a18cd1 0%, #fbc2eb 100%);
        background-size: cover;
        flex: 1;
        align-items: center;
    }
    .login{
        text-align: center;
        margin: 0 auto;
        width: 600px;
        height: 630px;
        background-color: rgba(87, 86, 86, 0.2);
        border-radius: 25px;
        box-shadow: 5px 2px 35px -7px #ff9a9e;
    }
    .login h1{
        margin-top: 40px;
        color: aliceblue;
        font-weight: 100;
    }
    .login_form{
        padding: 20px;
    }
    .login_form span{
        color: rgb(131, 220, 255);
        font-size: 18px;
        font-weight: 100;
    }
    .login_form input{
        background-color: transparent;
        width: 320px;
        padding: 2px;
        text-indent: 2px;
        color: white;
        font-size: 20px;
        height: 45px;
        margin: 30px 30px 30px 5px;
        outline: none;
        border: 0;
        border-bottom: 1px solid rgb(131, 220, 255);
    }
    input::placeholder{
        color: #fbc2eb;
        font-weight: 100;
        font-size: 18px;
        font-style: italic;
    }
    .login_Btn{
        background-color: rgba(255, 255, 255, 0.582);
        border: 1px solid rgb(190, 225, 255);
        padding: 5px;
        width: 200px;
        height: 40px;
        border-radius: 20px;
        font-size: 20px;
        color: rgb(100, 183, 255);
        font-weight: 100;
        margin-top: 10px;
    }
    .login_Btn:hover{
        box-shadow: 2px 2px 15px 2px rgb(190, 225, 255);
        background-color: transparent;
        color: white;
        animation: login_mation 0.5s;
    }
    .infoArea{
        margin-top: 10px;
        color: red;
    }
</style>

</html>

2、loginVerify.java

import net.sf.json.JSONObject;

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.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@WebServlet(urlPatterns = "/loginVerify")
public class loginVerify extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将HTTP响应头改为JSON
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        //创建消息内
        Message msg = new Message();
        msg.setState("SUC");
        msg.setTime("");
        Connection connection = null;

        //1.数据接收
        try {
            String user_email = req.getParameter("user_email");
            String user_pwd = req.getParameter("user_pwd");

            if(user_email !=null) {
                //连接数据库
                //创建连接字符
                String dbhost = "localhost:3306";
                String dbname = "database";
                String dbuser = "root";
                String dbpassword = "123456";
                String url = "jdbc:mysql://" + dbhost + "/" + dbname+ "?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
                //创建连接对象(connection)
                Class.forName("com.mysql.cj.jdbc.Driver");
                connection = DriverManager.getConnection(url, dbuser, dbpassword);
                //调用Connection对象,创建表达对象(Statement)
                Statement statement = connection.createStatement();
                //创建SQL查询语句
                String sql = "select * from user where user_email = '" + user_email + "'";

                //调用Statement执行查询,将查询结果封装成为结果集对象(ResultSet)
                ResultSet rs = statement.executeQuery(sql);

                if (rs.next()) {
                    if (user_email != null && user_pwd != null) {
                        if (!user_pwd.equals(rs.getString("user_pwd"))) {
                            throw new Exception("密码错误");
                        }else{
                           HttpSession session = req.getSession();
                           session.setAttribute("user_pwd",user_email);
                            msg.setMsg("登陆成功");
                            msg.setContent(user_email);
                        }
                    } else {
                        msg.setMsg("用户 " + user_email + " 存在");
                        msg.setContent(user_email);
                    }

                } else {
                    throw new Exception("用户不存在");
                }

            }else {
                throw new Exception("用户密码数据不全");
            }

        }
        //2.异常处理
        catch (Exception e) {
            msg.setState("ERR");
            msg.setContent(null);
            msg.setMsg(e.getMessage());
        }
        //3.返回数据
        finally {
            //序列化JavaBean对象
            JSONObject jsonObject = JSONObject.fromObject(msg);
            String jstr = jsonObject.toString();
            //返回JSON
            PrintWriter out = resp.getWriter();
            out.print(jstr);
            try{
                if(connection != null){
                    connection.close();
                }
            }catch (Exception e){

            }
        }
    }
}

3、register.jsp

<%--
  Created by IntelliJ IDEA.
  User: 小侣呀
  Date: 2023/5/24
  Time: 19:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册界面</title>
    <script src="jquery-3.1.1.min.js"></script>
    <script>
        $().ready(function (){

            $("#register_btn").click(function (){

                //获取用户输入
                var user_name = $("#user_name").val();
                var user_email = $("#user_email").val();
                var user_pwd = $("#user_pwd").val();
                var sure_pwd = $("#sure_pwd").val();
                var user_image = $("#user_image")[0].files[0];
                var user_sex = $("input[name='sex']:checked").val();

                var formdata = new FormData();
                formdata.append('user_name',user_name);
                formdata.append('user_email',user_email);
                formdata.append('user_pwd',user_pwd);
                formdata.append('sure_pwd',sure_pwd);
                formdata.append('user_image',user_image);
                formdata.append('user_sex',user_sex);
                var msg = "";

                if(user_name == "" || user_email == ""){
                    msg = "用户名、邮箱不能为空";
                }
                else if(user_name.length >= 12){
                    msg = "用户名不能大于12个字符";
                }
                else if(!/^[A-Za-z0-9_\-]+$/.test(user_name)){
                    msg = "用户名只能为大小写字母、数字、下划线和横线";
                }
                else if(user_email.length > 20){
                    msg = "邮箱不能大于20个字符";
                }//验证邮箱格式
                else if(!/[^@\.]+@[^@\.]+\.[^@\.]{1,2}/.test(user_email)){
                    msg = "邮箱格式不对";
                }//验证密码是否正确
                else if(user_pwd == "" || sure_pwd == ""){
                    msg = "密码不能为空"
                }
                else if(user_pwd != sure_pwd){
                    msg = "两次密码不一致,重新输入";
                }  //验证密码长度
                else if (user_pwd.length < 8 || user_pwd.length > 20) {
                    msg = "密码必须再8~20个字符之间";
                }//验证密码格式
                else if (/^([0-9]+|[A-Za-z]+)$/.test(user_pwd)) {
                    msg = "密码不能为纯数字或纯字母";
                }
                else if (sure_pwd.length < 8 || sure_pwd.length > 20) {
                    msg = "密码必须再8~20个字符之间";
                }//验证密码格式
                else if (/^([0-9]+|[A-Za-z]+)$/.test(sure_pwd)) {
                    msg = "密码不能为纯数字或纯字母";
                }

                if(msg != ""){
                    $("#infoArea").html(msg);
                    $("#infoArea").show();
                }
                else{
                    $.ajax({
                        url:"registeVerify",
                        data:formdata,
                        type:"post",
                        dataType:"json",
                        processData: false,
                        contentType: false,
                        cache: false,
                        success:function (jData){
                            if(jData.state =="SUC"){
                                $("#infoArea").html(jData.msg);
                                $("#infoArea").show();
                                document.location.href="login.jsp";
                                alert("注册成功")
                            }
                        }
                    });
                }
            });

            //点击注册按钮跳转到注册界面
            $("#have_acount").click(function (){
                document.location.href="login.jsp";
            });

        });
    </script>
</head>
<body>
    <div class="register">
        <h1>注册</h1>
        <div class="register_form">
            <span>用&nbsp;&nbsp;户&nbsp;&nbsp;名:</span>
            <input type="text" id="user_name" placeholder="请输入用户名">
            <br>
            <span>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱:</span>
            <input type="text" id="user_email" placeholder="请输入邮箱号">
            <br>
            <span>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:</span>
            <input type="password" id="user_pwd" placeholder="请输入密码">
            <br>
            <span>确认密码:</span>
            <input type="password" id="sure_pwd" placeholder="请确认密码">
            <br>
            <span>照&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;片:</span>
            <input type="file" id="user_image">
        </div>
        <div class="sex_from">
            <span>&nbsp;&nbsp;性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>
            <label>
                <input type="radio" id="sex1" name="sex" value="男">男
                <input type="radio" id="sex2" name="sex" value="女">女
            </label>
        </div>
        <div class="btn">
            <button class="register_btn" id="register_btn">注 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 册</button> <br>
            <button class="register_btn" id="have_acount">已 &nbsp;有 &nbsp;账 &nbsp;号</button> <br>
            <div class="infoArea" id="infoArea" ></div>
        </div>
    </div>
</body>
    <style>
        body{
            padding: 0;
            margin: 0;
            height: 100vh;
            display: flex;
            justify-content: center;
            background-image: linear-gradient(#a18cd1 0%, #fbc2eb 100%);
            background-size: cover;
            flex: 1;
            align-items: center;
        }
        .register{
            /* text-align: center; */
            margin: 0 auto;
            width: 600px;
            height: 630px;
            background-color: rgba(87, 86, 86, 0.2);
            border-radius: 25px;
            box-shadow: 5px 2px 35px -7px #ff9a9e;
        }
        .register h1{
            margin-top: 40px;
            color: aliceblue;
            font-weight: 100;
            text-align: center;
        }
        .register_form{
            padding: 10px;
            text-align: center;
        }
        .sex_from{
            padding: 10px;
        }
        .register_form span{
            color: rgb(131, 220, 255);
            font-size: 18px;
            font-weight: 100;
        }
        .sex_from span{
            color: rgb(131, 220, 255);
            font-size: 18px;
            font-weight: 100;
            margin-left: 48px;
        }

        .register_form input{
            background-color: transparent;
            width: 320px;
            padding: 2px;
            text-indent: 2px;
            color: white;
            font-size: 20px;
            height: 30px;
            margin: 30px 30px 0px 30px;
            outline: none;
            border: 0;
            border-bottom: 1px solid rgb(131, 220, 255);
        }
        .sex_from label{
            color: white;;
            background-color: transparent;

        }
        .sex_from label input{
            margin-left: 50px;

        }
        input::placeholder{
            color: #fbc2eb;
            font-weight: 100;
            font-size: 18px;
            font-style: italic;
        }
        .register_btn{
            background-color: rgba(255, 255, 255, 0.582);
            border: 1px solid rgb(190, 225, 255);
            padding: 5px;
            width: 200px;
            height: 40px;
            border-radius: 20px;
            font-size: 20px;
            color: rgb(100, 183, 255);
            font-weight: 100;
            margin-top: 10px;
        }
        .btn{
            text-align: center;
        }
        .register_btn:hover{
            box-shadow: 2px 2px 15px 2px rgb(190, 225, 255);
            background-color: transparent;
            color: white;
        }
        .infoArea{
            margin-top: 10px;
            color: red;
        }
    </style>

</html>

4、registeVerify.java

import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

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.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.List;

@WebServlet(urlPatterns = "/registeVerify")
public class registeVerify extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        Message msgobj = new Message();
        msgobj.setState("SUC");

        User user = new User();
        Connection connection = null;
        PreparedStatement pstmt = null;

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(1024*1024*5);	//最大上传文件5Mb
        upload.setHeaderEncoding("UTF-8");

        //获取存储文件目录
        String uploadPath = req.getServletContext().getRealPath("./") + "upload";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists())		//如果目录不存在则创建
            uploadDir.mkdir();

        try {
            //数据接受
            @SuppressWarnings("unchecked")
            // 从upload(ServletFileUpload)对象中拿到表单数据,接收到的所有数据都放置在formItems中,包括文件数据和文本数据
            List<FileItem> formdatas = upload.parseRequest(req);
            if (formdatas == null || formdatas.size() == 0) {
                throw new Exception("未收到数据");
            }
            // 迭代表单数据
            for (FileItem dataitems : formdatas) {
                //处理表单中的文本字段
                if (dataitems.isFormField()) {
                    System.out.println(dataitems.getFieldName());        //打印接收到的数据的name
                    System.out.println(new String(dataitems.get(), "UTF-8"));    //打印接收到的数据
                    if(dataitems.getFieldName().equals("user_name")){
                        user.setName(new String(dataitems.get()));
                    }
                    else if(dataitems.getFieldName().equals("user_email")){
                        user.setEmail(new String(dataitems.get()));
                    }
                    else if(dataitems.getFieldName().equals("user_pwd")){
                        user.setPwd(new String(dataitems.get()));
                    }
                    else if(dataitems.getFieldName().equals("sure_pwd")){
                        user.setSurePwd(new String(dataitems.get()));
                    }
                    else if(dataitems.getFieldName().equals("user_sex")){
                        user.setSex(new String(dataitems.get()));
                    }
                }
                // 处理表单中的文件
                else {
                    //用户上传的文件名,在执行保存时,也可以改成自己的文件名
                    String fileName = new File(dataitems.getName()).getName();
                    //文件在服务上的保存路径
                    String filePath = uploadPath + File.separator + fileName;
                    //打印文件保存的路径
                    System.out.println(new String(dataitems.get(), "UTF-8"));
                    // 执行文件保存
                    dataitems.write(new File(filePath));
                   if(dataitems.getFieldName().equals("user_image")){
                        user.setImg(fileName);
                    }
                }
            }

            if (user.getEmail() !=null){

                //创建连接字符
                String dbhost = "localhost:3306";
                String dbname = "database";
                String dbuser = "root";
                String dbpassword = "123456";
                String url = "jdbc:mysql://" + dbhost + "/" + dbname+ "?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
                //创建连接对象(connection)
                Class.forName("com.mysql.cj.jdbc.Driver");
                connection = DriverManager.getConnection(url, dbuser, dbpassword);
                //调用Connection对象,创建表达对象(Statement)
                Statement statement = connection.createStatement();

                //数据库查询
                String sql = "select * from user where user_email = '" + user.getEmail() + "'";
                ResultSet rs = statement.executeQuery(sql);
                if(rs.next()){
                    throw new Exception("用户已存在");
                }
                else{
                    if(user.getName() != "" || user.getPwd() != "" || user.getSurePwd() != ""){
                        //插入数据
                        String insert_sql = "insert into user(user_name,user_email,user_pwd,user_img,user_sex)" + "values(?,?,?,?,?)";
                        if(user.getSurePwd().equals(user.getPwd())){
                            pstmt = connection.prepareStatement(insert_sql);
                            pstmt.setString(1, user.getName());
                            pstmt.setString(2, user.getEmail());
                            pstmt.setString(3, user.getPwd());
                            pstmt.setString(4, user.getImg());
                            pstmt.setString(5, user.getSex());

                            int n= pstmt.executeUpdate();
                            System.out.println("是否插入数据插入 n = 1, insert_into: "+n);
                        }
                        else{
                            throw new Exception("密码错误");
                        }

                    }else {
                        throw new Exception("密码用户名不能为空");
                    }
                }
            }

            System.out.println("我的user_img: "+user.toString());
            msgobj.setContent(user);
        }
        catch (Exception e){
            msgobj.setState("ERR");
            msgobj.setMsg(e.getMessage());
        }finally {
            JSONObject jsonObject = JSONObject.fromObject(msgobj);
            String jstr = jsonObject.toString();
            PrintWriter out = resp.getWriter();
            out.print(jstr);
            try{
                if(pstmt != null){
                    pstmt.close();
                }
            }catch (Exception e){

            }
            try{
                if(connection != null){
                    connection.close();
                }
            }catch (Exception e){

            }

        }

    }
}

5.main.jsp

<%--
  Created by IntelliJ IDEA.
  User: 小侣呀
  Date: 2023/5/24
  Time: 19:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>个人信息界面</title>
</head>
<body>
    <%  //获取在 session的值
        Object user_name = session.getAttribute("user_name");
        Object user_email = session.getAttribute("user_email");
        Object user_pwd = session.getAttribute("user_pwd");
        Object user_img = session.getAttribute("user_img");
        Object user_sex = session.getAttribute("user_sex");

    %>
    <div class="userInfo">
        <h1>个人信息</h1>
        <div class="userInfo_form">
            <span>用&nbsp;&nbsp;户&nbsp;&nbsp;名:</span>
            <input type="text" placeholder = <%out.print(user_name.toString());%>>
            <br>
            <span>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱:</span>
            <input type="text" placeholder = <%out.print(user_email.toString());%>>
            <br>
            <span>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:</span>
            <input type="password" placeholder = <%out.print(user_pwd.toString());%>>
            <br>
            <span>性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>
            <input type="text" placeholder = <%out.print(user_sex.toString());%>>

        </div>
        <div class="pic_from">
            <span>照&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;片:</span>
            <br>
            <img src="upload/<%=user_img%>">
        </div>
    </div>

</body>
    <style>
        body{
            padding: 0;
            margin: 0;
            height: 100vh;
            display: flex;
            justify-content: center;
            background-image: linear-gradient(#a18cd1 0%, #fbc2eb 100%);
            background-size: cover;
            flex: 1;
            align-items: center;
        }
        .userInfo{
            margin: 0 auto;
            width: 600px;
            height: 630px;
            background-color: rgba(87, 86, 86, 0.2);
            border-radius: 25px;
            box-shadow: 5px 2px 35px -7px #ff9a9e;
        }
        .userInfo h1{
            margin-top: 40px;
            color: aliceblue;
            font-weight: 100;
            text-align: center;
        }
        .userInfo_form{
            padding: 10px;
            text-align: center;
        }
        .pic_from{
            padding: 10px;
        }
        .userInfo_form span{
            color: rgb(131, 220, 255);
            font-size: 18px;
            font-weight: 100;
        }
        .pic_from span{
            color: rgb(131, 220, 255);
            font-size: 18px;
            font-weight: 100;
            margin-left: 60px;
        }
        .pic_from img{
            margin-left: 150px;
            width: 320px;
            height: 160px;
        }
        .userInfo_form input{
            background-color: transparent;
            width: 320px;
            padding: 2px;
            text-indent: 2px;
            color: white;
            font-size: 20px;
            height: 30px;
            margin: 30px 30px 0px 30px;
            outline: none;
            border: 0;
            border-bottom: 1px solid rgb(131, 220, 255);
        }
        input::placeholder{
            color: #fbc2eb;
            font-weight: 100;
            font-size: 18px;
            font-style: italic;
        }

    </style>
</html>

6、main.java

import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

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.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.List;

@WebServlet(urlPatterns = "/main")
public class main extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        Message msgobj = new Message();
        msgobj.setState("SUC");

        User user = new User();
        //定义session对象
        HttpSession session = req.getSession();
        Connection connection = null;
        //获取login.jsp传上来的值
        String user_email = req.getParameter("user_email");
        try {
            if (user_email !=null){
                //创建连接字符
                String dbhost = "localhost:3306";
                String dbname = "database";
                String dbuser = "root";
                String dbpassword = "123456";
                String url = "jdbc:mysql://" + dbhost + "/" + dbname+ "?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
                //创建连接对象(connection)
                Class.forName("com.mysql.cj.jdbc.Driver");
                connection = DriverManager.getConnection(url, dbuser, dbpassword);
                //调用Connection对象,创建表达对象(Statement)
                Statement statement = connection.createStatement();
                //创建查询语句
                String sql = "select * from user where user_email = '"+ user_email +"' ";
                ResultSet rs = statement.executeQuery(sql);
                while(rs.next()) {
                    //读取数据库的值
                    user.setName(rs.getString("user_name"));
                    user.setEmail(rs.getString("user_email"));
                    user.setPwd(rs.getString("user_pwd"));
                    user.setImg(rs.getString("user_img"));
                    user.setSex(rs.getString("user_sex"));
                }
                System.out.println("打印:查询数据库值是否得到: "+user.toString());
                if(user.getName() != null && user.getEmail() != null && user.getPwd() != null){
                    session.setAttribute("user_name",user.getName());
                    session.setAttribute("user_email",user.getEmail());
                    session.setAttribute("user_pwd",user.getPwd());
                    session.setAttribute("user_img",user.getImg());
                    session.setAttribute("user_sex",user.getSex());
                    //重定向 main.jsp 这个貌似不需要
                    resp.sendRedirect("main.jsp");
                }else{
                    throw new Exception("出现错误");
                }
            }else {
                throw new Exception("邮箱不为空");
            }
        }
        catch (Exception e){
            msgobj.setState("ERR");
            msgobj.setMsg(e.getMessage());
        }
        finally {
            try{
                if(connection != null){
                    connection.close();
                }
            }catch (Exception e){

            }
        }
    }
}

7、Message.java

public class Message {
    private String state;
    private String msg;
    private Object Content;

    private String time;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getContent() {
        return Content;
    }

    public void setContent(Object content) {
        Content = content;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

8、实体类User.java

public class User {
    String name;
    String email;
    String pwd;
    String surePwd;

    public String getSurePwd() {
        return surePwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", pwd='" + pwd + '\'' +
                ", surePwd='" + surePwd + '\'' +
                ", sex='" + sex + '\'' +
                ", img='" + img + '\'' +
                '}';
    }
    public void setSurePwd(String surePwd) {
        this.surePwd = surePwd;
    }

    String sex;
    String img;


    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getSex() {
        return sex;
    }

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

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }
}

五、运行结果:

 DBeaver中显示插入数据库

 

 

有不好的地方希望大家多多指点,我是一只小菜鸡。

有些地方跟老师给的要求不同

转载请注明出处或者链接地址:https://www.qianduange.cn//article/11602.html
标签
servlet
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!