본문 바로가기

JSP, Servlet/JSP, Servlet 기초

[JSP/Servlet] 서블릿 프로그램 작성하기

이클립스에서 [File->New->Dynamic Web Project] 선택
 프로젝트명: jsp-project-02
 패키지명: unit01
 서블릿 클래스명: HelloServlet
 클래스명 입력 후 [Next]버튼을 눌러 “URL Mapping” 입력
 URL Mapping – 실제 자바 클래스 이름 대신에 사용하는 URL 문자열
 “URL mappings:” 목록에서 항목을 선택 후 [Edit] 버튼을 클릭.
 “Pattern” 입력 란에 “/hello”를 입력하고 [OK] 버튼 클릭

 

package Unit01;

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 helloServlet
 */
@WebServlet("/hello")
public class helloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public helloServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html"); // 클라이언트에 응답할 페이지 정보 설정
		PrintWriter out = response.getWriter();
		out.println("<html><head><title>Hello</title></head>");
		out.println("<body><h1>");
		out.println("Hello Servlet");
		out.println("</h1></body>");
		out.println("</html>");
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

 

 

서블렛 url 설정을 hello로 하였다.

 

@WebServlet
 서블릿 클래스의 요청을 위한 URL 매핑 어노테이션
 자바 클래스명 대신 서블릿을 요청하기 위한 문자열로 서블릿 클래스와 매핑.

 

응답 객체에 콘텐트 타입 지정하기
 HttpServletResponse 객체인 response로 setContentType() 메소드 호출
 “text/html” – 결과를 text 또는 html로 전송한다는 의미
 한글 인코딩 방식 지정

 

출력 스트림 얻어오기
 HttpServletResponse 객체에서 getWriter() 메소드를 호출하여 출력 스트림인
PrintWriter 객체를 생성한다.

728x90
반응형