먼저 자바 웹 프로젝트를 생성해야 합니다. 프로젝트 생성 방법은 다음 링크를 참조할 수 있습니다:
https://blog.csdn.net/u012532559/article/details/51013400
프로젝트 구조는 다음과 같습니다:
- 로그인 페이지 index.jsp 내용 수정
<%--
Created by IntelliJ IDEA.
User: Developer
Date: 2023/11/15
Time: 10:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>로그인</title>
</head>
<body>
<div id="login-container" style="width: 350px;margin: 0px auto">
<div id="login-box">
<form action="AuthenticationServlet" method="post">
<div class="form-section">
<div>
<label>아이디:</label>
<input name="userId" value="">
</div>
<div>
<label>비밀번호:</label>
<input type="password" name="userPassword" value="">
</div>
<div>
<input type="submit" value="로그인">
</div>
</div>
</form>
</div>
</div>
</body>
</html>
- DBUtil 클래스 생성
package com.example.db;
import java.sql.*;
public class DatabaseConnector {
// SQL Server 드라이버 클래스명
private static final String DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 데이터베이스 연결 URL
private static final String CONNECTION_URL = "jdbc:sqlserver://localhost:1433;integratedSecurity=true;DatabaseName=WebApp";
// 데이터베이스 사용자명
private static final String DB_USER = ".";
// 데이터베이스 비밀번호
private static final String DB_PASSWORD = "";
public static Connection establishConnection(){
try {
// SQL Server 드라이버 로드
Class.forName(DRIVER_CLASS);
// 데이터베이스 연결 반환
return DriverManager.getConnection(CONNECTION_URL);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void closeResources(Connection conn,Statement stmt , ResultSet rs ){
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null){
try{
rs.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
System.out.println("DB 연결 테스트: " + establishConnection());
}
}
- User 엔티티 클래스 생성
package com.example.model;
public class Account {
private String userId;
private String userPassword;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
- AccountDao 클래스 생성
package com.example.dao;
import java.sql.*;
import com.example.model.Account;
import com.example.db.DatabaseConnector;
public class AccountDao {
// 사용자 ID로 계정 정보 조회
public Account findAccountById(String userId){
// SQL 쿼리문 작성
String query = "select * from Users where userId=?";
// 데이터베이스 연결 객체
Connection conn= DatabaseConnector.establishConnection();
// 결과셋
ResultSet rs= null;
// Account 객체 생성
Account account = new Account();
try {
// PreparedStatement 생성
PreparedStatement ps = conn.prepareStatement(query);
// 파라미터 설정
ps.setString(1, userId);
// 쿼리 실행
rs=ps.executeQuery();
// 결과가 존재하는 경우
if(rs.next()){
// Account 객체에 데이터 설정
account.setUserId(rs.getString(1));
account.setUserPassword(rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
// 리소스 해제
DatabaseConnector.closeResources(conn, null, rs);
}
// Account 객체 반환
return account;
}
public static void main(String[] args) {
AccountDao dao = new AccountDao();
Account user = dao.findAccountById("testuser");
System.out.println("조회된 비밀번호: " + user.getUserPassword());
}
}
- AuthService 클래스 생성
package com.example.service;
import com.example.dao.AccountDao;
import com.example.model.Account;
public class AuthService {
public boolean authenticateUser(String userId, String userPassword) {
AccountDao dao = new AccountDao();
Account account = dao.findAccountById(userId);
System.out.println("계정 정보: " + account);
return account != null && userPassword.equals(account.getUserPassword()) ? true : false;
}
}
- AuthenticationServlet 클래스 생성
package com.example.servlet;
import java.io.IOException;
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 com.example.service.AuthService;
@WebServlet(name = "AuthenticationServlet")
public class AuthenticationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 인코딩 설정
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 요청 파라미터 추출
String userId = request.getParameter("userId");
String userPassword = request.getParameter("userPassword");
AuthService authService = new AuthService();
// 인증 서비스 호출
boolean isAuthenticated = authService.authenticateUser(userId, userPassword);
String result = isAuthenticated ? "success" : "failure";
request.setAttribute("result", result);
if(result.equals("success")){
request.getRequestDispatcher("login_success.jsp").forward(request, response);
}
else{
request.getRequestDispatcher("login_failure.jsp").forward(request, response);
}
}
}
- 마지막으로 index.jsp와 동일한 디렉토리에 login_success.jsp와 login_failure.jsp 파일을 생성하여 로그인 성공 또는 실패 시 이동할 페이지를 만듭니다.
참고: "Failed to load the sqljdbc_auth.dll cause :- no sqljdbc_auth in java.library.path" 경고가 나타나면, sqljdbc_auth.dll 파일을 JDK의 bin 폴더에 추가해야 합니다. 예를 들어, D:\jdk-8\bin 경로에 파일을 배치하면 문제를 해결할 수 있습니다.