#Spring - 2. Servlet
본문 바로가기
Programming/Spring

#Spring - 2. Servlet

by 권가 2019. 6. 11.

Servlet을 알아가기 전 Static Pages(정적 페이지)와 Dynamic Pages(동적 페이지)에 대해 알고 넘어가자


1. Static Pages vs Dynamic Pages

Static Pages

Web Server

Dynamic Pages

Web Application Server

+System Environment

Client -> WebServer (1-tier)

Client -> Web Application Server -> Database (2-tier)

Client -> Web Server -> Web Application Server -> Database (3-tier)

                            -> Web Application Server -> Database

                            -> Web Application Server -> Database


2. Web Service Architecture


3. Servlet 개요

Servlet: 웹 기반 요청을 동적으로 처리할 수 있는 서버측 Java 프로그램

 

서블릿을 사용하게 되면
- 웹 페이지 양식을 통해 사용자로부터의 입력을 수집할 수 있다.
- 데이터베이스 또는 다른 소스에서 레코드 검색
- 동적으로 웹 페이지 작성

서블릿은 서블릿 기능을 지원하는 WAS(Web Application Server)에 상주한다.
- WAS: Apache Tomcat, setty, WebLogic, JBoss


Java Servlet으로 HTML 양식 데이터 처리

1. 사용자가 Form 태그의 필드를 채우는 것이다. 

2. Form 태그에서 제출한다.
3. 서버가 제출된 데이터를 바탕으로  요청을 처리한다.
4. 고객에게 회신한다.


HTML Form


Servlet Program

public class LoginServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException IOException {
    
    //read form fields
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
    //get response writer
    PrintWriter writer = response.getWriter();
    
    //build HTML code
    String hemlResponse = "<html>";
    htmlResponse += "<h2> Your username is: " + username + "<br/>";
    htmlResponse += "Your password is: " + password + "</h2>";
    htmlResponse += "</html>";
    
    //return response
    writer.println(htmlResponse);
    }
 }


Apache Tomcat

가장 잘 알려진 Servlet/JSP 컨테이너
웹 서버 + Java Servlet 및 JSP API 구현
Apache Software Foundation에서 개발
http://tomcat.apache.org/ 에서 Apache 소프트웨어 라이센스 사용 가능


Files

WebContent/login.html

WebContent/someDir/test.html

해당 URLs

• http://localhost/helloLogin/login.html

• http://localhost/helloLogin/someDir/test.html


Web.xml 내용

web.xml: 배포 설명자
브라우저에서 Java servlet에 액세스할 수 있으려면 servlet 컨테이너에 배포할 servletservlet을 매핑할 URL을 알려야 함
가장 중요한 부분:
별칭 설정: servlet 이름을 실제 servlet 클래스에 연결
매핑: URL을 servlet 이름에 연결

 

web.xml 예


5. HTML forms

- HTML form: 입력 요소가 포함된 웹 페이지의 섹션(예: 텍스트 상자)
- 웹 서버에 form 내용을 제출할 수 있는 제출 요소(버튼)를 포함하는 경우가 많음
- 제출이 작업(form을 처리하는 페이지의 URL)과 연결됨


HTML form example


form methods

두 가지 유형의 양식 제출 방법이 있다.
1. GET 방식
양식 데이터가 URL에 추가됨(물음표별로 작업 URL에서 분리된 데이터)
ex) http://www.test.com/hello?key1=value1&key2=value2
브라우저에서 웹 서버로 정보를 전달하는 기본 방법 
서버에 전달할 암호 또는 기타 중요한 정보가 있는 경우 GET 방법을 사용하지말 것(URL에 모두 보이기 때문에)
GET 메서드 크기 제한: 1024자 
쿼리 유형 작업 또는 결과가 달라지지 않는 작업에 사용.

 

2. POST 방법
URL에서 ?(질문 표시) 후에 정보를 텍스트 문자열로 보내는 대신 POST 메서드는 별도의 메시지로 정보를 전송한다. 
중요 정보 전달 시 POST 작업 사용


6. Servlet Program

1) 서버에 오는 HTTP 요청은 서블릿 컨테이너에 위임한다.
2) 서블릿 컨테이너는 서비스() 방법을 호출하기 전에 서블릿을 적재한다.
3) 서블릿 컨테이너는 여러 개의 스레드를 생성하여 여러 개의 요청을 처리한다. 
서블릿의 단일 인스턴스의 서비스() method를 실행하는 각각의 스레드

 

