使用HttpServlet实现简易登录

一、编写首页

我在首页设置两个超链接实现页面跳转,分别指向登录页面和注册页面

如图下所示:

 实现代码如下:

<html>
  <head>
    <title>Java Web</title>
  </head>
  <body>
    <a href="Login.jsp"><h2>去登录</h2></a>
    <a href="Enroll.jsp"><h2>去注册</h2></a>
  </body>
</html>

二、编写登录页面

在登录页面中我们需要用到JDBC连接数据库进行数据查询操作(判断用户输入的账号密码是否正确)

首先我们先来编写登录页面

如图所示:

 

 实现代码如下所示:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2023/2/14
  Time: 11:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--<h2>登录</h2>
<form action="login" method="post">
    账号:<input type="text" name="user"><br>
    密码:<input type="password" name="pwd"><br>
    <input type="submit" value="登录">
</form>--%>
<html>
    <head>
        <title>Java Web</title>
    </head>
    <body>
        <h2>登录</h2>
        <form action="login" method="post">
            账号:<input type="text" name="user"><br>
            密码:<input type="password" name="pwd"><br>
        <input type="submit" value="登录">
        </form>
    </body>
</html>

三、编写注册页面

在注册页面中我们需要用到JDBC连接数据库进行数据的添加操作(通过servlet获取浏览器发出请求中的数据添加到数据库中)

在实现添加数据之前我们先来完成注册页面的编写

如图所示:

 四、判断是否有该账号

我们需要判断数据库中是否有该账号,如果有该账号提示登录成功,如果没有该账号则提示用书登录失败。

如果要实现这个功能的话我分了以下几个步骤:

1. 从请求中获取用户提交的数据

2. 根据用户提交的账号和密码去数据库中执行查询操作,这时候我们就需要用到JDBC来进行连接数据库了

3. 如果数据库中有该账号则提示登录成功,如果没有该账号则提示登录失败

实现代码如下所示:

/**
 * 登录类
 */
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Login...get");
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Login...post");
        //1.从请求中获取用户提交的参数(数据)
        request.setCharacterEncoding("UTF-8");//设置请求的编码格式为中文
        String user = request.getParameter("user");//根据表单的name属性获取用户输入的值
        String pwd = request.getParameter("pwd");//根据表单的name属性获取用户输入的值

        System.out.println(user);
        System.out.println(pwd);
        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        //2.根据用户提交的用户名和密码---去数据库执行查询
        try {
            //2.1 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.2 获取连接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users?useSSL=false&serverTimezone=UTC", "root", "123456");
            //2.3 编写SQL语句
            String sql = "select * from users where user=? and pwd=?";
            //2.4 预处理SQL语句对象
            pstm = con.prepareStatement(sql);
            //2.5 给?赋值
            pstm.setObject(1,user);
            pstm.setObject(2,pwd);
            System.out.println(user);
            System.out.println(pwd);
            //2.6 获取数据
            rs = pstm.executeQuery();
            //2.7 设置响应的编码格式为UTF-8格式
            response.setCharacterEncoding("UTF-8");
            //2.8 设置以文本或网页的形式响应
            response.setContentType("text/html;charset=UTF-8");
            //2.9 判断是否有数据,做出响应
            if (rs.next()){
                //登录成功
                response.getWriter().write("登录成功!");//使用字符集给前端做出响应
            }else {
                //登录失败
                response.getWriter().write("账号不存在或密码错误!");
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //3. 关闭资源
            try {
                //判断rs是否为空,如果不为空则关闭资源
                if (rs!=null){
                    rs.close();
                }
                //判断pstm是否为空,如果不为空则关闭资源
                if (pstm!=null){
                    pstm.close();
                }
                //判断con是否为空,如果不为空则关闭资源
                if (con!=null){
                    con.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 

五、添加账号

添加账号我们就要进行数据库的添加数据操作(从请求中获取用户提交的注册信息然后再

通过JDBC把获取到的注册信息添加到数据库中)

如果要实现这个功能的话我分了以下几个步骤:

1. 从请求中获取用户提交的数据

2. 把用户提交的注册信息添加到数据库中

实现代码如下所示:

/**
 * 注册类
 */
public class Enroll extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("enroll...get");
        //调用doPost方法
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("enroll...post");
        //设置请求的编码格式为UTF-8格式
        request.setCharacterEncoding("UTF-8");
        //1. 从请求中获取用户提交的注册参数(数据)
        String zhangh = request.getParameter("zhangh");
        String pwd = request.getParameter("pwd1");
        //2. 通过JDBC把获取到的注册信息添加到数据库中
        Connection con = null;
        PreparedStatement pstm = null;
        try {
            //2.1 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.2 获取连接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users?useSSL=false&serverTimezone=UTC", "root", "123456");
            //2.3 编写SQL语句
            String sql = "insert into users (user,pwd) values (?,?)";
            //2.4 预处理SQL语句对象
            pstm = con.prepareStatement(sql);
            //2.5 给?赋值
            pstm.setObject(1,zhangh);
            pstm.setObject(2,pwd);
            //2.6 执行SQl语句返回受影响的行数
            int i = pstm.executeUpdate();
            //2.7 设置响应的编码格式为UTF-8格式
            response.setCharacterEncoding("UTF-8");
            //2.8 设置以文本或网页的形式响应
            response.setContentType("text/html;charset=UTF-8");//已什么样的格式(文本/网页)响应
            //2.9 判断影响行数是否大于零,大于零表示添加数据成功,反之添加数据失败,做出响应
            if (i>0){
                //注册成功
                response.getWriter().write("注册成功!");//使用字符集给前端做出响应
            }else {
                //注册失败
                response.getWriter().write("注册失败!");//使用字符集给前端做出响应
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //3. 关闭资源
            try {
                //判断pstm是否为空,如果不为空则关闭资源
                if (pstm!=null){
                    pstm.close();
                }
                //判断con是否为空,如果不为空则关闭资源
                if (con!=null){
                    con.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

六、配置servlet类

在.xml内来配置servlet类处理请求

实现代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--配置Servlet类-->
    <servlet>
        <!-- 起别名 -->
        <servlet-name>login</servlet-name>
        <!-- servlet类所在的位置:类的全类名就是 包名.类名 -->
        <servlet-class>com.http.Servlet.Login</servlet-class>
    </servlet>
    <!-- Servlet类的映射:Servlet用来处理哪个请求 -->
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>enroll</servlet-name>
        <servlet-class>com.http.Servlet.Enroll</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>enroll</servlet-name>
        <url-pattern>/enroll</url-pattern>
    </servlet-mapping>
</web-app>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值