index.jsp파일에서 HelloServlet.java(Servlet)로 데이터를 요청하면, 서블릿에서 다시 JSP로 데이터를 json형태로 보내주는 것을 구현해보자.

즉, web에서 jsp는 client 측이고, servlet은 server 측이다.

jsp에서는 버튼을 누르면, $.ajax() 메서드를 통해 servlet으로부터 데이터를 받게 되고,

servlet에서 여러가지 type의 데이터를 json 형태로 바꿔 보내주도록 한다.

 

0. jsp에서 servlet으로 데이터 전송하기

먼저, servlet에서 getParameter()를 이용해 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
package ajax3;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
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.Human;
import net.sf.json.JSONObject;
 
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet doGet()");
    
        String id = req.getParameter("id");
        String pw = req.getParameter("pw");
        
        System.out.println("id: " + id + " pw: " + pw); // 서버가 클라이언트로부터 데이터를 받은 상태
        
    }    
    
}
 
cs

jsp 파일(index.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
39
40
41
42
43
44
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
//             data: "id=abc&pw=123",
            data:{id:"abc", pw:"123"}, // json 방식으로 서블릿에 보낼 데이터
            success:function(data){
                alert("success");
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

그 결과 다음과 같은 결과가 콘솔창에 나타난다.

이제 총 4가지의 타입의 객체를 서블릿에서 jsp로 보내주는 코드를 작성해본다.

위와 중복되는 부분은 제외하고 수정된 부분만 비교해보면

1. String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        String str = "안녕하세요";
        
        JSONObject jObj = new JSONObject();
        jObj.put("str", str); // key, value
        
        resp.setContentType("application/x-json; charset=utf-8");
        resp.getWriter().print(jObj);
        
        
    }    
    
}
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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
            success:function(data){
                alert(data); // [object Object]
                alert(JSON.stringify(data)); // {"str":"안녕하세요"}
                alert(data.str); // 안녕하세요
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

 

2. Object(Human.java)

Human.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
package dto;
 
import java.io.Serializable;
 
public class Human implements Serializable{
    
    private String name;
    private int age;
    
    public Human() {
    }
 
    public Human(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    
}
 
cs

Human 객체를 참조하기 위한 변수 human을 servlet에서 생성하여 사용한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        // Object
        
        // dto
        
        Human human = new Human("홍길동"24);
        
        JSONObject jObj = new JSONObject();
        jObj.put("human", human);
        
        resp.setContentType("application/x-json; charset=utf-8");
        resp.getWriter().print(jObj);
        
        
    }    
    
}
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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
            success:function(data){
                alert(data); // [object Object]
                alert(JSON.stringify(data)); // {"human":{"age":24,"name":"홍길동"}}
                alert(data.human.name); // 홍길동
                alert(data.human.age); // 24
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

 

3. list

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        // list
        
        List<Human> list = new ArrayList<Human>();
        list.add(new Human("홍길동"24));
        list.add(new Human("성춘향"16));
        list.add(new Human("홍두께"22));
        
        JSONObject jObj = new JSONObject();
        jObj.put("list", list);
        
        resp.setContentType("application/x-json; charset=utf-8");
        resp.getWriter().print(jObj);
        
        
    }    
    
}
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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
            success:function(data){
                alert(data); // [object Object]
                alert(JSON.stringify(data)); // {"list":[{"age":24,"name":"홍길동"},{"age":16,"name":"성춘향"},{"age":22,"name":"홍두께"}]}
                alert(data.list[1].name); // 성춘향
                alert(data.list[0].age); // 24
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

 

4. HashMap

다양한 자료형의 값들을 넣어서 json 형태로 바꾼 후 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
@WebServlet("/hello")
public class HelloServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        // Map
        
        String str = "안녕하세요";
        
        List<Human> list = new ArrayList<Human>();
        list.add(new Human("홍길동"24));
        list.add(new Human("성춘향"16));
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", str);
        map.put("mylist", list);
        
        JSONObject jObj = new JSONObject();
        jObj.put("map", map);
        
        resp.setContentType("application/x-json; charset=utf-8");
        resp.getWriter().print(jObj);
        
    }    
    
}
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
<%@ 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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
 
<p id="demo"></p>
 
<button type="button">클릭</button>
 
