2012-4-24 Application Scope와 listener를 사용해서 여러명의 값을 공동장소 저장하고 불러오기[과제]
프로그래밍/JSP Programming 2012. 4. 24. 16:50
- Listener class
package : servlet.member.listener
class : SaveRequestMemberListener
-- Application scope에 list-ArrayList객체를 binding
package servlet.member.listener;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SaveRequestMemberListener implements ServletContextListener {
public SaveRequestMemberListener() {
}
public void contextInitialized(ServletContextEvent sce) {
//1.ServletContext 조회
ServletContext ctx = sce.getServletContext();
//2. application scope에 ArrayList 객체를 binding
ctx.setAttribute("list", new ArrayList());
}
public void contextDestroyed(ServletContextEvent arg0) {
//application 종료 시 DB에 데이터 넣는 작업
}
}
- servlet class
package : servlet.member.attribute
name : SaveReqMemberServlet
- 요청파라미터를 읽어 MemberDTO객체로 만든 뒤 apllication scope의 list에 추가
package servlet.member.attribute;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import servlet.member.dto.MemberDTO;
/**
* Servlet implementation class SaveReqMemberServlet
*/
public class SaveReqMemberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SaveReqMemberServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. ServletContext 조회
ServletContext cxt = getServletContext();
//2. 요청 파라미터 조회
request.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
String name = request.getParameter("name");
int age = 0; //숫자를 변환 시켜줄때는 반드시 try{}catch{}로 예외처리 해줘라
try{
age=Integer.parseInt(request.getParameter("age"));
}catch(NumberFormatException e){}
String sex = request.getParameter("sex");
MemberDTO memberDTO = new MemberDTO(id, name, age, sex);
//3. application scop에서 ArrayList 객체 lookup
ArrayList list= (ArrayList)cxt.getAttribute("list");
list.add(memberDTO);
//4. 응답처리
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<a href ='/homework/attribute/request_member_form.html'>회원등록</a> ");
out.println("<a href ='/homework/ShowAllReqMembersServlet'>회원모두보여주기</a> ");
out.println("</body></html>");
}
}
ShowAllReqMembersServlet
- application scope의 list에 있는 MemberDTO의 값들을 모두 출력하여 응답
package servlet.member.attribute;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import servlet.member.dto.MemberDTO;
public class ShowAllReqMembersServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ShowAllReqMembersServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.ServletContext 조회
ServletContext cxt = getServletContext();
//2. Application scope에서 ArrayList객체 lookup
ArrayList list= (ArrayList)cxt.getAttribute("list");
//3. 응답처리
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>homework 어플리케이션에서 요청한 회원정보</h2>");
for(Object obj : list){
MemberDTO memberDTO = (MemberDTO) obj;
out.println("Id : "+memberDTO.getId()+"<br>");
out.println("이름 : "+memberDTO.getName()+"<br>");
out.println("나이 : "+memberDTO.getAge()+"<br>");
out.println("성별 : "+memberDTO.getSex()+"<br>");
out.println("<hr>");
}
// for(int i = 0;i<list.size();i++){
// out.println(list.get(i));
// }
// out.println("</body></html>");
}
}
class
package : servlet.member.dto
name : MemberDTO(아이디, 이름, 나이, 성별을 갖고 있어야 함)
package servlet.member.dto;
public class MemberDTO {
private String id;
private String name;
private int age;
private String sex;
public MemberDTO() {
super();
}
public MemberDTO(String id, String name, int age, String sex) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "MemberDTO [id=" + id + ", name=" + name + ", age=" + age
+ ", sex=" + sex + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MemberDTO other = (MemberDTO) obj;
if (age != other.age)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
return true;
}
}
- HTML
WebContent
folder : attribute
html : request_member_form.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>request_member_form</title>
</head>
<body>
<form action="/homework/SaveReqMemberServlet" method="post">
<table>
<tr>
<td>id : </td>
<td><input type="text" name="id" size="10"></td>
</tr>
<tr>
<td>이름 : </td>
<td><input type="text" name="name" size="10"></td>
</tr>
<tr>
<td>나이 : </td>
<td><input type="text" name="age" size="10"></td>
</tr>
<tr>
<td colspan="2">성별 : 남<input type="checkbox" name="sex" value="man"> 여<input type="checkbox" name="sex" value="woman"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="전송"></td>
</tr>
</table>
</form>
</body>
</html>
- xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>homework</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>servlet.member.listener.SaveRequestMemberListener</listener-class>
</listener>
<servlet>
<description></description>
<display-name>SaveReqMemberServlet</display-name>
<servlet-name>SaveReqMemberServlet</servlet-name>
<servlet-class>servlet.member.attribute.SaveReqMemberServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SaveReqMemberServlet</servlet-name>
<url-pattern>/SaveReqMemberServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ShowAllReqMembersServlet</display-name>
<servlet-name>ShowAllReqMembersServlet</servlet-name>
<servlet-class>servlet.member.attribute.ShowAllReqMembersServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowAllReqMembersServlet</servlet-name>
<url-pattern>/ShowAllReqMembersServlet</url-pattern>
</servlet-mapping>
</web-app>
* 회원등록(회원등록 페이지 누르면 여러명의 회원정보 등록)
* 등록 및 보여주기
* 회원모두보여주기 클릭 결과
'프로그래밍 > JSP Programming' 카테고리의 다른 글
2012-4-25 클라이언트의 요청을 다른 컴포넌트로 이동시키기 (0) | 2012.04.25 |
---|---|
2012-4-25 request scope활용[실습] (0) | 2012.04.25 |
2012-4-24 Application scope개념 & ServletAttributeServlet[실습] (0) | 2012.04.24 |
2012-4-24 Attribute(속성) (0) | 2012.04.24 |
2012-4-24 DriverLoadingListener[실습]( 이클립스 이용하여 리스너 자동 생성하기) (0) | 2012.04.24 |