본문 바로가기

개발/JavaScript

[Ajax] #08. MVC Model 2 :: Servlet + Ajax 적용한 간단한 예제 (2) gson 활용

 

이 전 포스팅들에서 했던 것은 Json으로 해서 Write로 전송해주는 것이었다.

이번 포스팅에서는 lib 폴더에 gson을 넣어주고 이를 활용한 예제이다.

 

 

#index.html

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
<br>
<input type="text" id="id">
<button type="button">click</button>
 
<script type="text/javascript">
 
$(function () {
    $("button").click(function () {
        
        $.ajax({
            
            /* 전송을 해주는 부분 */
            
            url:"./hello",                         // 현재 경로 표시
            type:"post",
            datatype:"json",
            data:{ id:$("#id").val(), pwd:"123" },
            
            /* 전송 하고나서 온 다음의 일 */
            success:function(json){
            //    alert("success");    
                alert(json);    
 
            },
            error:function(){
                alert("error");
                
            }
            
        });
        
    });
});
 
</script>
 
</body>
</html>
cs

 

#HelloServlet.java

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
package hello;
 
import java.io.IOException;
 
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 com.google.gson.Gson;
 
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        String str = "hello";
        
        // google json 
        String gson = new Gson().toJson(str);
        
        resp.getWriter().write(gson);
        
    }
 
}
 
cs

● gson = google json 을 적용시킨다.

 

 

 

 

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
package hello;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
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 com.google.gson.Gson;
 
import dto.CustUserDto;
 
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
        // 확인용
        String str = "hello";
        
        // google json 
        String gson = new Gson().toJson(str);
        
        resp.getWriter().write(gson);
        */
        
        List<CustUserDto> list = new ArrayList<CustUserDto>();
        list.add(new CustUserDto("zxc""홍길동""대전시"));
        list.add(new CustUserDto("hjk""향단이""여수시"));
        
        
        resp.setContentType("application/json");             // json 변환
        resp.setCharacterEncoding("UTF-8");                 // 한글로 정상 출력하기 위함
        
        // gson-2.8.5.jar 추가할 것
        String gson = new Gson().toJson(list);
        
        resp.getWriter().write(gson);                                // return해 주는 함수
        
    }
 
}
 
cs

 


[ Code All ]

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
<br>
<input type="text" id="id">
<button type="button">click</button>
 
<script type="text/javascript">
 
$(function () {
    $("button").click(function () {
        
        $.ajax({
            
            /* 전송을 해주는 부분 */
            
            url:"./hello",                                 // 현재 경로 표시
            type:"post",
            datatype:"json",
            data:{ id:$("#id").val(), pwd:"123" },
            
            /* 전송 하고나서 온 다음의 일 */
            success:function(json){
            //    alert("success");    
            //    alert(json);    
            //    alert(json[0].id);
            //    alert(json[0].name);
            //    alert(json[0].address);
            
                $.each(json, function (i, val) {
                    $("#demo").append("i:" + i + " id:" + val.id 
                                                    + " name: " + val.name
                                                    + " address: " + val.address + "<br>" );                    
                });
            
            
            },
            error:function(){
                alert("error");
                
            }
            
        });
 
    });
});
 
</script>
 
</body>
</html>
cs
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
package hello;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
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 com.google.gson.Gson;
 
import dto.CustUserDto;
 
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
        // 확인용
        String str = "hello";
        
        // google json 
        String gson = new Gson().toJson(str);
        
        resp.getWriter().write(gson);
        */
        
        List<CustUserDto> list = new ArrayList<CustUserDto>();
        list.add(new CustUserDto("zxc""홍길동""대전시"));
        list.add(new CustUserDto("hjk""향단이""여수시"));
        
        
        resp.setContentType("application/json");             // json 변환
        resp.setCharacterEncoding("UTF-8");                 // 한글로 정상 출력하기 위함
        
        // gson-2.8.5.jar 추가할 것
        String gson = new Gson().toJson(list);
        
        resp.getWriter().write(gson);                                // return해 주는 함수
 
    }
 
}
 
cs

 

#CustUserDto.java

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
package dto;
 
import java.io.Serializable;
/*
CREATE TABLE CUSTUSER(
    ID VARCHAR2(50) PRIMARY KEY,
    NAME VARCHAR2(50) NOT NULL,
    ADDRESS VARCHAR2(50)
);
*/
public class CustUserDto implements Serializable {
 
    private String id;
    private String name;
    private String address;
    
    public CustUserDto() {
    }
 
    public CustUserDto(String id, String nameString address) {
        super();
        this.id = id;
        this.name = name;
        this.address = address;
    }
    
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
    @Override
    public String toString() {
        return "CustUserDto [id=" + id + ", name=" + name + ", address=" + address + "]";
    }
    
}
 
cs