<script>
$(function (){
    
    $("button").click(function(){
//         alert("button click");
        
        $.ajax({
            url:"./hello"// HelloServlet.java로 접근
            type: "get"// GET 방식
            success:function(data){
                alert(data); // [object Object]
                alert(JSON.stringify(data)); // {"map":{"mylist":[{"age":24,"name":"홍길동"},{"age":16,"name":"성춘향"}],"title":"안녕하세요"}}
                alert(data.map.mylist[1].name); // 성춘향
                alert(data.map.title); // 안녕하세요
            },
            error:function(){
                alert("error");
            }
            
        });
        
    });
    
});
 
 
</script>
 
</body>
</html>
cs

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Java > JSP, Servlet' 카테고리의 다른 글

JSP 내장 객체(out, request, session, pageContext)  (0) 2023.02.07
Servlet 정리  (0) 2023.02.06

간단하게 사용하는 코드를 저장하고, 자세한 설명은 다른 게시물에 추가하도록 하자.

 

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
<%@ 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>
</head>
<body>
 
<%-- 
 
    내장 객체 : 동적으로 할당(생성)하지 않고 (언제든지 바로) 사용할 수 있는 객체
    
    out: web으로 출력
    request
    response
    session
    pageContext
    application
         :
--%>
 
<h3>out(web에 출력)</h3>
 
<%
    String title = "hello jsp"
    out.println("<p>" + "hello jsp" + "</p>");
    out.println("<p>" + title + "</p>"); // = servlet java(html)
%>
 
<p><%=title %></p>
 
<h3>request</h3>
<%
// request(요청) : parameter 값을 취득, session을 접근, Object를 전송, encoding 설정 
// HttpServletRequest
// encoding 설정
request.setCharacterEncoding("utf-8");
 
// parameter 값을 취득
// 값 한개 취득(getParameter)
String name = request.getParameter("name");
// url에 "?name=홍길동"을 추가하면,
%>
<p><%=name %></p> <!-- 홍길동 -->
 
<%
// 값 여러개 취득(getParameterValues)
    String[] hobby = request.getParameterValues("hobby");
    // url에 ?hobby=book&hobby=game&hobby=running 추가
    for(int i = 0;i < hobby.length; i++){
    %>
        <p><%=hobby[i] %></p>
    <%    
    }
%>
 
<%
// session에 접근
session = request.getSession(); // 세션 생성 및 얻기
session.setAttribute("visited""1"); // 세션 이름: visited, 세션 값 1 저장
String str = (String)session.getAttribute("visited");
// request.getSession().getAttribute("세션명")의 리턴 타입이 Object이므로 캐스트 연산을 해야한다.
out.println("<h1>" + str + "</h1>"); // 1
 
%>
 
 
 
 
</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
package sample02;
 
import java.io.Serializable;
 
public class Human implements Serializable{
    String name;
    int age;
    
    public Human() {
    }
 
    public Human(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
    
    
    
}
 
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
<%@page import="sample02.Human"%>
<%@ 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>
</head>
<body>
 
<h3>response</h3>
<%
// response: 이동
// response.sendRedirect("이동할 jsp 페이지"): 페이지 이동
// String name = "Tom";
// response.sendRedirect("defaultCopy.jsp?name=" + name + "&age=" + 15);
%>
 
<h3>pageContext</h3>
<
String name = "성춘향";
int age = 16;
 
// 마치 짐을 싸듯이...!
Human human = new Human(name, age);
// human이라는 참조변수가 가리키는 객체를 lady라는 이름으로 담아 보낼 준비
request.setAttribute("lady", human);
 
pageContext.forward("defaultCopy.jsp");
 
 
 
%>
 
</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
<%@page import="sample02.Human"%>
<%@ 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>
</head>
<body>
 
<h1>defaultCopy.jsp</h1>
 
<%--
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
--%>
<%-- 
<p><%=name %></p> 
<p><%=age %></p> 
 --%>
 
<%
    Human human = (Human)request.getAttribute("lady");
%>
<p>이름:<%=human.getName() %></p>
<p>나이:<%=human.getAge() %></p>
 
</body>
</html>
cs

'Java > JSP, Servlet' 카테고리의 다른 글

JSP와 Servlet 사이에 데이터 주고 받기(json)  (0) 2023.02.08
Servlet 정리  (0) 2023.02.06

+ Recent posts