본문 바로가기

프로그래밍/Spring Boot

Spring Boot_스프링 기본 파싱 전략

스프링 기본 파싱 전략

반드시 기억할 것은 HTML form 태그는 기본적으로 방식을 get, post만 지원한다.

→ 스프링부트 컨트롤러는 key = value 데이터를 자동으로 파싱해서 변수에 담아준다.

 

  1. form 태그 METHOD → get 처리
    특장 : body로 데이터를 담아 보내지 않음.

  2. form에 대한 한계 GET, POST만 가능
    REST FULL API 활용 못함. 

    PUT, DELETE는 form 말고 ajax로 restfull 방식 변경해서 처리하기.

 

temp.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<%@ 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>
<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script
    src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script
    src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>form 테스트</h1>
        
        <form action="/temp/join2" method="post">
            <div class="form-group">
                <label for="">username : </label>
                <input type="text" name="username" class="form-control" value="항1">
            </div>
            <div class="form-group">
                <label for="" >password : </label>
                <input type="password" name="password" class="form-control" value="1234">
            </div>
            <div class="form-group">
                <label for="">email : </label>
                <input type="text" name="email" class="form-control" value="a@naver.com">
            </div>
            <button id="join--submit" class="btn btn-primary" >회원가입</button>
        </form>
    </div>
</body>
</html>
cs

 

 

UserControllerTest.java

스프링 부트 컨트롤러는 key=value 데이터를 자동으로 파싱해서 변수에 담아준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Controller 
public class UserControllerTest {
 
    // 1. key=value
    @PostMapping("/temp/join")
    public String join(String username, String password, String email) {
        User reqUser = new User();
        reqUser.setUsername(username);
        reqUser.setPassword(password);
        reqUser.setEmail(email);
        
        return reqUser;
    }
    
    // 2. Object Mapper를 통해서 바로 객체로 파싱하기 
    // Object Mapper는 Dto를 파싱해준다.
    @PostMapping("/temp/join2")
    @ResponseBody // 페이지 리턴이 아니라 데이터를 리턴하라 명령
    public String join(@RequestBody User reqUser) { // @RequestBody : http 바디에서 값을 가져와 파싱해달라고 알려줌
        System.out.println(reqUser.toString());
        userRepository.save(reqUser);
        
        return reqUser;
    }
}
cs

 

 

ajax 통신

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<%@ 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>
<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script
    src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script
    src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>form 태스트</h1>
        
        <form action="/temp/join2" method="post">
            <div class="form-group">
                <label for="username">username : </label>
                <input type="text" name="username" id="username" class="form-control" value="항1">
            </div>
            <div class="form-group">
                <label for="password" >password : </label>
                <input type="password" name="password" id="password" class="form-control" value="1234">
            </div>
            <div class="form-group">
                <label for="email">email : </label>
                <input type="text" name="email" class="form-control" id="email" value="a@naver.com">
            </div>
        </form>
                
        <button id="join--submit" class="btn btn-primary" >회원가입</button>
    </div>
    <script type="text/javascript">
        $(document).ready(function() {
            
            $("#join--submit").on("click", () => {
                // MIME TYPE -> application/json 
                // js --> json 문자열로 변경하는 방법 
                // object --> JSON 문자열로 변경 
                
                let data = {
                    username: $("#username").val(),
                    password: $("#password").val(), 
                    email: $("#email").val()
                };
                //console.log(JSON.stringify(data));
                $.ajax({
                    type: 'POST'
                    url : '/temp/join2',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify(data),
                    dataType: 'json'
                }).done(function(response) {
                    console.log(response);
                    console.log(typeof response);
                    alert("회원가입성공");
                    location.href = "/temp/index";
                }).fail(function(error) {
                    alert("서버오류");
                }); 
            });
        });
    </script>
</body>
</html>
cs

→ JSON.stringify() : JavaScript 값이나 객체를 JSON 문자열로 바꿔줌