JavaWeb使用mvc模式實現(xiàn)登錄功能
部署項目、環(huán)境搭建


詳細內(nèi)容
1.導(dǎo)包

2.web >> index.jsp web >> login.jsp web >> success.jsp

1) web >> index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="login.jsp">登錄</a>
</body>
</html>2) web >> login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄</title>
<style>
#msg {
color: red;
}
</style>
</head>
<body>
<form action="user" method="post">
賬號:<input type="text" name="userName"><span id="msg"><%=request.getAttribute("msg")%></span>
密碼:<input type="text" name="passWord">
<input type="hidden" name="method" value="login">
<input type="submit" value="登錄">
</form>
</body>
</html>3) web >> success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="constant.Con" %>
<html>
<head>
<title>用戶中心</title>
</head>
<body>
<%=request.getSession().getAttribute(Con.USER)%><h1 style="color: green">歡迎您</h1>
<a href="login.html">返回重新登錄</a>
</body>
</html>3.constant >> Con

package constant;
import java.io.Serializable;
public class Con implements Serializable {
//session中保存用戶登錄信息
public static final String USER = "user";
}entity >> User

package entity;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String userName;
private String passWord;
public User(int id, String userName, String passWord) {
this.id = id;
this.userName = userName;
this.passWord = passWord;
}
public User() {
}
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;
}
}4.resources >> prop.properties

driverClassName=com.mysql.cj.jdbc.Driver urlName=jdbc:mysql://localhost:3306/myjdbc?characterEncoding=utf8&useSSL=false&serverTimezone=UTC userName=root passwordName=root

5.utils >> JDBCUtils

package utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/*
JDBC工具類
*/
public class JDBCUtils {
// 聲明驅(qū)動的路徑
static String driverClass;
static String url;
static String user;
static String password;
/*
靜態(tài)代碼塊只會在加載class文件的時候執(zhí)行一次,
將注冊驅(qū)動的代碼由靜態(tài)代碼塊來實現(xiàn)
*/
static {
// 創(chuàng)建屬性集對象
Properties prop = new Properties();
// 將文件中的數(shù)據(jù)讀取到屬性集中
try {
//prop.properties
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("prop.properties");
prop.load(is);
} catch (IOException e) {
e.printStackTrace();
}
// 獲取key對應(yīng)的value
driverClass = prop.getProperty("driverClassName");
url = prop.getProperty("urlName");
user = prop.getProperty("userName");
password = prop.getProperty("passwordName");
try {
// 加載驅(qū)動
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
將獲取資源的方法進行封裝: Connection連接接口對象
*/
public static Connection getConnection() throws SQLException, ClassNotFoundException {
// 獲取連接
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
/*
封裝方法,用于釋放資源
*/
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
// 調(diào)用已經(jīng)實現(xiàn)功能的方法直接使用
close(connection, statement);
}
/*
重載一個釋放資源的代碼,用來釋放兩個資源
*/
public static void close(Connection connection, Statement statement) {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}6.servlet >> UserServlet

package servlet;
import constant.Con;
import service.UserService;
import service.impl.UserServiceImpl;
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;
@WebServlet(name = "user", urlPatterns = "/user")
public class UserServlet extends HttpServlet {
private UserService userService = new UserServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.設(shè)置請求字符集為utf-8
req.setCharacterEncoding("utf-8");
//2.獲取請求參數(shù)method,根據(jù)值調(diào)用不同方法處理業(yè)務(wù)
String method = req.getParameter("method");
if (method.equals("login")) {
this.login(req, resp);
}
}
//登錄方法
private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.獲取賬號和密碼
String userName = req.getParameter("userName");
String passWord = req.getParameter("passWord");
//2.調(diào)用service的方法處理登錄
boolean result = userService.checkUser(userName, passWord);
if (result) {
//true表示登錄成功
//轉(zhuǎn)發(fā)跳轉(zhuǎn)成功頁面
//req.getRequestDispatcher("/success.jsp").forward(req, resp);
//將用戶信息保存在session域?qū)ο笾?
req.getSession().setAttribute(Con.USER, userName);
//重定向跳轉(zhuǎn)成功頁面
resp.sendRedirect(req.getContextPath() + "/success.jsp");
} else {
//false登錄失敗,返回登錄頁面
req.setAttribute("msg", "賬號密碼不匹配");
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
}
}7.service >> UserService service >> impl >> UserServiceImpl

package service;
public interface UserService {
//判斷登錄成功與否
boolean checkUser(String userName, String passWord);
}package service.impl;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import entity.User;
import service.UserService;
import utils.JDBCUtils;
import java.sql.Connection;
import java.util.List;
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoImpl();
@Override
public boolean checkUser(String userName, String passWord) {
// 連接對象
Connection connection = null;
try {
//1.獲取數(shù)據(jù)庫連接
connection = JDBCUtils.getConnection();
//2.調(diào)用dao方法查詢數(shù)據(jù)
List<User> users = userDao.findUserByUserNameAndPassWord(connection, userName, passWord);
//3.根據(jù)查詢結(jié)果返回成功失敗標志
if (users.size() > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
JDBCUtils.close(connection, null);
}
}
}8.dao >> UserDao dao >> impl >> UserDaoImpl

package dao;
import entity.User;
import java.sql.Connection;
import java.util.List;
public interface UserDao {
//根據(jù)賬號密碼查詢數(shù)據(jù)庫,返回結(jié)果集
List<User> findUserByUserNameAndPassWord(Connection connection, String userName, String passWord);
}package dao.impl;
import dao.UserDao;
import entity.User;
import utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements UserDao {
@Override
public List<User> findUserByUserNameAndPassWord(Connection connection, String userName, String passWord) {
// 發(fā)送sql語句對象
PreparedStatement statement = null;
List<User> userList = new ArrayList<>();
try {
connection = JDBCUtils.getConnection();
// 獲取Statement對象
statement = connection.prepareStatement("select * from user where username = ? and password = ?");
statement.setString(1, userName);
statement.setString(2, passWord);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
User user = new User();
int id = rs.getInt(1);
String username = rs.getString(2);
String password = rs.getString(3);
user.setId(id);
user.setUserName(username);
user.setPassWord(password);
userList.add(user);
}
return userList;
} catch (Exception e) {
e.printStackTrace();
return userList;
} finally {
JDBCUtils.close(null, statement, null);
}
}
}登錄實現(xiàn)
1.首頁 index.jsp

2.錯誤登錄 login.jsp


3. 正確登錄 login.jsp

4. 登錄成功 success.jsp

到此這篇關(guān)于JavaWeb使用mvc模式實現(xiàn)登錄功能的文章就介紹到這了,更多相關(guān)JavaWeb mvc登錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java jni調(diào)用c函數(shù)實例分享(java調(diào)用c函數(shù))
Java代碼中調(diào)用C/C++代碼,當然是使用JNI,JNI是Java native interface的簡寫,可以譯作Java原生接口,下面看實例吧2013-12-12
如何更優(yōu)雅地獲取spring boot yml中的值
這篇文章主要給大家介紹了關(guān)于如何更優(yōu)雅地獲取spring boot yml中值的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用spring boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
使用Spring的StopWatch實現(xiàn)代碼性能監(jiān)控的方法詳解
在開發(fā)過程中,偶爾還是需要分析代碼的執(zhí)行時間,Spring 框架提供了一個方便的工具類 StopWatch,本文將介紹 StopWatch 的基本用法,并通過示例演示如何在項目中使用 StopWatch 進行代碼性能監(jiān)控2023-12-12
IDEA編譯報錯:Error:(2048,1024) java: 找不到符號的解決方案
在使用 Lombok 的過程中,你是否曾遇到過 IDEA 編譯報錯 Error:(2048,1024) java: 找不到符號?下面就讓我們來深入剖析這一問題的根源,并給出相應(yīng)的解決方案,需要的朋友可以參考下2025-02-02
JAVA8 STREAM COLLECT GROUPBY分組實例解析
這篇文章主要介紹了JAVA8 STREAM COLLECT GROUPBY分組實例解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-01-01
重學(xué)SpringBoot3之如何發(fā)送Email郵件功能
這篇文章主要給大家介紹了重學(xué)SpringBoot3之如何發(fā)送Email郵件功能的相關(guān)資料,文中包括環(huán)境準備、項目配置、代碼實現(xiàn)、最佳實踐和安全性建議,通過采用異步發(fā)送、重試機制、限流等最佳實踐,可以構(gòu)建一個健壯的郵件發(fā)送系統(tǒng),需要的朋友可以參考下2024-11-11
自定義spring mvc的json視圖實現(xiàn)思路解析
這篇文章主要介紹了自定義spring mvc的json視圖的實現(xiàn)思路解析,本文給大家介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2017-12-12
SpringBoot整合Canal+RabbitMQ監(jiān)聽數(shù)據(jù)變更詳解
在現(xiàn)代分布式系統(tǒng)中,實時獲取數(shù)據(jù)庫的變更信息是一個常見的需求,本文將介紹SpringBoot如何通過整合Canal和RabbitMQ監(jiān)聽數(shù)據(jù)變更,需要的可以參考下2024-12-12

