JSP/서블릿 흝어 보기

HttpServletRequest

언제 이용하는가?

하나의 요청에서 HttpServletRequest 객체가 소멸하기 까지 상태정보를 유지하고자 할 때, 한번의 요청으로 실행된 페이지끼리 정보를 공유하고자 할 때 사용되며, 디스패처에 의한 요청재지정을 하기 전 HttpServletRequest 객체의 setAttribute( ) 메소드로 데이터를 등록하고 요청 재지정으로 HttpServletRequest 객체가 전달된 페이지에서 getAttribute( ) 메소드로 추출할 수 있다.

Request 단위 정보 공유

하나의 요청에 의해 실행되는 페이지간의 정보를 공유하는 예제를 살펴보자 

memberInput.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>회원 가입하기</h3>
<form method="post" action="memberReg">
    <p>아이디</p>
	<input type="text" name="userId" placeholder="이름을 입력해 주세요">

	<p>패스워드</p>
	<input type="password" name="passwd" placeholder="패스워드를 입력해 주세요">

	<p>이메일</p>
	<input type="text" name="email" placeholder="이메일을 입력해 주세요">
	
	<p>이메일 수신여부</p>
	<input type="radio" name="emailAgree" value="yes">예
	<input type="radio" name="emailAgree" value="no" checked>아니오
		
	<p>관심사항</p>
	<input type="checkbox" name="interest" value="IT">IT/인터넷
	<input type="checkbox" name="interest" value="movie">영화
	<input type="checkbox" name="interest" value="music">음악
	<input type="checkbox" name="interest" value="book">책
	<input type="checkbox" name="interest" value="food">음식
	
	<p>핸드폰</p>	
	<select name="hp_1">
        <option value="010">010</option>
        <option value="010">011</option>
     </select>
     <input type="text" name="hp_2" placeholder="핸드폰 번호를 입력해주세요">
	
	<p>자기소개</p>
	<textarea name="introduce" placeholder="자기소개를 입력해주세요" cols="30" rows="4"></textarea>
	<br/>
	
	<input type="submit" value="전송">
	
</form>
</body>
</html>

Member.java

package job.study.web;

public class Member {
    private String userId;
	private String passwd;
	private String email;
	private String hp_1;
	private String hp_2;
	private String emailAgree; //라디오
	private String[] interest; //체크박스
	private String introduce;
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getHp_1() {
		return hp_1;
	}
	public void setHp_1(String hp_1) {
		this.hp_1 = hp_1;
	}
	public String getHp_2() {
		return hp_2;
	}
	public void setHp_2(String hp_2) {
		this.hp_2 = hp_2;
	}
	public String getEmailAgree() {
		return emailAgree;
	}
	public void setEmailAgree(String emailAgree) {
		this.emailAgree = emailAgree;
	}
	public String[] getInterest() {
		return interest;
	}
	public void setInterest(String[] interest) {
		this.interest = interest;
	}
	public String getIntroduce() {
		return introduce;
	}
	public void setIntroduce(String introduce) {
		this.introduce = introduce;
	}		
}

MemberRegServlet.java

package job.study.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class jobTestServlet
 */
@WebServlet("/memberReg")
public class MemberRegServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MemberRegServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setContentType("text/html);charset=UTF-8");
		
		//요청정보 몸체에 있는 문자열들을 인자값으로 지정한 문자코드로 인코딩한다.
		request.setCharacterEncoding("UTF-8");
		
		//getParameter는 중복되지 않고 유일하게 하나만 넘어올 떄 사용된다.
		//getParameter의 반환값은 String이다. 
		String userId = request.getParameter("userId");
		String passwd = request.getParameter("passwd");
		String email = request.getParameter("email");
		String hp_1 = request.getParameter("hp_1");
		String hp_2 = request.getParameter("hp_2");
		String emailAgree = request.getParameter("emailAgree");
		//getParameterValues는 체크박스처럼 다중 선택되는 입력 양식의 값을 추출할 떄 사용된다.
		String[] interest = request.getParameterValues("interest");
		String introduce = request.getParameter("introduce");
		
		//멤버객체에 회원정보를 저장한다.
		Member member = new Member();
		member.setUserId(userId);
		member.setPasswd(passwd);
		member.setEmail(email);
		member.setHp_1(hp_1);;
		member.setHp_2(hp_2);
		member.setEmailAgree(emailAgree);
		member.setInterest(interest);
		member.setIntroduce(introduce);
		
		//HttServletRequest 객체에 회원정보를 등록한다.
		request.setAttribute("member",member);
		
		//디스패처에 의한 요청 재지정
		//멤버객체를 출력 할 서블릿의 URI를 지정한다.
		RequestDispatcher rd = request.getRequestDispatcher("memberOutput");
		rd.forward(request, response);
		
	}

}

MemberOutputServlet.java

package job.study.web;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ResumeOutputServlet
 */
@WebServlet("/memberOutput")
public class MemberOutputServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MemberOutputServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		//HttpServletRequest 객체에 등록된 회원 정보를 추출한다.
		Member member = (Member) request.getAttribute("member");
		
		out.println("<h3>회원아이디 : "+member.getUserId()+"</h3>");
		out.println("<h3>패스워드 : "+member.getPasswd()+"</h3>");
		out.println("<h3>이메일 : "+member.getEmail()+"</h3>");
		out.println("<h3>핸드폰 : "+member.getHp_1()+"-"+member.getHp_2()+"</h3>");		
		out.println("<h3>이메일수신여부 : "+member.getEmailAgree()+"</h3>");
		out.println("<h3>관심사항: </h3>");
		
		String[] interest = member.getInterest();
				
		for(int i=0; i< interest.length;i++)
		{
			if(i+1 == interest.length) {
				out.println(interest[i]);
			}else {
				out.println(interest[i]+",");
			}
		}
		out.println("<h3>자기소개 : "+member.getIntroduce()+"</h3>");

		out.close();
	}

}

실행결과

댓글

댓글 본문