Server

SERVLET STEP 2 - Servlet 응용

IT의 큰손 2023. 5. 8. 12:50
728x90

★ Servlet 구조

  • 작동 원리 및 구조

 

■ 데이터 전송 및 수신

  • 1. 데이터 전송 -> Ex04
  • 2. 데이터 수신 -> Ex04Ok
  • Ex04 소스코드 
package com.test.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

public class Ex04 extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		resp.setCharacterEncoding("UTF-8");
		
		PrintWriter writer = resp.getWriter();
		
		writer.println("<html>");
		writer.println("<head>");
		writer.println("<meta charset='UTF-8'>");
		writer.println("</head>");
		writer.println("<body>");
		writer.println("<h1>데이터 보내기</h1>");
		writer.println("<form method='GET' action='/servlet/ex04ok'>");
		writer.println("<div>이름 : <input type='text' name='name'></div>");
		writer.println("<div></div>");
		writer.println("<div></div>");
		writer.println("<div><input type='submit' value='보내기'></div>");
		writer.println("</form>");
		writer.println("</body>");
		writer.println("</html>");

		writer.close();
	}
	
}
  • Ex04Ok
  • 1. 데이터 수신하기
//1. 데이터 수신하기
    String name = req.getParameter("name"); //텍스트 박스에 입력한 문자열
    System.out.println(name);
  • 결과

결과

  • 2. 응답 페이지 작성
//2. 응답 페이지 작성
    resp.setCharacterEncoding("UTF-8");

    PrintWriter writer = resp.getWriter();

    writer.println("<html>");
    writer.println("<head>");
    writer.println("<meta charset='UTF-8'>");
    writer.println("</head>");
    writer.println("<body>");
    writer.println("<h1>데이터 수신 완료</h1>");
    writer.println("<div>데이터 : " + name +"</div>");
    writer.println("</body>");
    writer.println("</html>");

    writer.close();
  • 결과

 

■ Post, Get 방식

  • Post 방식
1. <form method="POST">
2. XMLHttpRequest(Ajax)
  • Get 방식
1. <form method="GET">
2. XMLHttpRequest(Ajax)
3. <a href="">
4. location.href
5. F5(새로고침)
6. URL 직접 입력
728x90