- 회원가입 등록
📌 UserController.java 내용 추가
package controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import logic.ShopService;
import logic.User;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private ShopService service;
@GetMapping("*") // * : 그 외 모든 get 방식 요청
public ModelAndView getUser() {
ModelAndView mav = new ModelAndView();
mav.addObject(new User());
return mav;
}
**@PostMapping("join")
public ModelAndView join (@Valid User user, BindingResult bresult) {
ModelAndView mav = new ModelAndView();
if(bresult.hasErrors()) { //입력값 오류 발생
mav.getModel().putAll(bresult.getModel());
//전반적인 오류코드 등록
bresult.reject("error.input.user");
return mav;
}
//db에 회원정보 등록
try {
service.userInsert(user);
mav.addObject("user", user);
} catch(DataIntegrityViolationException e) {
e.printStackTrace();
bresult.reject("error.duplicate.user");
mav.getModel().putAll(bresult.getModel());
return mav;
}
mav.setViewName("redirect:login");
return mav;
}**
}
📌 ShopService.java 내용 추가
package logic;
import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import dao.ItemDao;
**import dao.UserDao;**
/*
* @Component : 해당 클래스를 객체화
* - Service 기능 : Controller 와 Model사이의 중간 역할의 클래스
*/
@Service //@Component + Service 기능
public class ShopService {
@Autowired //현재 내 컨테이너(객체)들 중에 itemDao 객체를 주입.
private ItemDao itemDao;
**@Autowired
private UserDao userDao;**
public List<Item> itemList() {
return itemDao.list();
}
public Item getItem(Integer id) {
return itemDao.getItem(id);
}
//db에 내용 저장. 파일 업로드.
//item : 저장 정보. 입력된 파라미터 값 + 업로드 된 파일의 내용
public void itemCreate(@Valid Item item, HttpServletRequest request) {
//item.getPicture() : 업로드 된 파일의 내용
if(item.getPicture() != null && !item.getPicture().isEmpty()) { //업로드 된 파일이 있는 경우
String uploadPath = request.getServletContext().getRealPath("/") + "img/"; //업로드 위치
uploadFileCreate(item.getPicture(), uploadPath); //업로드 구현 완료
item.setPictureUrl(item.getPicture().getOriginalFilename()); //파일의 이름
}
//maxid : item테이블 중 최대 id 값
int maxid = itemDao.maxId();
item.setId(maxid+1);
itemDao.insert(item);
}
private void uploadFileCreate(MultipartFile file, String uploadPath) {
//uploadPath : 파일이 업로드 되는 폴더
String orgFile = file.getOriginalFilename(); //업로드 된 파일의 이름
File fpath = new File(uploadPath);
if(!fpath.exists()) fpath.mkdirs(); //업로드 폴더를 생성(없으면)
try {
//파일의 내용 => uploadPath + orgFile 로 파일 저장
file.transferTo(new File(uploadPath + orgFile)); //파일업로드
} catch(Exception e) {
e.printStackTrace();
}
}
public void itemUpdate(Item item, HttpServletRequest request) {
//item.getPicture() : 업로드 된 파일의 내용
if(item.getPicture() != null && !item.getPicture().isEmpty()) { //업로드 된 파일이 있는 경우
String uploadPath = request.getServletContext().getRealPath("/") + "img/"; //업로드 위치
uploadFileCreate(item.getPicture(), uploadPath); //파일 업로드 : 업로드된 내용을 서버에 파일로 저장
item.setPictureUrl(item.getPicture().getOriginalFilename()); //파일의 이름을 db에 등록하기 위해 설정
}
itemDao.update(item);
}
public void itemDelete(Integer id) {
itemDao.delete(id);
}
**public void userInsert(@Valid User user) {
userDao.insert(user);
}**
}
📌 UserDao.java 생성
package dao;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import logic.User;
@Repository
public class UserDao {
private NamedParameterJdbcTemplate template;
private Map<String, Object> param = new HashMap<>();
private RowMapper<User> mapper = new BeanPropertyRowMapper<>(User.class);
@Autowired
public void setDataSource(DataSource dataSource) {
template = new NamedParameterJdbcTemplate(dataSource);
}
public void insert(@Valid User user) {
SqlParameterSource param = new BeanPropertySqlParameterSource(user);
String sql = "insert into useraccount"
+ " (userid, password, username, phoneno, postcode,"
+"address, email, birthday)"
+ " values(:userid, :password, :username, :phoneno, :postcode,"
+ " :address, :email, :birthday)";
template.update(sql, param);
}
}
- 사용자 로그인 화면
📌 login.jsp 생성
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%-- /WEB-INF/view/user/login.jsp --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>로그인화면</title>
<script type="text/javascript">
function win_open(page) {
var op = "width=500, height=350, left=50,top=150";
open(page,"",op);
}
</script>
</head><body>
<h2>사용자 로그인</h2>
<form:form modelAttribute="user" method="post" action="login" name="loginform">
<input type="hidden" name="username" value="유효성검증을위한 파라미터" >
<input type="hidden" name="email" value="valid@aaa.bbb" >
<spring:hasBindErrors name="user">
<font color="red"><c:forEach items="${errors.globalErrors}" var="error">
<spring:message code="${error.code}" />
</c:forEach></font></spring:hasBindErrors>
<table border="1" style="border-collapse: collapse;" class="w3-table">
<tr height="40px"><td>아이디</td><td><form:input path="userid" class="w3-input"/>
<font color="red"><form:errors path="userid" /></font></td></tr>
<tr height="40px"><td>비밀번호</td><td><form:password path="password" class="w3-input"/>
<font color="red"><form:errors path="password" /></font></td></tr>
<tr height="40px"><td colspan="2" class="w3-center">
<button type="submit" class="w3-button w3-blue">로그인</button>
<button type="button" onclick="location.href='join'" class="w3-button w3-blue">회원가입</button>
<button type="button" onclick="win_open('idsearch')" class="w3-button w3-blue">아이디찾기</button>
<button type="button" onclick="win_open('pwsearch')" class="w3-button w3-blue">비밀번호찾기</button>
</td></tr></table>
</form:form></body></html>
'수업(국비지원) > Spring' 카테고리의 다른 글
| [Spring] (MVC 2) AOP설정 - 로그인,로그아웃 알림 (0) | 2023.04.21 |
|---|---|
| [Spring] (MVC 2) 로그인, 로그아웃(UserController, ShopService, UserDao) (0) | 2023.04.21 |
| [Spring] (MVC 2) 사용자 등록(join, User, UserController, ) - 유효성 검사 (0) | 2023.04.21 |
| [Spring] (MVC 2) sitemesh 설정(pom.xml, SiteMeshFilter, kiclayout) (0) | 2023.04.20 |
| [Spring] (MVC 2) 장바구니 상품 삭제(CartController), 장바구니 구현(CartController) (0) | 2023.04.20 |