Servlet 생명주기

서블릿 인스턴스가 생성되면 해당 초기화() 메서드가 호출됨
서블릿에 접수된 모든 요청에 대해 서블릿 서비스() 방법을 호출한다. 
서블릿 컨테이너에 의해 서블릿이 언로드될 때, 서블릿의 파괴() 방법을 호출한다.
서비스() 방법은 HTTP 요청 유형(GET, POST, PUT, DELETE 등)을 확인한다. 
필요에 따라 doGet, doPost, doPut, doDelete 등 호출

 

Servlet 구현 클래스

웹 애플리케이션 개발자들은 일반적으로 javax.servlet.http를 확장하는 서블릿을 작성한다.HttpServlet 
요청 매개 변수를 통해 양식 데이터 읽기, 응답 매개 변수를 통해 출력/결과 웹 페이지 생성

다음 방법 중 하나 이상을 재정의할 것으로 예상:
protected doGet(HttpServletRequest request, HttpServletResponse response) 
protected doPost(HttpServletRequest request, HttpServletResponse response)

Servlet Sample Code

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

public class Hello extends HttpServlet {

    protected void doPost(HttpServletRequest request, 
	HttpServletResponse response) throws ServletException, IOException {
	
	// read form fields
	String username = request.getParameter("username");
	String password = request.getParameter("password");

	// get response writer
	PrintWriter writer = response.getWrite();

	// build HTML code
	String htmlResponse = "<html>";
	htmlResponse += "<h2>Your username is: " + username + "<br/>";
	htmlResponse += "Your password is: " + password + "</h2>";
	htmlResponse += "</html>";

	// return response
	writer.println(htmlResponse);    
    }
}

HttpServletRequest Class

- Reading Form data
getParameter(): form 매개변수의 값을 가져오려면 이 방법을 호출하십시오.
getParameterValues(): form의 매개 변수가 두 개 이상이며, 여러 값을 반환하는 경우(예: CheckBox)

- Java 변환 기능(Integer.parseInt()과 같은)을 사용하여 적절한 유형으로 변환해야 할 수 있음

- 예
String name = request.getParameter("firstname" );
int year = Integer.parseInt( request.getParameter("year");

 

HttpServletResponse Class

form 처리 결과를 용이하게 하기 위해 사용됨
getWriter() 메서드를 호출하여 PrintWriter 핸들을 가져온 다음, 해당 핸들에 인쇄 방법 실행
예:

response.setContentType("text/html" );

PrintWriter out = response.getWriter();

out.println("h2" 시작 </h2");

Handling text/password field

Handling checkbox field

Handling radio button field

Handling text area field

Handling dropdown list field


7. Servlet Concurrency(동시성)

Java 서블릿 컨테이너는 일반적으로 멀티스레드됨
즉, 동일한 서블릿에 대한 다중 요청이 동시에 실행될 수 있다. 
따라서 서블릿을 구현할 때는 Concurrency(동시성)을 고려해야 한다.


8. Servlet Annotations

Servlet API 3.0은 javax.servlet.annotation이라는 새로운 패키지를 도입했다. 
Tomcat 7 +

Annotations은 웹 배포 설명자 파일(web.xml)에서 동등한 XML 구성을 대체할 수 있음 

Annotations 유형
@WebServlet: 서블릿 선언
@WebInitParam : 초기화 파라미터 지정 

@WebServlet(value = "/Simple", initParams = { 
	@WebInitParam(name="foo", value="Hello "), 
	@WebInitParam(name="bar", value=" World!") 

public class Simple extends HttpServlet { 

    protected void doGet(HttpServletRequest request, 
	HttpServletResponse response) 
	throws ServletException, IOException {
 
	response.setContentType("text/html"); 
	PrintWriter out=response.getWriter(); 

	out.print("<html><body>"); 
	out.print("<h3>Hello Servlet</h3>"); 
	out.println(getInitParameter("foo")); 
	out.println(getInitParameter("bar")); 
	out.print("</body></html>"); 
    } 
} 

정리.

서블릿은 자바를 통해 form 데이터를 처리한다.
- HttpServlet을 확장하는 Java 프로그램
서블릿은 웹 애플리케이션의 일부이다.
- web.xml은 적절한 매핑을 나타냄
기타 서블릿 기능: 리디렉션, 세션/쿠키, 필터

댓글