본문 바로가기

Programming/Javascript

학생 목록 list로 관리하기 (ajax 활용)

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;
	}
}