전체적은 설명을 덧붙이자면 클라이언트 즉, 웹 브라우저에 입력 값을 받는다. 그리고 로그인 버튼을 누르면 서버로 입력된 데이터가 이동하는데, 이를 서버로 '요청'한다고 한다.
용도에 따라 요청하는 의도가 다르지만 현재 예시가 로그인이므로 '인증'에 대한 요청이라고 가정하자.
그럼 어떻게 인증할까?
보통 데이터베이스에 해당 아이디와 비밀번호가 일치하는지 확인할 것이다. DB에 데이터를 확인하기 위해 바로 sql문으로 치환되는 것이 아닌, Web Server와 Application Server, Database Server로 나눠서 처리한다.
자바를 사용하여 웹페이지를 동적으로 생성하는 서버측 프로그램 (or 그 사양)
이후 다룰 JSP와 비슷한 점이 있지만 JSP는 Java in HTML, Servlet은 HTML in Java라는 차이가 있다. 그래서 Servlet은 문자열 안에 HTML 태그를 담아야 한다.
위에서 설명한 그림과 비슷한 내용이다. 이제는 서블릿이 로직처리, DB와 연동 처리, 화면 처리를 해준다. 나중에는 이를 MVC로 분리한다.
일반적으로 Servlet 인터페이스를 구현하면 init부터 get, service 메서드 등을 전부 구현해야 한다. 이를 간편하게 처리하기 위해 service를 제외한 나머지 메서드를 구현한 GenericServlet 추상 클래스를 상속받으면 된다. 그럼 sevice로직에 해당하는 service메서드 만 구현하면 된다.
클라이언트로 데이터를 받을 때 GET/POST 두 가지 방식으로 받는다.
톰캣 10.1버전 미만은 두 방식을 나누어 구현해야 했지만, 10.1부터는 나누지 않아도 된다.
HttpServlet 추상 클래스를 살펴보자. 내부 클래스를 들여다보면, 추상 클래스지만 추상 메서드가 없는 것을 확인할 수 있다. 이는 개발자가 직접 생성하지 못하도록 제어하기 위해 의미상 추상을 붙였다고 할 수 있다. service 메서드 역시 구현되어 있으므로 필요할 때 재정의하면 되고 기본적인 GET/POST방식은 doGet() / doPost() 메서드를 사용하면 된다.
Servlet 클래스는 main 메서드가 없다. 즉, 객체의 생성부터 함수를 호출하는 것의 주체가 사용자가 아닌 Servlet Container에게 있다.
클라이언트가 요청(Request)을 하게 되면 Servlet 컨테이너는 Servlet객체를 생성하고, 초기화한다. 각 생성과 초기화는 한 번 만 한다. 그리고 요청에 대한 처리는 요청마다 반복한다. 또한, Servlet객체가 필요없어지면 제거하는 작업까지 컨테이너가 담당한다.
public interface Servlet {
/**
* Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
* <p>
* The servlet container calls the <code>init</code> method exactly once after instantiating the servlet. The
* <code>init</code> method must complete successfully before the servlet can receive any requests.
* <p>
* The servlet container cannot place the servlet into service if the <code>init</code> method
* <ol>
* <li>Throws a <code>ServletException</code>
* <li>Does not return within a time period defined by the Web server
* </ol>
*
* @param config a <code>ServletConfig</code> object containing the servlet's configuration and initialization
* parameters
*
* @exception ServletException if an exception has occurred that interferes with the servlet's normal operation
*
* @see UnavailableException
* @see #getServletConfig
*/
void init(ServletConfig config) throws ServletException;
/**
* Returns a {@link ServletConfig} object, which contains initialization and startup parameters for this servlet.
* The <code>ServletConfig</code> object returned is the one passed to the <code>init</code> method.
* <p>
* Implementations of this interface are responsible for storing the <code>ServletConfig</code> object so that this
* method can return it. The {@link GenericServlet} class, which implements this interface, already does this.
*
* @return the <code>ServletConfig</code> object that initializes this servlet
*
* @see #init
*/
ServletConfig getServletConfig();
/**
* Called by the servlet container to allow the servlet to respond to a request.
* <p>
* This method is only called after the servlet's <code>init()</code> method has completed successfully.
* <p>
* The status code of the response always should be set for a servlet that throws or sends an error.
* <p>
* Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently.
* Developers must be aware to synchronize access to any shared resources such as files, network connections, and as
* well as the servlet's class and instance variables. More information on multithreaded programming in Java is
* available in <a href="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html"> the Java tutorial on
* multi-threaded programming</a>.
*
* @param req the <code>ServletRequest</code> object that contains the client's request
* @param res the <code>ServletResponse</code> object that contains the servlet's response
*
* @exception ServletException if an exception occurs that interferes with the servlet's normal operation
* @exception IOException if an input or output exception occurs
*/
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
/**
* Returns information about the servlet, such as author, version, and copyright.
* <p>
* The string that this method returns should be plain text and not markup of any kind (such as HTML, XML, etc.).
*
* @return a <code>String</code> containing servlet information
*/
String getServletInfo();
/**
* Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This
* method is only called once all threads within the servlet's <code>service</code> method have exited or after a
* timeout period has passed. After the servlet container calls this method, it will not call the
* <code>service</code> method again on this servlet.
* <p>
* This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory,
* file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state
* in memory.
*/
void destroy();
}
HTTP 메서드처럼 GET/POST/PUT/DELETE방식이 존재하지만, 가장 많이 사용하는 GET/POST 방식만 다뤄보겠다.
GET방식으로 요청이 들어오면 URL에 있는 파라미터를 받아야 한다.
그러기 위해 URL을 다음과 같이 분리했다.
http://www.ssafy.com/good.js?parameter1=value1¶meter2=value2
여기에 ?를 기준으로 오른쪽은 Query라고 한다. 그 다음에는 &를 기준으로 파라미터 이름과 값이 =을 사이에 두고 있다.
그리고 이 파라미터 데이터를 다음과 같이 받아올 수 있다.
- 단수
getParameter(String parameterName)- 복수
getParameterValues(String parameterName)