JSP Servlet 기초(1)
- JSP
- 2018. 1. 29. 12:47
JSP Servlet의 기본인 jsp 에서 데이터를 post 방식과 get 방식으로 전송하는 방법에 대해 알아 보겠습니다.
먼저 이클립스에서 src에 패키지를 만듭니다 패키지명은
com.jsp.ex 로 했습니다
다음 패키지 안에 Servlet 을 하나 만들어줍니다
(서블릿명은 Study로 만들었습니다)
WebContent에 jsp 파일을 하나 만들어줍니다
이제 jsp 파일에서 <body> 안에 <form> 태그를 넣어 데이터를 보낼 준비를 합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>Insert title here</title> </head> <body> <form action="Study" method="post"> <input type="submit" value="post"> </form> </body> </html> | cs |
action은 데이터를 보낼곳을 말하고 method="post" 는 데이터를 post 방식으로 보내겠다는 겁니다
Input 태그의 type은 submit 으로, post 라는 이름의 버튼을 만들어 준겁니다.
이를 누르게 되면 form태그가 form 태그 안의 데이터들을 가지고 action="Study" 로 보내집니다
물론 위에서는 아무 데이터도 없기 때문에 데이터를 가지고 가지 않습니다.
다음 위에서 만들었던 Servlet 파일에서
아래와 같이 입력합니다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | package com.jsp.ex; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/Study") public class Study extends HttpServlet { private static final long serialVersionUID = 1L; public Study() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doPost"); } } | cs |
10line에 @WebServlet("/Study") 웹서블릿 어노테이션 이며
보통은 파일명과 일치시킵니다. 웹서블릿 어노테이션을 달아줘야 jsp 파일에서
action을 이용해 데이터를 원하는 서블릿으로 보내줄수 있습니다.
24line에 doPost 메소드는 jsp 파일에서 method="post" 방식으로 보내면
doPost 메소드를 실행하게 됩니다.
doGet 메소드는 데이터를 method="get" 방식으로 보내면 실행됩니다
System.out.println("doGet"); 은 출력문으로 메소드가 실행되면 콘솔창에
doGet 이출력됩니다.
이제 jsp 파일을 실행시켜보면 jsp 파일에서 get 또는 post 방식으로 보내진
메소드가 실행되면서 콘솔창으로 메소드가 실행 되었는지 확인할수있습니다.
'JSP' 카테고리의 다른 글
JSP Servlet 기초(6) 쿠키생성 (2) | 2018.01.29 |
---|---|
JSP Servlet 기초(5) response (0) | 2018.01.29 |
JSP Servlet 기초(4) request + tag (2) | 2018.01.29 |
JSP Servlet 기초(3) 태그 (0) | 2018.01.29 |
JSP Servlet 기초(2) (1) | 2018.01.29 |