스프링 프레임워크
servlet-context.xml (웹과 연관있음)
root-context.xml (웹과 독립됨)
스프링 부트
application.properties (하나로 환경설정 다 해결하자)
또는
application.yml ( 줄 간격 정확하게 해줘야한다. )
둘 다 똑같다. 스프링부트를 관리해주는 설정 파일이다.
대신 yml은 단계, 계층만 잘 적어주면 된다.
tomcat-embed-jasper
- Spring Boot에서는 JSP 사용을 권장하지 않는다.
Spring Boot에서 css, js, img 경로를 추가하는 방법
스프링에서는 xml에 직접 적어줬다면
스프링 부트는 spring-boot-starter-web에서 알아서 의존관계에의해서 해주므로 직접 쓸 필요가 없다.
: src/main/resources/static 안에 넣으면된다.
Chapter02MySQL
[ 전체 경로 정리 ]
Chapter02MySQL
src/main/java
com.example.demo
Chapter02MySqkApplication.java(main 메소드)
user.controller
UserController.java
user.service
UserService.java (인터페이스)
user.service.impl
UserServiceImpl.java
user.dao
UserDAO.java(인터페이스)
user.bean
UserDTO.java
src/main/resources
application.properties
mapper
userMapper.xml
static
css
writeForm.css
image
js
write.js
index.html
templates
user
writeForm.html
static은 정적이므로 요청할 수 있는 창을 띄워주는 역할이다.
뭔가를 서버로부터 동적으로 갱시하겠다는 templates (응답)
jsp 넣겠다하면 src - 리액트도 여기로 들어간다.
Chapter02MySQL
src/main/resources
static
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>*** 메인화면 ***</h3>
<hr/>
<p><a href="">등록</a>
<p><a href="">목록</a>
</body>
</html>
DB와 연관된 애들을 원하는데 우리는 설정한 적이 없으므로 에러가 떨어진다.
우리가 MYSQL을 깔아놨기 때문에 !!
Chapter02MySqlApplication.java
그러므로 지금 당장 DB를 안 쓸거다라는 말을 적어야한다.
exclude = DataSourceAutoConfiguration.class
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Chapter02MySqlApplication {
public static void main(String[] args) {
SpringApplication.run(Chapter02MySqlApplication.class, args);
}
}
이제 잘 실행이 된다 !!
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>*** 메인화면 ***</h3>
<hr/>
<p><a href="/user/writeForm">등록</a>
<p><a href="">목록</a>
</body>
</html>
/ 를 만나면 바로 컨트롤러로 가겠끔 컨트롤러를 하나 더 만들자 !!
Chapter02MySQL
src/main/java
com.example.demo
Chapter02MySqkApplication.java(main 메소드)
user.controller
UserController.java
src/main/resources
static
index.html
UserController.java
@Controller
package user.controller;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
}
컨트롤러 설정하러 가자 !!
Chapter02MySqlApplication.java
@ComponentScan(basePackages = {"user.controller"})
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {"user.controller"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Chapter02MySqlApplication {
public static void main(String[] args) {
SpringApplication.run(Chapter02MySqlApplication.class, args);
}
}
UserController.java
package user.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("user")
public class UserController {
@GetMapping(value="writeForm")
public String writeForm() {
return "user/writeForm";
}
}
writeForm.html
잘뜨는지부터 확인하자 !!!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
ㅋㅋㅋ
</body>
</html>
회원가입 폼
writeForm.css
.write-container {
display: flex;
justify-content: center;
align-items: center;
height: 60vh;
flex-direction: column;
}
.write-box {
border: 1px solid #ccc;
padding: 15px;
border-radius: 8px;
width: 300px;
box-shadow: 0px 4px 10px rgba(82, 80, 80, 0.1);
}
.write-title {
margin-bottom: 8px;
font-weight: bold;
}
.write-input {
width: 100%;
padding: 5px;
box-sizing: border-box;
border-radius: 4px;
border: 1px solid #ddd;
margin-bottom: 8px;
}
.write-button {
width: 100%;
padding: 8px;
border-radius: 4px;
border: none;
background-color: #FFDFF6;
color: black;
font-weight: bold;
cursor: pointer;
}
.write-button:hover {
background-color: #f5b7e3;
}
.div {
color: red;
font-size: 10pt;
margin-bottom: 8px;
}
table {
width: 100%;
margin-bottom: 15px;
}
td {
padding: 6px;
}
writeForm.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>회원가입</title>
<link rel="stylesheet" href="../css/writeForm.css">
</head>
<body>
<div class="write-container">
<a href="">
<img src="../image/free-icon-love-4096198.png" width="80px" height="80px" alt="heart"/>
</a>
<h2 class="board-list-title">회원가입</h2>
<form id="userWriteForm" class="write-box">
<table>
<tr>
<td><label class="write-title" for="name">이름</label></td>
<td><input type="text" class="write-input" name="name" id="name" /></td>
</tr>
<tr>
<td colspan="2">
<div id="nameDiv" class="div"></div>
</td>
</tr>
<tr>
<td><label class="write-title" for="id">아이디</label></td>
<td><input type="text" class="write-input" name="id" id="id" /></td>
</tr>
<tr>
<td colspan="2">
<div id="idDiv" class="div"></div>
</td>
</tr>
<tr>
<td><label class="write-title" for="pwd">비밀번호</label></td>
<td><input type="password" class="write-input" name="pwd" id="pwd" /></td>
</tr>
<tr>
<td colspan="2">
<div id="pwdDiv" class="div"></div>
</td>
</tr>
</table>
<button type="button" id="writeBtn" class="write-button">회원가입</button>
</form>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="../js/writeForm.js"></script>
</body>
</html>
아이디 중복
writeForm.js
먼저 아이디 중복검사부터 처리하자 !!
$(function () {
// 아이디 중복 검사
$('#id').on('focusout', function(){
$('#idDiv').empty();
let id = $('#id').val();
if (id === '') {
$('#idDiv').html('아이디를 입력하세요.').css('color', 'red');
} else {
$.ajax({
type: 'post',
url: '/user/getExistId',
data: {'id': id},
dataType: 'text',
success: function(data){
if (data == 'exist') {
$('#idDiv').html('이미 사용 중인 아이디입니다.').css('color', 'red');
} else {
$('#idDiv').html('사용가능한 아이디입니다.').css('color', 'green');
}
},
error: function(e){
console.log(e);
}
});
}
});
UserController.java
@PostMapping(value="getExistId")
@ResponseBody
public String getExistId(@RequestParam("id") String id) {
return userService.getExistId(id);
}
Chapter02MySQL
src/main/java
com.example.demo
Chapter02MySqkApplication.java(main 메소드)
user.controller
UserController.java
user.service
UserService.java (인터페이스)
user.service.impl
UserServiceImpl.java
src/main/resources
static
index.html
UserServiceImpl.java
@Service
package user.service.impl;
import org.springframework.stereotype.Service;
import user.service.UserService;
@Service
public class UserServiceImpl implements UserService {
}
Chapter02MySqlApplication.java
@ComponentScan(basePackages = {"user.controller", "user.service.impl"})
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {"user.controller", "user.service"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Chapter02MySqlApplication {
public static void main(String[] args) {
SpringApplication.run(Chapter02MySqlApplication.class, args);
}
}
UserController.java
생성자 injection으로 걸어보자 !!
public class UserController {
private UserService userService;
//Autowired 대신해서 생성자 injection
public UserController(UserService userService) {
this.userService = userService;
}
UserService.java
public String getExistId(String id);
package user.service;
public interface UserService {
public String getExistId(String id);
}
UserServiceImpl.java
package user.service.impl;
import org.springframework.stereotype.Service;
import user.service.UserService;
@Service
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
@Override
public String getExistId(String id) {
return null;
}
}
UserDAO 생성하러 가자 !!
Chapter02MySQL
src/main/java
com.example.demo
Chapter02MySqkApplication.java(main 메소드)
user.controller
UserController.java
user.service
UserService.java (인터페이스)
user.service.impl
UserServiceImpl.java
user.dao
UserDAO.java(인터페이스)
src/main/resources
static
index.html
UserServiceImpl.java
@Autowired
private UserDAO userDAO;
package user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import user.dao.UserDAO;
import user.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public String getExistId(String id) {
return null;
}
}
Chapter02MySqlApplication.java
@ComponentScan(basePackages = {"user.controller", "user.service.impl", "user.dao"})
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {"user.controller", "user.service", "user.dao"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Chapter02MySqlApplication {
public static void main(String[] args) {
SpringApplication.run(Chapter02MySqlApplication.class, args);
}
}
UserDAO.java
@Mapper
package user.dao;
import org.apache.ibatis.annotations.Mapper;
import user.bean.UserDTO;
@Mapper
public interface UserDAO {
public UserDTO getExistId(String id);
}
원래는 SpringConfiguration에서 mapper로 쓴다하고
@MapperScan("user.dao") 이렇게 알려줬었다.
이제는 main메서드에다가 적어줘야한다.
Chapter02MySqlApplication.java
@MapperScan("user.dao")
@EnableTransactionManagement
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@ComponentScan(basePackages = {"user.controller", "user.service", "user.dao"})
@MapperScan("user.dao")
@EnableTransactionManagement
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Chapter02MySqlApplication {
public static void main(String[] args) {
SpringApplication.run(Chapter02MySqlApplication.class, args);
}
}
UserServiceImpl.java
@Transactional
package user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import user.dao.UserDAO;
import user.service.UserService;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public String getExistId(String id) {
return null;
}
}
원래는 db.properties에 했던거를 이제는 application.properties에 해준다.
application.properties
server.port=8080 -- 그냥 해봄
spring.application.name=Chapter02MySQL
# Server Port
server.port=8080
# MySQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Seoul
spring.datasource.username=root
spring.datasource.password=1234
#MyBatis
#mybatis.config-location=classpath:spring/mybatis-config.xml
#mybatis.mapper-locations=classpath:mapper/userMapper.xml
#mybatis.mapper-locations=classpath:mapper/**/*Mapper.xml
mybatis.mapper-locations=classpath:mapper/**/*.xml
mybatis.type-aliases-package=user.bean
Chapter02MySQL
src/main/java
com.example.demo
Chapter02MySqkApplication.java(main 메소드)
user.controller
UserController.java
user.service
UserService.java (인터페이스)
user.service.impl
UserServiceImpl.java
user.dao
UserDAO.java(인터페이스)
user.bean
UserDTO.java
src/main/resources
mapper
userMapper.xml
static
css
writeForm.css
image
js
write.js
index.html
templates
user
writeForm.html
UserDTO.java
package user.bean;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
public class UserDTO {
private String name;
private String id;
private String pwd;
}
userMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- <mapper namespace="userSQL"> -->
<mapper namespace="user.dao.UserDAO">
<!-- 중복 아이디 체크 -->
<select id="getExistId" parameterType="String" resultType="userDTO">
SELECT * FROM usertable WHERE id = #{id};
</select>
Chapter02MySqlApplication.java
//@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) -- 아까 막아둔거 풀기 !
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@ComponentScan(basePackages = {"user.controller", "user.service.impl", "user.dao"})
@MapperScan("user.dao")
@EnableTransactionManagement
//@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@SpringBootApplication
public class Chapter02MySqlApplication {
public static void main(String[] args) {
SpringApplication.run(Chapter02MySqlApplication.class, args);
}
}
UserServiceImpl.java
package user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import user.bean.UserDTO;
import user.dao.UserDAO;
import user.service.UserService;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public String getExistId(String id) {
UserDTO userDTO = userDAO.getExistId(id);
System.out.println(userDTO);
if(userDTO == null)
return "non_exist";
else
return "exist";
}
}
Chapter02MySQL
src/main/java
com.example.demo
Chapter02MySqkApplication.java(main 메소드)
user.controller
UserController.java
user.service
UserService.java (인터페이스)
user.service.impl
UserServiceImpl.java
user.dao
UserDAO.java(인터페이스)
user.bean
UserDTO.java
src/main/resources
application.properties -- 잠깐 보관해두기 !! 그리고 삭제 !!!!
application.yml -- 생성하기
mapper
userMapper.xml
static
css
writeForm.css
image
js
write.js
index.html
templates
user
writeForm.html
application.yml
YAML 파일은 들여쓰기에 공백(스페이스)만 허용하고, 탭은 사용할 수 없다.
# Server Port
server:
port: 8080
# MySQL
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Seoul
username: root
password: 1234
#MyBatis
mybatis:
mapper-locations: classpath:mapper/**/*.xml
type-aliases-package: user.bean
다시 실행 잘되는거 확인하면 똑같이 잘된다 !!!
회원가입
writeForm.js
// 회원가입 등록
$('#writeBtn').on('click', function(event){
event.preventDefault();
$('#nameDiv').empty();
$('#idDiv').empty();
$('#pwdDiv').empty();
let isValid = true;
// 이름 검증
if($('#name').val().trim() == ''){
$('#nameDiv').html('이름을 입력하세요.').css('color', 'red');
$('#name').focus();
isValid = false;
}
// 아이디 검증
if($('#id').val().trim() == ''){
$('#idDiv').html('아이디를 입력하세요.').css('color', 'red');
$('#id').focus();
isValid = false;
}
// 비밀번호 검증
if($('#pwd').val().trim() == ''){
$('#pwdDiv').html('비밀번호를 입력하세요.').css('color', 'red');
$('#pwd').focus();
isValid = false;
}
if(isValid){
$.ajax({
type: 'post',
url: '/user/write',
data: $('#userWriteForm').serialize(),
success: function(){
alert('회원가입이 완료되었습니다.');
//location.href = '/user/list';
},
error: function(e){
console.log(e);
}
});
}
});
UserController.java
@PostMapping(value="write")
@ResponseBody
public void write(@ModelAttribute UserDTO userDTO) {
return userService.write(userDTO);
}
UserService.java
public void write(UserDTO userDTO);
package user.service;
import user.bean.UserDTO;
public interface UserService {
public String getExistId(String id);
public void write(UserDTO userDTO);
}
UserServiceImpl.java
@Override
public void write(UserDTO userDTO) {
userDAO.write(userDTO);
}
UserDAO.java
public void write(UserDTO userDTO);
package user.dao;
import org.apache.ibatis.annotations.Mapper;
import user.bean.UserDTO;
@Mapper
public interface UserDAO {
public UserDTO getExistId(String id);
public void write(UserDTO userDTO);
}
userMapper.xml
<insert id="write" parameterType="userDTO">
INSERT INTO usertable (name, id, pwd)
VALUES (#{name}, #{id}, #{pwd});
</insert>
회원가입 잘 된다 !! DB에도 잘들어간다 !!!
타임리프 형식으로 바꾸기
writeForm.html
writeForm.js 주석걸기 !!
ajax 안 쓰겠다는 것이다.
<!-- <script src="../js/writeForm.js"></script> -->
<script type="text/javascript">
$(function () {
// 회원가입 등록
$('#writeBtn').on('click', function(event){
event.preventDefault();
$('#nameDiv').empty();
$('#idDiv').empty();
$('#pwdDiv').empty();
let isValid = true;
// 이름 검증
if($('#name').val().trim() == ''){
$('#nameDiv').html('이름을 입력하세요.').css('color', 'red');
$('#name').focus();
isValid = false;
}
// 아이디 검증
if($('#id').val().trim() == ''){
$('#idDiv').html('아이디를 입력하세요.').css('color', 'red');
$('#id').focus();
isValid = false;
}
// 비밀번호 검증
if($('#pwd').val().trim() == ''){
$('#pwdDiv').html('비밀번호를 입력하세요.').css('color', 'red');
$('#pwd').focus();
isValid = false;
}
if(isValid){
$('#userWriteForm').submit(); //<form /> 안에 있는 action을 통해서 페이지 이동
}
});
});
</script>
submit을 걸었기 때문에 돌아오라는게 아니라 그냥 가버려라 !! 이다.
<form /> 안에 있는 action을 통해서 페이지 이동
<!-- <form id="userWriteForm" class="write-box"> -->
<form method="post" id="userWriteForm" class="write-box" action="/user/write2">
form 태그에 action 걸어주기 !!
<form method="post" id="userWriteForm" class="write-box" th:action="@{/user/write2}">
타임리프 형식으로 바꾸자 !!
UserController.java
@PostMapping(value="write2")
public String write2(@ModelAttribute UserDTO userDTO) {
System.out.println(userDTO);
userService.write(userDTO);
return "user/write";
}
write.html (templates.user 패키지에 생성)
확인차 일단 저렇게 적어보기 !
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
회원가입 완료
</body>
</html>
write.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<script th:inline="javascript">
/*<![CDATA][*/
window.onload = function(){
alert("회원가입 완료");
location.href = "/user/list";
}
/*]]>*/
</script>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>*** 메인화면 ***</h3>
<hr/>
<p><a href="/user/writeForm">등록</a>
<p><a href="/user/list">목록</a>
</body>
</html>
UserController.java
@GetMapping(value = "list")
public List<UserDTO> list(){
System.out.println("list");
return null;
}
list 찍히는지만 확인 !!
회원 목록 출력하기
UserController.java
@GetMapping(value = "list")
public String list(Model model){
//System.out.println("list");
List<UserDTO> list = userService.list();
model.addAttribute("list", list);
return "user/list";
}
UserService.java
public List<UserDTO> list();
package user.service;
import java.util.List;
import user.bean.UserDTO;
public interface UserService {
public String getExistId(String id);
public void write(UserDTO userDTO);
public List<UserDTO> list();
}
UserServiceImpl.java
@Override
public List<UserDTO> list() {
return userDAO.list();
}
UserDAO.java
public List<UserDTO> list();
package user.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import user.bean.UserDTO;
@Mapper
public interface UserDAO {
public UserDTO getExistId(String id);
public void write(UserDTO userDTO);
public List<UserDTO> list();
}
userMapper.xml
<select id="list" resultType="userDTO">
SELECT * FROM usertable;
</select>
list.html
타임리프로 뿌려주기 !!
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>회원 목록</title>
<link rel="stylesheet" href="../css/list.css">
</head>
<body>
<div class="list-container">
<h2 class="list-title">회원 목록</h2>
<table class="list-table">
<thead>
<tr>
<th>이름</th>
<th>아이디</th>
<th>비밀번호</th>
</tr>
</thead>
<tbody>
<tr th:each="dto : ${list}">
<td th:text="${dto.name}">name</td>
<td th:text="${dto.id}">id</td>
<td th:text="${dto.pwd}">pwd</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
list.css
@charset "UTF-8";
.list-container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 60vh;
padding: 20px;
}
.list-title {
font-size: 1.5em;
font-weight: bold;
color: #333;
margin-bottom: 20px;
}
.list-table {
width: 80%;
border-collapse: collapse;
box-shadow: 0px 4px 10px rgba(82, 80, 80, 0.1);
}
.list-table th, .list-table td {
border: 1px solid #ddd;
padding: 10px;
text-align: center;
}
.list-table th {
background-color: #FFDFF6;
font-weight: bold;
color: #333;
}
.list-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.list-table tr:hover {
background-color: #FFF1FE;
}
회원정보 수정폼
list.html
아이디에 a 태그
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>회원 목록</title>
<link rel="stylesheet" href="../css/list.css">
</head>
<body>
<div class="list-container">
<a href="/">
<img src="../image/free-icon-love-4096198.png" width="80px" height="80px" alt="heart"/>
</a>
<h2 class="list-title">회원 목록</h2>
<table class="list-table">
<thead>
<tr>
<th>이름</th>
<th>아이디</th>
<th>비밀번호</th>
</tr>
</thead>
<tbody>
<tr th:each="dto : ${list}">
<td th:text="${dto.name}">name</td>
<td>
<a th:href="@{/user/detail/{id}(id=${dto.id})}" th:text="${dto.id}">id</a>
</td>
<td th:text="${dto.pwd}">pwd</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
UserController.java
@GetMapping(value = "detail/{id}")
public String detail(@PathVariable("id") String id, Model model){
System.out.println(id);
UserDTO userDTO = userService.getUserById(id);
model.addAttribute("dto", userDTO);
return "user/detail";
}
detail/html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>회원 정보</title>
<link rel="stylesheet" href="/css/detail.css">
</head>
<body>
<div class="detail-container">
<a href="/">
<img src="/image/free-icon-love-4096198.png" width="80px" height="80px" alt="heart"/>
</a>
<h2 class="detail-title">회원 정보</h2>
<div class="detail-box">
<table class="detail-table">
<tr>
<td class="detail-label">이름</td>
<td th:text="${dto.name}">홍길동</td>
</tr>
<tr>
<td class="detail-label">아이디</td>
<td th:text="${dto.id}">hong123</td>
</tr>
<tr>
<td class="detail-label">비밀번호</td>
<td th:text="${dto.pwd}">******</td>
</tr>
</table>
<div class="button-container">
<a th:href="@{/user/edit/{id}(id=${dto.id})}" class="detail-button edit-button">수정</a>
<a th:href="@{/user/delete/{id}(id=${dto.id})}" class="detail-button delete-button">삭제</a>
</div>
</div>
</div>
</body>
</html>
회원가입 수정하기
UserController.java
@GetMapping("edit/{id}")
public String edit(@PathVariable("id") String id, Model model) {
UserDTO userDTO = userService.getUserById(id);
model.addAttribute("dto", userDTO);
return "user/edit";
}
edit.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>회원 수정</title>
<link rel="stylesheet" href="/css/detail.css">
</head>
<body>
<div class="detail-container">
<a href="/">
<img src="/image/free-icon-love-4096198.png" width="80px" height="80px" alt="heart"/>
</a>
<h2 class="detail-title">회원 정보 수정</h2>
<div class="detail-box">
<form method="post" id="userUpdateForm" th:action="@{/user/update}">
<table class="detail-table">
<tr>
<td class="detail-label">이름</td>
<td><input type="text" th:value="${dto.name}" name="name" id="name" required /></td>
</tr>
<tr>
<td colspan="2">
<div id="nameDiv" class="div"></div>
</td>
</tr>
<tr>
<td class="detail-label">아이디</td>
<td><input type="text" th:value="${dto.id}" name="id" readonly id="id" /></td>
</tr>
<tr>
<td class="detail-label">비밀번호</td>
<td><input type="password" th:value="${dto.pwd}" name="pwd" id="pwd" required /></td>
</tr>
<tr>
<td colspan="2">
<div id="pwdDiv" class="div"></div>
</td>
</tr>
</table>
<div class="button-container">
<button type="submit" id="updateBtn" class="detail-button edit-button" style="width: 60%;">수정 완료</button>
<a href="javascript:history.back();" class="detail-button delete-button">취소</a>
</div>
</form>
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
// 회원 수정
$('#updateBtn').on('click', function(event){
event.preventDefault();
$('#nameDiv').empty();
$('#pwdDiv').empty();
let isValid = true;
// 이름 검증
if($('#name').val().trim() == ''){
$('#nameDiv').html('이름을 입력하세요.').css('color', 'red');
$('#name').focus();
isValid = false;
}
// 비밀번호 검증
if($('#pwd').val().trim() == ''){
$('#pwdDiv').html('비밀번호를 입력하세요.').css('color', 'red');
$('#pwd').focus();
isValid = false;
}
if(isValid){
$('#userUpdateForm').submit();
}
});
});
</script>
</body>
</html>
UserController.java
@PostMapping("update")
public String update(@ModelAttribute UserDTO userDTO) {
userService.update(userDTO);
return "redirect:/user/detail/" + userDTO.getId();
}
UserService.java
public void update(UserDTO userDTO);
package user.service;
import java.util.List;
import user.bean.UserDTO;
public interface UserService {
public String getExistId(String id);
public void write(UserDTO userDTO);
public List<UserDTO> list();
public UserDTO getUserById(String id);
public void delete(String id);
public void update(UserDTO userDTO);
}
UserServiceImpl.java
@Override
public void update(UserDTO userDTO) {
userDAO.update(userDTO);
}
UserDAO.java
public void update(UserDTO userDTO);
package user.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import user.bean.UserDTO;
@Mapper
public interface UserDAO {
public UserDTO getExistId(String id);
public void write(UserDTO userDTO);
public List<UserDTO> list();
public UserDTO getUserById(String id);
public void delete(String id);
public void update(UserDTO userDTO);
}
userMapper.xml
<update id="update" parameterType="userDTO">
UPDATE usertable
SET name = #{name}, pwd = #{pwd}
WHERE id = #{id};
</update>
회원정보 삭제
UserController.java
@GetMapping(value = "delete/{id}")
public String delete(@PathVariable("id") String id) {
userService.delete(id);
return "redirect:/user/list";
}
UserService.java
public void delete(String id);
package user.service;
import java.util.List;
import user.bean.UserDTO;
public interface UserService {
public String getExistId(String id);
public void write(UserDTO userDTO);
public List<UserDTO> list();
public UserDTO getUserById(String id);
public void delete(String id);
public void update(UserDTO userDTO);
}
UserServiceImpl.java
@Override
public void delete(String id) {
userDAO.delete(id);
}
UserDAO.java
public void update(UserDTO userDTO);
package user.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import user.bean.UserDTO;
@Mapper
public interface UserDAO {
public UserDTO getExistId(String id);
public void write(UserDTO userDTO);
public List<UserDTO> list();
public UserDTO getUserById(String id);
public void delete(String id);
public void update(UserDTO userDTO);
}
userMapper.xml
<delete id="delete" parameterType="String">
DELETE FROM usertable WHERE id = #{id};
</delete>
'Spring Boot' 카테고리의 다른 글
DAY 89 - JPA (2024.11.12) (1) | 2024.11.12 |
---|---|
DAY 88 - JPA (2024.11.11) (0) | 2024.11.12 |
DAY 85 - Thymeleaf (2024.11.06) (0) | 2024.11.06 |
DAY 84 - Thymeleaf (2024.11.05) (0) | 2024.11.06 |
DAY 83 - Spring Boot / HOMEWORK (2024.11.04) (1) | 2024.11.04 |