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 |