넓고얕은지식사전

JSP & Servlet 게시판 구현하기(로그인) 본문

IT/JSP & Servlet

JSP & Servlet 게시판 구현하기(로그인)

맛난이 2023. 1. 12. 23:05
반응형

지난번에 가입 기능을 구현 하였다.

https://nullgoyatten.tistory.com/18

 

 

JSP & Servlet 게시판 구현하기(가입)

이클립스에서 회원제 게시판을 구현해 보자 게시판을 구현하기에 앞서 DB를 구축하자. 필자는 앞서 만들어 놓은 VMware DB서버를 사용할 예정이다. 이 글이 처음 본 사람 이라면 아래의 링크를 통

nullgoyatten.tistory.com

그렇다면 이번에는 로그인 기능을 구현해보자.

 

1. 패키지 생성 (패키지명 : auth.service)

 

2. User 클래스는 로그인 한 사용자 정보를 담는다. 

경로 : auth.service > User.java

package auth.service;

public class User {

	private String id;
	private String name;

	public User(String id, String name) {
		this.id = id;
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

}

 

3. LoginFailException 클래스를 만든다. 

경로 : auth.service > LoginFailException.java

package auth.service;

public class LoginFailException extends RuntimeException {

}

 

4. LoginService 클래스는 사용자가 입력한 아이디와 암호가 올바른지 검사한다. 아이디와 암호가 일치하면 로그인 한 사용자 정보를 담은 User객체를 리턴한다. 

경로 : auth.service > LoginService.java

package auth.service;

import java.sql.Connection;
import java.sql.SQLException;

import jdbc.connection.ConnectionProvider;
import member.dao.MemberDao;
import member.model.Member;

public class LoginService {

	private MemberDao memberDao = new MemberDao();

	public User login(String id, String password) {
		try (Connection conn = ConnectionProvider.getConnection()) {
			Member member = memberDao.selectById(conn, id);
			if (member == null) {
				throw new LoginFailException();
			}
			if (!member.matchPassword(password)) {
				throw new LoginFailException();
			}
			return new User(member.getId(), member.getName());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}

5. 패키지 생성 (패키지명 : auth.command)

 

6. LoginHandler 작성. GET방식 요청시 폼을 위한 뷰를 리턴하고 POST방식 요청시 LoginService를 이용하여 로그인을 처리한다. 

경로 : auth.command> LoginHandler.java

package auth.command;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import auth.service.LoginFailException;
import auth.service.LoginService;
import auth.service.User;
import mvc.command.CommandHandler;

public class LoginHandler implements CommandHandler {

	private static final String FORM_VIEW = "/WEB-INF/view/loginForm.jsp";
	private LoginService loginService = new LoginService();

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) 
	throws Exception {
		if (req.getMethod().equalsIgnoreCase("GET")) {
			return processForm(req, res);
		} else if (req.getMethod().equalsIgnoreCase("POST")) {
			return processSubmit(req, res);
		} else {
			res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			return null;
		}
	}

	private String processForm(HttpServletRequest req, HttpServletResponse res) {
		return FORM_VIEW;
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) 
	throws Exception {
		String id = trim(req.getParameter("id"));
		String password = trim(req.getParameter("password"));

		Map<String, Boolean> errors = new HashMap<>();
		req.setAttribute("errors", errors);

		if (id == null || id.isEmpty())
			errors.put("id", Boolean.TRUE);
		if (password == null || password.isEmpty())
			errors.put("password", Boolean.TRUE);

		if (!errors.isEmpty()) {
			return FORM_VIEW;
		}

		try {
			User user = loginService.login(id, password);
			req.getSession().setAttribute("authUser", user);
			res.sendRedirect(req.getContextPath() + "/index.jsp");
			return null;
		} catch (LoginFailException e) {
			errors.put("idOrPwNotMatch", Boolean.TRUE);
			return FORM_VIEW;
		}
	}

	private String trim(String str) {
		return str == null ? null : str.trim();
	}
}

 

 

7. commandHandlerURI.properties 수정. LoginHandler가 /login.do 요청을 처리하도록 매핑 설정에 추가한다. 

/join.do=member.command.JoinHandler
/login.do=auth.command.LoginHandler

8. loginForm.jsp 작성

경로 :  WebContent > WEB-INF > view > loginForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>로그인</title>
</head>
<body>
<form action="login.do" method="post">
<c:if test="${errors.idOrPwNotMatch}">
아이디와 암호가 일치하지 않습니다.
</c:if>
<p>
	아이디:<br/><input type="text" name="id" value="${param.id}">
	<c:if test="${errors.id}">ID를 입력하세요.</c:if>
</p>
<p>
	암호:<br/><input type="password" name="password">
	<c:if test="${errors.password}">암호를 입력하세요.</c:if>
</p>
<input type="submit" value="로그인">
</form>
</body>
</html>

9. index.jsp 작성

경로 :  WebContent > index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="u" tagdir="/WEB-INF/tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>회원제 게시판 예제</title>
</head>
<body>
<%-- 
<c:if test="${! empty authUser}">
	${authUser.name}님, 안녕하세요.
	<a href="logout.do">[로그아웃하기]</a>
	<a href="changePwd.do">[암호변경하기]</a>
</c:if>
<c:if test="${empty authUser}">
	<a href="join.do">[회원가입하기]</a>
	<a href="login.do">[로그인하기]</a>
</c:if>
--%>
<u:isLogin>
	CT: ${authUser.name}님, 안녕하세요.
	<a href="logout.do">[로그아웃하기]</a>
	<a href="changePwd.do">[암호변경하기]</a>
</u:isLogin>
<u:notLogin>
	CT: <a href="join.do">[회원가입하기]</a>
	<a href="login.do">[로그인하기]</a>
</u:notLogin>
<br/>
</body>
</html>

 

10. 폴더 생성 (폴더명 : tags)

경로 :  WebContent > WEB-INF > tags

 

11. isLogin.tag 작성

경로 :  WebContent > WEB-INF > tags > isLogin.tag

<%@ tag body-content="scriptless" pageEncoding="utf-8" %>
<%@ tag trimDirectiveWhitespaces="true" %>
<%
	HttpSession httpSession = request.getSession(false);
	if (httpSession != null && httpSession.getAttribute("authUser") != null) {
%>
<jsp:doBody />
<%
	}
%>

12. notLogin.tag 작성

경로 :  WebContent > WEB-INF > tags > notLogin.tag

<%@ tag body-content="scriptless" pageEncoding="utf-8" %>
<%@ tag trimDirectiveWhitespaces="true" %>
<%
	HttpSession httpSession = request.getSession(false);
	if (httpSession == null || httpSession.getAttribute("authUser") == null) {
%>
<jsp:doBody />
<%
	}
%>

 

13. 테스트

잘된다.

 

다음글 : 로그아웃 구현

https://nullgoyatten.tistory.com/20

 

JSP & Servlet 게시판 구현하기(로그아웃)

지난번에 로그인 기능을 구현 하였다. https://nullgoyatten.tistory.com/19 그렇다면 이번에는 로그아웃 기능을 이어서 구현해보자. 1. LogoutHandler 작성 경로 : auth.command> LogoutHandler.java package auth.command; impor

nullgoyatten.tistory.com

 

반응형
Comments