WebContent > student.html
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
var obj = {
name : "학생",
age : 22
};
$.ajax({
url : "Check",
type : "POST",
dataType : "json",
data : obj,
success : function(result) {
for (var i = 0; i < result.length; i++) {
console.log(result[i].name);
console.log(result[i].age);
}
},
error : function() {
alert('error');
}
});
</script>
</body>
</html>
Java Resources > src > com > Check.java
package com;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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("/Check")
public class Check extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
MemberDTO dto1 = new MemberDTO("학생1", "22");
MemberDTO dto2 = new MemberDTO("학생2", "21");
MemberDTO dto3 = new MemberDTO("학생3", "28");
ArrayList<MemberDTO> list = new ArrayList<MemberDTO>();
list.add(dto1);
list.add(dto2);
list.add(dto3);
Gson gson = new Gson();
String value = gson.toJson(list);
PrintWriter out = response.getWriter();
out.print(value);
}
}
Java Resources > src > com > MemberDTO.java
package com;
public class MemberDTO {
private String name;
private String age;
public MemberDTO(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
'Programming > Javascript' 카테고리의 다른 글
의견 공유판 만들기 (0) | 2020.03.09 |
---|---|
캐릭터 움직이기 (0) | 2020.03.09 |
리스트 항목추가하기 (ajax를 활용하여 영화 순위 리스트로 가져오기) (0) | 2020.03.08 |
css 적용 (0) | 2020.03.08 |
준비물 메모장 구현 실습 (0) | 2020.03.08 |