본문 바로가기

개발/JavaScript

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

MODEL 2는, 어떤 것이든 마찬가지겠지만 앞서 해보았던 MODEL 1보다는 절차가 조금 더 많다.

우선 lib에 들어갈 jar 파일들이 필요하다. 

 

 

※ 해당 포스팅 코드의 핵심 : Servlet에서 map을 json Object로 바꿔준 후 데이터를 날려주어야 한다.

 

#CustUserServlet.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package cust;
 
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
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 dto.CustUserDto;
import net.sf.json.JSONObject;
 
@WebServlet("/custuser")
public class CustUserServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("CustUserServlet doGet");
        String id = req.getParameter("id");
        String pwd = req.getParameter("pwd");
        System.out.print(id + " " + pwd);
        
 
        // 전송 Data         
        // (1)
        JSONObject jobj = new JSONObject();
//        jobj.put("str", "Hello");         // String 전송
        
        // (2)
 
        /*
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title", "사과");
        
        // (3)
        jobj.put("map", map);             // HashMap 전송
        */
        
        
        // (4) 
        // Dto 를 불러온다. > HashMap에 심어준다
        List<CustUserDto> list = new ArrayList<CustUserDto>();
        list.add(new CustUserDto("aaa""홍길동""서울시"));
        list.add(new CustUserDto("bbb""일지매""부산시"));
        
        HashMap<StringObject> map = new HashMap<StringObject>();
        map.put("custlist", list);
        
        jobj.put("map", map); 
        // 데이터들을 묶어놓은 리스트를 map에 넣어주고, map에 대한 데이터를 똑같이 넘겨준다. 
 
        
        // 맵 통째로 날아가는 것
        resp.setContentType("application/x-json; charset=UTF-8");
        resp.getWriter().print(jobj);
        
        
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("CustUserServlet doPost");
    }
 
}
 
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

 

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
49
50
51
<!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:"custuser",
            type:"get",
            datatype:"json",
    //        data:"id=abc&pwd=123",                 // get, post 방식 비교
    //        data:{ id:"abc", pwd:123 }
            data:{ id:$("#id").val(), pwd:"123" },
            
            success:function(json){
    //            alert("success");
    //            alert( json.str );
    //            alert( json.map.title );          // 사과
        
                let custlist = json.map.custlist;   // map을 이렇게 넘겨 받는다
                alert( custlist[0].id );    
                alert( custlist[0].name );    
                    
            },
            error:function(){
                alert("error");
                
            }
            
        });
        
    });
});
 
</script>
 
</body>
</html>
cs