1월 20일

SJY0000·2022년 1월 20일
0

JSP, SERVLET and DB연동

목록 보기
14/24

오늘 배운 것

  • ToDo 로그인, 가입하기 페이지 생성하기
  • ToDo 로그인 만들기

header부분

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<header>
	<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
		<div class="container-fluid">
			<a class="navbar-brand" href="#">TODO APP</a>
			<button class="navbar-toggler" type="button"
				data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
				aria-controls="navbarSupportedContent" aria-expanded="false"
				aria-label="Toggle navigation">
				<span class="navbar-toggler-icon"></span>
			</button>
			<div class="collapse navbar-collapse" id="navbarSupportedContent">
				<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
					<li class="nav-item"><a class="nav-link" href="<%=request.getContextPath()%>/login/login.jsp">로그인</a></li>
					<li class="nav-item"><a class="nav-link" href="<%=request.getContextPath()%>/register/register.jsp">가입하기</a></li>
				</ul>
			</div>
		</div>
	</nav>
</header>
  • 로그인 클릭 시 login.jsp로 이동, 가입하기 클릭 시 register.jsp로 이동
  • 일정크기이하 화면일 때 메뉴바가 변함

footer부분

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<footer class="footer font-small black">
	<div class="footer-copyright text-center py-3">
		© 2022 Copyright : <strong> Korea IT</strong>
	</div>
</footer>

가입하기

  • bootstrap을 이용하여 생성
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/bootstrap.min.css" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/style.css" />
<title>유저 등록</title>
</head>
<body>
	<jsp:include page="../common/header.jsp" />
	<!-- navbar 끝 -->
	<!-- 본문 -->
	<div class="container">
		<h2>유저 등록</h2>
		<div class="col-md-6">
			<div class="alert alert-success center" role="alert">
				<p><%=session.getAttribute("message")%></p>
			</div>
			<form action="<%=request.getContextPath()%>/register" method="post">
				<div class="form-group">
					<label for="firstName">성 :</label> <input type="text"
						class="form-control" name="firstName" required />
				</div>
				<div class="form-group">
					<label for="lastName">이름 :</label> <input type="text"
						class="form-control" name="lastName" required />
				</div>
				<div class="form-group">
					<label for="userName">Id :</label> <input type="text"
						class="form-control" name="userName" required />
				</div>
				<div class="form-group">
					<label for="password">password :</label> <input type="text"
						class="form-control" name="password" required />
				</div>
				<div class="form-group mt-3">
					<button type="submit" class="btn btn-outline-success">
						가입하기</button>
				</div>
			</form>
		</div>
	</div>
	<!-- 본문 끝 -->
	<jsp:include page="../common/footer.jsp" />
	<script src="<%=request.getContextPath()%>/js/bootstrap.bundle.min.js"></script>
</body>
</html>

로그인부분

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/bootstrap.min.css" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/style.css" />
<title>로그인</title>
</head>
<body>
	<jsp:include page="../common/header.jsp" />
	<!-- navbar 끝 -->
	<!-- 본문 -->
	<div class="container">
		<h2>로그인</h2>
		<div class="col-md-6">
			<div class="alert alert-success center" role="alert">
				<p><%=session.getAttribute("message")%></p>
			</div>
			<form action="<%=request.getContextPath()%>/login" method="post">
				<div class="form-group">
					<label for="username">Id :</label> <input type="text"
						class="form-control" name="username" value="<%=session.getAttribute("user") %>" required />
				</div>
				<div class="form-group">
					<label for="password">password :</label> <input type="text"
						class="form-control" name="password" required />
				</div>
				<div class="form-group mt-3">
					<button type="submit" class="btn btn-outline-secondary">
						로그인</button>
				</div>
			</form>
		</div>
	</div>
	<!-- 본문 끝 -->
	<jsp:include page="../common/footer.jsp" />
	<script src="<%=request.getContextPath()%>/js/bootstrap.bundle.min.js"></script>
</body>
</html>

  • ID, password 둘 중 하나라도 일치하지 않으면 실패메시지가 출력됨

users, todos DB table 생성하기

login Controller

package todoApp.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;

import todoApp.dao.LoginDao;
import todoApp.model.LoginBean;

@WebServlet("/login")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private LoginDao loginDao;
	
	@Override
	public void init() {
		loginDao = new LoginDao();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.setAttribute("user", ""); // 공백입력, 로그인 실패를 해도 계속 보여줄 것이기 떄문에					
		session.setAttribute("message", "");	// null값이 출력되지 않도록 공백입력
		// login 페이지로 이동
		response.sendRedirect("login/login.jsp"); // login 폴더 안의 login.jsp페이지로 이동
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8"); // 입력 받을 떄 한글
		response.setContentType("text/html;charset=UTF-8"); // 출력할 떄 한글
		// ID, PASSWORD를 parameter로 입력받기
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		LoginBean loginBean = new LoginBean();
		
		loginBean.setUsername(username);
		loginBean.setPassword(password);
		
		if (loginDao.validate(loginBean)) { // 계정이 있음 => todolist.jsp로 forward
			RequestDispatcher dispatcher = request.getRequestDispatcher("todo/todolist.jsp");
			dispatcher.forward(request, response);
		} else { // 로그인 실패 시
			HttpSession session = request.getSession();
			session.setAttribute("user", username); // ID는 다시 보내줌
			session.setAttribute("message", "잘못입력하셨습니다.");
			response.sendRedirect("login/login.jsp"); // 모든 입력데이터가 사라짐(페이지 새로열기)
		}	
	}
}

SQL문을 이용하여 DB데이터 조회

package todoApp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import todoApp.model.LoginBean;
import todoApp.utils.JDBCUtils;

// DB연결하여 login 확인하는 메소드 만들 Class
public class LoginDao {
	// 계정이 있으면 true, 없으면 false
	public boolean validate(LoginBean loginbean) {
		boolean status = false;
		String sql = "SELECT * from users where userName = ? and password = ?";
		
		try {
			Connection conn = JDBCUtils.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, loginbean.getUsername());
			pstmt.setString(2, loginbean.getPassword());
			
			ResultSet rs = pstmt.executeQuery();
			
			status = rs.next(); // 한 줄이라도 있으면 true, 없으면 false
		} catch (SQLException e) {
			System.out.println("SQL login ERROR!");
		}
		return status;
	}
}

0개의 댓글

관련 채용 정보