앎/web

[Servlet] 웹 페이지에서의 데이터 요청 방식 (GET, POST)

후니아부지 2014. 3. 6. 15:56

GET 방식의 요청

  • 웹 브라우저의 주소 표시줄에서 접속하려는 URL을 직접 입력하는 경우
  • 웹 페이지에서 링크를 클릭한 경우
  • 웹 페이지에서 링크나 버튼에 설정된 이벤트에 의해 자바 스크립트가 실행되어 location.href 에 의해 요청이 발생한 경우
  • 웹 페이지에서 링크나 버튼에 설정된 이벤트에 의해 자바 스크립트가 실행되어 window.open() 함수가 실행 되는 경우
  • 웹 페이지에서 링크나 버튼 혹은 그에 따른 자바 스크립트가 실행되어 <form> 태그에 의해 요청이 발생한 경우
  • REDIRECT 방식에 의해 웹 페이지가 이동되는 요청이 발생하는 경우
예제)
RequestMethodTestServlet.java
package com.study;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestMethodTestServlet extends HttpServlet {
	 public void init() {		 
	 }
	 
	 public void service(HttpServletRequest _request, HttpServletResponse _response) 
					 throws IOException, ServletException {
		String method = _request.getMethod();
		System.out.println("HTTP Method: " + method);
	 }
	 
	 public void destory() {		 
	 }
}


web.xml

  <servlet>
  	<servlet-name>RequestMethod</servlet-name>
  	<servlet-class>com.study.RequestMethodTestServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>RequestMethod</servlet-name>
  	<url-pattern>/RequestMethod.do</url-pattern>
  </servlet-mapping>


GetRequest.htm

<!DOCTYPE html>
<html>
	<head>
		<meta charset="EUC-KR">
		<title>GET 방식 요청 테스트</title>
		<script language="javascript">
        <!--
			function movePage() {
            	location.href = "/GetTest.do";
			} 
        //-->
		</script>
		
	</head>
	<body>
		<a href="/GetTest.do">LINK</a>
		<br/><br/>
		<input type="button" value="버튼(javascript location.href)" onClick="movePage()"/>
	
	</body>
</html>


POST 방식의 요청

  • <form> 태그의 POST 지정

<form method="POST" action="....">

  • javascript를 통한 form method 지정

<script>

    function check_form() {

        myform.method = "POST";

        return true;

    }

</script>

<form name="myform" method="GET" action="...." onSubmit="return check_form()">

  • 서블릿에서 RequestDispatcher 객체를 사용하여 다른 페이지에서 POST로 넘어온 요청을 forward하는 경우
  • JSP의 forward 태그 라이브러리를 사용하여 다른 페이지에서 POST로 넘어온 요청을 forward하는 경우

예제)
PostRequest.htm
<!DOCTYPE html>
<html>
	<head>
		<meta charset="EUC-KR">
		<title>POST 방식 요청 테스트</title>
		<script language="javascript">
		<!--
			function movePage() {
				myform.method="POST";
				myform.submit();			
			}		
		//-->
		</script>	
	</head>
	<body>
		<form name="myform" action="/RequestTest/Request.do">
			<input type="button" value="전송" onClick="movePage()"/>
		</form>
	</body>
</html>