JavaWeb Servlet實現網頁登錄功能

上次寫瞭一篇JDBC工具類實現登錄功能,但是隻能在控制臺實現輸入用戶名密碼。這次使用瞭Servlet來實現登錄功能,可以通過在頁面上輸入賬號密碼,然後提交表單,查詢數據庫,從而實現登錄功能。

1、配置文件,導入jar包

2、創建數據庫環境

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頁面

<!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文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student
username=root
password=root
maxActive=10
maxWait=1000

5、創建包cn.itcast.domain,創建類User

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

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方法

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類

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、目錄結構

2、運行界面

3、輸入用戶名密碼均正確

4、跳轉到成功登錄界面

5、輸入用戶名或密碼錯誤時

6、跳轉登錄失敗界面

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: