服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - JavaWeb Servlet实现网页登录功能

JavaWeb Servlet实现网页登录功能

2021-09-26 00:55跑起来要带风! Java教程

这篇文章主要为大家详细介绍了JavaWeb Servlet实现网页登录功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

上次写了一篇JDBC工具类实现登录功能,但是只能在控制台实现输入用户名密码。这次使用了Servlet来实现登录功能,可以通过在页面上输入账号密码,然后提交表单,查询数据库,从而实现登录功能。

1、配置文件,导入jar包

JavaWeb Servlet实现网页登录功能

2、创建数据库环境

?
1
2
3
4
5
6
7
8
9
use student;
create table user(
 id int primary key auto_increment,
    username varchar(32),
    password varchar(32)
);
 
insert into user values(null,'zhangsan','123');
insert into user values(null,'lisi','234');

3、在web目录下创建HTML页面

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
    <form action="/day14_request/loginServlet" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

4、在src下编写druid.properties文件

?
1
2
3
4
5
6
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student
username=root
password=root
maxActive=10
maxWait=1000

5、创建包cn.itcast.domain,创建类User

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package cn.itcast.domain;
 
/*
    用户的实体类
 */
public class User {
    private int id;
    private String username;
    private String password;
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

6、创建包cn.itcast.util,编写工具类JDBCUtils

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package cn.itcast.util;
 
import com.alibaba.druid.pool.DruidDataSourceFactory;
 
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
 
/*
    JDBC工具类,使用Durid连接池
 */
public class JDBCUtils {
    private static DataSource dataSource;
 
    static {
        try {
            //1、加载配置文件
            Properties properties = new Properties();
            InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(resourceAsStream);
 
            //2、初始化连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
 
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
 
    }
 
    /**
     * 获取连接池对象
     */
    public static DataSource getDataSource() {
        return dataSource;
    }
 
    /**
     * 获取连接Connection对象
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}

7、创建包cn.itcast.dao,创建类UserDao,提供login方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package cn.itcast.dao;
 
import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
 
/**
 * 操作数据库中User表的类
 */
public class UserDao {
    //声明JDBCTemplate对象共用
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
 
    /**
     * 登录方法
     * @param loginUser 只有用户和密码
     * @return user 包含用户全部信息,没有查询到,返回null
     */
    public User login(User loginUser) {
 
        try {
            //1、编写sql
            String sql = "select * from user where username = ? and password = ?";
 
            //2、调用query方法
            User user = jdbcTemplate.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    loginUser.getUsername(),loginUser.getPassword());
            return user;
        } catch (DataAccessException e) {
            e.printStackTrace();//记录日志
            return null;
        }
    }
 
}

8、编写cn.itcast.web.servlet.LoginServlet类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package cn.itcast.web.servlet;
 
import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import org.apache.commons.beanutils.BeanUtils;
 
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;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
 
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、设置编码
        request.setCharacterEncoding("utf-8");
 
        /*//2、获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //3、封装对象
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);*/
 
        //2、获取所有请求参数(这里使用BeanUtils来简化操作)
        Map<String, String[]> parameterMap = request.getParameterMap();
        //3.1 创建User对象
        User loginUser = new User();
        //3.2 使用BeanUtils对象
        try {
            BeanUtils.populate(loginUser,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
 
 
        //4、调用UserDao的login方法
        UserDao userDao = new UserDao();
        User user = userDao.login(loginUser);
 
        //5、判断user
        if (user == null) {
            //登录失败
            request.getRequestDispatcher("/failServlet").forward(request,response);
        } else {
            //登录成功
            //存储数据
            request.setAttribute("user",user);
            //转发
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

运行结果:

1、目录结构

JavaWeb Servlet实现网页登录功能

2、运行界面

JavaWeb Servlet实现网页登录功能

3、输入用户名密码均正确

JavaWeb Servlet实现网页登录功能

4、跳转到成功登录界面

JavaWeb Servlet实现网页登录功能

5、输入用户名或密码错误时

JavaWeb Servlet实现网页登录功能

6、跳转登录失败界面

JavaWeb Servlet实现网页登录功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_44668898/article/details/107542031

延伸 · 阅读

精彩推荐