2021-04-21 08:34  阅读(76)
文章分类:Servlet 简单教程 文章标签:Servlet
©  原文作者:一点教程 原文地址:http://www.yiidian.com/servlet/

本文我们将创建一个简单的用户登录示例,本文使用MySQL5.7作为数据库。

1 创建表和准备数据

在MySQL的test数据库中创建t_user表:

    
    CREATE TABLE `t_user` (
       `id` int(11) NOT NULL AUTO_INCREMENT,
       `username` varchar(50) DEFAULT NULL,
       `password` varchar(50) DEFAULT NULL,
       PRIMARY KEY (`id`)
     ) ENGINE=InnoDB DEFAULT CHARSET=utf8

插入一些测试数据,待会登录使用:

20210421083118_1.png

2 编写登录页面

编写login.jsp,用于用户登录:

    
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>一点教程网-使用Servlet完成用户登录</title>
    </head>
    <body>
    <h1>使用Servlet完成用户登录</h1>
    <form action="Login" method="post">
        用户名:<input type="text" name="username"/><br/><br/>
        密码:<input type="password" name="userpass"/><br/><br/>
        <input type="submit" value="登录"/>
    </form>
    </body>
    </html>

3 编写LoginServlet

LoginServlet用于查询数据库用户表,以完成用户身份校验逻辑:

    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    public class LoginServlet extends HttpServlet {
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
    
            String n=request.getParameter("username");
            String p=request.getParameter("userpass");
    
            if(LoginDao.validate(n, p)){
                RequestDispatcher rd=request.getRequestDispatcher("Welcome");
                rd.forward(request,response);
            }
            else{
                out.print("抱歉,用户名或密码错误");
                RequestDispatcher rd=request.getRequestDispatcher("login.jsp");
                rd.include(request,response);
            }
    
            out.close();
        }
    
    }
    

4 编写LoginDao

LoginDao用于处理数据库查询的具体逻辑:

    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    public class LoginDao {
    
        public static boolean validate(String name,String pass){
            boolean status=false;
            try{
                Class.forName("com.mysql.jdbc.Driver");
                Connection con= DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/test","root","root");
    
                PreparedStatement ps=con.prepareStatement(
                        "select * from t_user where username=? and password=?");
                ps.setString(1,name);
                ps.setString(2,pass);
    
                ResultSet rs=ps.executeQuery();
                status=rs.next();
    
            }catch(Exception e){
                System.out.println(e);
            }
            return status;
        }
    }
    

5 编写WelcomeServlet

WelcomeServlet是登录成功后的用户欢迎页面:

    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    public class WelcomeServlet extends HttpServlet {
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
    
            String n=request.getParameter("username");
            out.print("欢迎你 "+n);
    
            out.close();
        }
    
    }
    

6 配置web.xml

    
    <?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_3_1.xsd"
             version="3.1">
    
        <servlet>
            <servlet-name>LoginServlet</servlet-name>
            <servlet-class>LoginServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>LoginServlet</servlet-name>
            <url-pattern>/Login</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <servlet-name>WelcomeServlet</servlet-name>
            <servlet-class>WelcomeServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>WelcomeServlet</servlet-name>
            <url-pattern>/Welcome</url-pattern>
        </servlet-mapping>
    
    </web-app>

7 运行测试

先访问登录页面,http://localhost:8080/login.jsp,如下:

20210421083114_2.png

输入了数据库不存在的用户名或密码时,提示如下:

2021042108318_3.png

当输入了正确的用户名和密码,则进入欢迎页面:

202104210839_4.png


本案例需要在lib目录导入mysql驱动程序,点击下面链接下载:

下载mysql-connector-java-5.1.40.jar

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> 使用Servlet完成用户登录
上一篇
使用Servlet完成用户注册
下一篇
使用Servlet完成条件查询