AddPhoneBook.java
package com;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
@WebServlet("/AddPhoneBook")
public class AddPhoneBook extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PhoneDTO dto1 = new PhoneDTO("이름1", "전화번호1", "나이1");
PhoneDTO dto2 = new PhoneDTO("이름2", "전화번호2", "나이2");
PhoneDTO dto3 = new PhoneDTO("이름3", "전화번호3", "나이3");
PhoneDTO dto4 = new PhoneDTO("이름4", "전화번호4", "나이4");
PhoneDTO dto5 = new PhoneDTO("이름5", "전화번호5", "나이5");
ArrayList<PhoneDTO> list = new ArrayList<>();
list.add(dto1);
list.add(dto2);
list.add(dto3);
list.add(dto4);
list.add(dto5);
HttpSession session = request.getSession(); // 세션 만들기
session.setAttribute("list", list); // ArrayList 보냄
session.setMaxInactiveInterval(100); // session 나이설정
response.sendRedirect("view.jsp");
}
}
main.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<a href="AddPhoneBook">전화번호부 보러가기!</a>
</body>
</html>
PhoneDTO.java
package com;
public class PhoneDTO {
private String name;
private String tel;
private String age;
public PhoneDTO(String name, String tel, String age) {
this.name = name;
this.tel = tel;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
view.jsp
<%@page import="com.PhoneDTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
ArrayList<PhoneDTO> list = (ArrayList<PhoneDTO>) session.getAttribute("list");
// Object를 ArrayList로 다운캐스팅, ArrayList import, PhoneDTO import
%>
<div>
<table border="1px solid black" text-align="center">
<tr>
<td>순번</td>
<td>이름</td>
<td>나이</td>
<td>전화번호</td>
</tr>
<%
for (int i = 0; i < list.size(); i++) {
%>
<tr>
<td><%=i + 1%></td>
<td><%=list.get(i).getName()%></td>
<td><%=list.get(i).getAge()%></td>
<td><%=list.get(i).getTel()%></td>
</tr>
<%
}
%>
</table>
</div>
</body>
</html>
'Programming > Servlet & JSP' 카테고리의 다른 글
장바구니(쿠키) (0) | 2020.02.20 |
---|---|
로그인(세션) (0) | 2020.02.20 |
쿠키 확인, 생성, 삭제 (0) | 2020.02.19 |
멤버 관리 (jsp, servlet, 로그인, 회원 가입, 정보 관리) (0) | 2020.02.19 |
footer 만들기, 꼬리 번호 (0) | 2020.02.19 |