본문 바로가기

jsp 프로젝트 V2 post

JSP게시판 만들기 7강 - 로그인

로그인시 username과 password로 select하여 찾으면 해당 오브젝트를 session에 담는다.

session은 어디에서나 찾을 수 있는 메모리 영역이다.

 

1. MemberDao.java

public Member 로그인(String username, String password) {
		try {
			String sql = "SELECT * FROM member WHERE username = ? AND password = ?";
			conn = DBConn.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			
			rs = pstmt.executeQuery();
			if(rs.next()) {
				Member member = new Member();	
				member.setId(rs.getInt("id"));
				member.setUsername(rs.getString("username"));				
				member.setPassword(rs.getString("password"));
				member.setEmail(rs.getString("email"));
				member.setCreateDate(rs.getTimestamp("createDate"));
				return member;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

2. MemberLoginProcAction.java

package com.cos.apple.db.action.member;

import java.io.IOException;

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

import com.cos.apple.db.action.Action;
import com.cos.apple.db.dao.MemberDao;
import com.cos.apple.db.model.Member;

public class MemberLoginProcAction implements Action{

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		MemberDao memberDao = new MemberDao();
		Member principal = memberDao.로그인(username, password);
		
		if(principal == null) {
			response.sendRedirect("member/loginForm.jsp");
		}else {
			HttpSession session = request.getSession();
			session.setAttribute("principal", principal);
			response.sendRedirect("index.jsp");
		}
	}

}

 

3. 회원가입 및 로그인 테스트 진행