DAO 를 추가하고
톰캣을 실행해서 잘 작동하는 지 확인해 보자
회원가입 먼저 테스트
RegisterController.java
package com.jcy.usedhunter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jcy.usedhunter.dao.UserDao;
import com.jcy.usedhunter.domain.User;
import com.jcy.usedhunter.validator.UserValidator;
@Controller // ctrl+shift+o 자동 import
@RequestMapping("/register")
public class RegisterController {
@Autowired
UserDao userDao;
final int FAIL = 0;
@InitBinder
public void toDate(WebDataBinder binder) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
binder.setValidator(new UserValidator()); // UserValidator를 WebDataBinder의 로컬 validator로 등록
// List<Validator> validatorList = binder.getValidators();
// System.out.println("validatorList="+validatorList);
}
@GetMapping("/add")
public String register() {
return "registerForm"; // WEB-INF/views/registerForm.jsp
}
@PostMapping("/add")
public String save(@Valid User user, BindingResult result, Model m) throws Exception {
System.out.println("result="+result);
System.out.println("user="+user);
// User객체를 검증한 결과 에러가 있으면, registerForm을 이용해서 에러를 보여줘야 함.
if(!result.hasErrors()) {
// 2. DB에 신규회원 정보를 저장
int rowCnt = userDao.insertUser(user);
if(rowCnt!=FAIL) {
return "registerInfo";
}
}
return "registerForm";
}
private boolean isValid(User user) {
return true;
}
}
registerForm.java
<%@ page contentType="text/html;charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page import="java.net.URLDecoder"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />
<style>
* { box-sizing:border-box; }
form {
width:400px;
height:600px;
display : flex;
flex-direction: column;
align-items:center;
position : absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%) ;
border: 1px solid rgb(89,117,196);
border-radius: 10px;
}
.input-field {
width: 300px;
height: 40px;
border : 1px solid rgb(89,117,196);
border-radius:5px;
padding: 0 10px;
margin-bottom: 10px;
}
label {
width:300px;
height:30px;
margin-top :4px;
}
button {
background-color: rgb(89,117,196);
color : white;
width:300px;
height:50px;
font-size: 17px;
border : none;
border-radius: 5px;
margin : 20px 0 30px 0;
}
.title {
font-size : 50px;
margin: 40px 0 30px 0;
}
.msg {
height: 30px;
text-align:center;
font-size:16px;
color:red;
margin-bottom: 20px;
}
.sns-chk {
margin-top : 5px;
}
</style>
<title>Register</title>
</head>
<body>
<!-- form action="<c:url value="/register/save"/>" method="POST" onsubmit="return formCheck(this)"-->
<form:form modelAttribute="user">
<div class="title">Register</div>
<div id="msg" class="msg"><form:errors path="id"/></div>
<label for="">아이디</label>
<input class="input-field" type="text" name="id" placeholder="8~12자리의 영대소문자와 숫자 조합">
<label for="">비밀번호</label>
<input class="input-field" type="text" name="pwd" placeholder="8~12자리의 영대소문자와 숫자 조합">
<label for="">이름</label>
<input class="input-field" type="text" name="name" placeholder="홍길동">
<label for="">이메일</label>
<input class="input-field" type="text" name="email" placeholder="example@aaa.co.kr">
<label for="">생일</label>
<input class="input-field" type="text" name="birth" placeholder="2020-12-31">
<div class="sns-chk">
<label><input type="checkbox" name="sns" value="facebook"/>페이스북</label>
<label><input type="checkbox" name="sns" value="kakaotalk"/>카카오톡</label>
<label><input type="checkbox" name="sns" value="instagram"/>인스타그램</label>
</div>
<button>회원 가입</button>
</form:form>
<script>
function formCheck(frm) {
let msg ='';
if(frm.id.value.length<3) {
setMessage('id의 길이는 3이상이어야 합니다.', frm.id);
return false;
}
return true;
}
function setMessage(msg, element){
document.getElementById("msg").innerHTML = `<i class="fa fa-exclamation-circle"> ${'${msg}'}</i>`;
if(element) {
element.select();
}
}
</script>
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<c:set var="loginOutLink" value="${pageContext.request.getSession(false).getAttribute('id')==null ? '/login/login' : '/login/logout'}"/>
<c:set var="loginOut" value="${pageContext.request.getSession(false).getAttribute('id')==null ? 'Login' : 'Logout'}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>중고헌터</title>
<link rel="stylesheet" href="<c:url value='/css/menu.css'/>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css"/>
</head>
<body>
<div id="menu">
<ul>
<li id="logo">중고헌터</li>
<li><a href="<c:url value='/'/>">Home</a></li>
<li><a href="<c:url value='/board/list'/>">Board</a></li>
<li><a href="<c:url value='${loginOutLink}'/>">${loginOut}</a></li>
<li><a href="<c:url value='/register/add'/>">Sign in</a></li>
<li><a href=""><i class="fas fa-search small"></i></a></li>
</ul>
</div>
<div style="text-align:center">
<h1>This is HOME</h1>
<h1>This is HOME</h1>
<h1>This is HOME</h1>
</div>
registerInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>id=${user.id}</h1>
<h1>pwd=${user.pwd}</h1>
<h1>name=${user.name}</h1>
<h1>email=${user.email}</h1>
<h1>birth=${user.birth}</h1>
<h1>sns=${user.sns}</h1>
</body>
</html>
로그인 테스트
LoginController.java
package com.jcy.usedhunter;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jcy.usedhunter.dao.UserDao;
import com.jcy.usedhunter.dao.UserDaoImpl;
import com.jcy.usedhunter.domain.User;
@Controller
@RequestMapping("/login")
public class LoginController {
@Autowired
UserDao userDao;
@GetMapping("/login")
public String loginForm() {
return "loginForm";
}
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
// 1. 세션을 종료
HttpSession session = request.getSession();
session.invalidate();
// 2. 홈으로 이동
return "redirect:/";
}
@PostMapping("/login")
public String login(String id, String pwd, String toURL, boolean rememberId,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// 1. id와 pwd를 확인
if(!loginCheck(id, pwd)) {
String msg = URLEncoder.encode("id 또는 pwd가 일치하지 않습니다.", "utf-8");
// 2-1. 일치하지 않으면 loginForm 으로 이동
return "redirect:/login/login?msg="+msg;
}
// 2-2. id와 pwd 가 일치하면
// 세션 객체를 얻어오기
HttpSession session = request.getSession();
// 세션 객체에 id 를 저장
session.setAttribute("id", id);
if(rememberId) {
// 1. 쿠키를 생성
Cookie cookie = new Cookie("id", id);
// 2. 응답에 저장
response.addCookie(cookie);
} else {
// 1. 쿠키를 삭제
Cookie cookie = new Cookie("id", id);
cookie.setMaxAge(0);
// 2. 응답에 저장
response.addCookie(cookie);
}
// 3. 홈으로 이동
toURL = toURL==null || toURL.equals("") ? "/" : toURL;
return "redirect:"+toURL;
}
private boolean loginCheck(String id, String pwd) {
User user = userDao.selectUser(id);
if(user==null) {
return false;
}
return user.getPwd().equals(pwd);
// return "asdf".equals(id) && "1234".equals(pwd);
}
}
loginForm.jsp
<%@ page contentType="text/html;charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page session="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />
<style>
* { box-sizing:border-box; }
a { text-decoration: none; }
form {
width:400px;
height:500px;
display : flex;
flex-direction: column;
align-items:center;
position : absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%) ;
border: 1px solid rgb(89,117,196);
border-radius: 10px;
}
input[type='text'], input[type='password'] {
width: 300px;
height: 40px;
border : 1px solid rgb(89,117,196);
border-radius:5px;
padding: 0 10px;
margin-bottom: 10px;
}
button {
background-color: rgb(89,117,196);
color : white;
width:300px;
height:50px;
font-size: 17px;
border : none;
border-radius: 5px;
margin : 20px 0 30px 0;
}
#title {
font-size : 50px;
margin: 40px 0 30px 0;
}
#msg {
height: 30px;
text-align:center;
font-size:16px;
color:red;
margin-bottom: 20px;
}
</style>
</head>
<body>
<form action="<c:url value='/login/login'/>" method="post" onsubmit="return formCheck(this);">
<h3 id="title">Login</h3>
<div id="msg">
<c:if test="${not empty param.msg}">
<i class="fa fa-exclamation-circle"> ${URLDecoder.decode(param.msg)}</i>
</c:if>
</div>
<input type="text" name="id" value="${cookie.id.value}" placeholder="이메일 입력" autofocus>
<input type="password" name="pwd" placeholder="비밀번호">
<input type="hidden" name="toURL" value="${param.toURL}">
<button>로그인</button>
<div>
<label><input type="checkbox" name="rememberId" ${empty cookie.id.value ? "":"checked" }> 아이디 기억</label> |
<a href="">비밀번호 찾기</a> |
<a href="">회원가입</a>
</div>
<script>
function formCheck(frm) {
let msg ='';
if(frm.id.value.length==0) {
setMessage('id를 입력해주세요.', frm.id);
return false;
}
if(frm.pwd.value.length==0) {
setMessage('password를 입력해주세요.', frm.pwd);
return false;
}
return true;
}
function setMessage(msg, element){
document.getElementById("msg").innerHTML = ` ${'${msg}'}`;
if(element) {
element.select();
}
}
</script>
</form>
</body>
</html>
DB에 값이 잘 들어갔다.
에러 메시지가 잘 작동하는 지 확인하자
UserValidator.java
package com.jcy.usedhunter.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.jcy.usedhunter.domain.User;
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
// return User.class.equals(clazz); // 검증하려는 객체가 User타입인지 확인
return User.class.isAssignableFrom(clazz); // clazz가 User 또는 그 자손인지 확인
}
@Override
public void validate(Object target, Errors errors) {
System.out.println("UserValidator.validate() is called");
User user = (User)target;
String id = user.getId();
// if(id==null || "".equals(id.trim())) {
// errors.rejectValue("id", "required");
// }
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "required"); // required.user.id
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "pwd", "required"); // required.user.pwd
if(id==null || id.length() < 5 || id.length() > 12) {
errors.rejectValue("id", "invalidLength", new String[]{"5","12"}, null);
}
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.jcy.usedhunter" />
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basenames">
<beans:list>
<beans:value>error_message</beans:value> <!-- /src/main/resources/error_message.properties -->
</beans:list>
</beans:property>
<beans:property name="defaultEncoding" value="UTF-8"/>
</beans:bean>
</beans:beans>
error_message.properties
required=필수 항목입니다.
required.user.pwd=사용자 비밀번호는 필수 항목입니다.
invalidLength.id=아이디의 길이는 {0}~{1} 사이어야 합니다.
'프로젝트 > 중고헌터' 카테고리의 다른 글
중고헌터 - MyBatis로 DAO 작성 (0) | 2022.10.02 |
---|---|
중고헌터- MyBatis 설정 및 게시판 만들기 준비 (1) | 2022.10.01 |
중고헌터 - 데이터 변환과 검증 2 (0) | 2022.09.28 |
중고헌터 - 데이터 변환과 검증 (0) | 2022.09.28 |
중고헌터 - DAO(Data Access Object) 작성 (0) | 2022.09.27 |