server.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--><!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
--><Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
<!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
<Listener className="org.apache.catalina.core.JasperListener"/>
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the BIO implementation that requires the JSSE
style configuration. When using the APR/native implementation, the
OpenSSL style configuration is required as described in the APR/native
documentation -->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine defaultHost="localhost" name="Catalina">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log." suffix=".txt"/>
<Context docBase="servletTest" path="/servletTest" reloadable="true" source="org.eclipse.jst.jee.server:servletTest"/></Host>
</Engine>
</Service>
</Server>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>servletTest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>servletTest01</servlet-name>
<servlet-class>kr.or.ddit.basic.ServletTest01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletTest01</servlet-name>
<url-pattern>/servletTest01.do</url-pattern>
</servlet-mapping>
</web-app>
servletTest01
package kr.or.ddit.basic;
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;
/*
* Servlet이란? => 컨테이너(서블릿엔진)에 의해 관리되는 자바 기반의 웹컴포넌트.
* 동적인 웹 컨텐츠 생성을 가능하게 한다.
*/
/*
* 이 서블릿을 호출할 URL주소 만들기
* 예) http://localhost:80/servletTest/servletTest01.do
* - http ==> 프로토클
* - localhost ==> 컴퓨터이름(도메인명) 또는 IP주소
* - 80 ==> PORT번호 (80번은 생략 가능)
* - /servletTest ==> 컨텍스트패스(보통 프로젝트이름으로 지정한다.)
* - /servletTest01.do ==> 서블릿 요청 URL패턴
*
*/
// 서블릿을 등록하는 방법이 2가지가 있는데
// 첫번째는 배포서술자(web.xml)를 이용하는 방법
// 두번째는 애노테이션을 이용하는 방법이 있다.
// 이 예제는 배포서술자를 이용하는 방법을 사용하는 예제이다.
public class ServletTest01 extends HttpServlet{
private static final long serialVersionUID = 1L;
/*
* 이 곳에서는 대부분 service()메서드나 doGet()메서드 또는 doPost()메서드를
* 재정의 해서 작성한다.
*
* doGet()메서드나 doPost()메서드의 매개변수로 다음과 같은 2개의 객체가 전달된다.
* 1) HttpServletRequest객체
* ==> 서비스 요청에 관련된 정보 및 메서드를 관리하는 객체
* 2) HttpServletResponse객체
* ==> 서비스 응답에 관련된 정보 및 메서드를 관리하는 객체
*/
//service()메서드 ==> 모든 요청시 실행되는 메서드
// ==> 이 메서드에서 전송방식에 맞는 메서드를 자동 호출해 준다.
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.service(req, resp);
}
//doGet()메서드 ==> GET방식의 요청을 처리하는 메서드
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8"); //응답 문서의 인코딩 방식 지정
response.setContentType("text/html; charset=utf-8"); //응답문서의 ContestType 지정
//처리한 내용을 응답으로 보내기 위한 PrintWriter객체 생성
PrintWriter out = response.getWriter();
//처리한 내용을 PrintWriter객체를 이용하여 출력한다.
//(이 작업이 곧 응답데이터를 클라이언트로 보내는 작업이 된다.)
//방법1 : append()메서드 이용하기
out.append("<html>")
.append("<head>")
.append("<meta charset='utf-8'>")
.append("<title>첫번째 Servlet 연습</title>")
.append("</head>")
.append("<body>")
.append("<h1 style='text-align:center;'>")
.append("안녕하세요. 첫번째 Servlet 프로그램입니다.<br>")
.append("실행 Servlet : " + request.getContextPath())
.append("</h1></body></html>");
}
//doPost()메서드 ==> POST방식의 요청을 처리하는 메서드
@Override
protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
doGet(requset, response);
}
}
BasicService.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Servlet 요청 연습</h1><hr>
<h2>GET방식 요청1 - 링크 방식</h2>
<a href="http://localhost/servletTest/servletTest03.do">GET 방식 요청1</a>
<br><hr><br>
<h2>
GET방식 요청2 - form태그의 submit방식<br>
- form태그의 method속성 생략하거나 'get'으로 설정한 경우
</h2>
<form action="http://localhost/servletTest/servletTest03.do" method="get">
<input type="submit" value="GET방식 요청2">
</form>
<br><hr><br>
<h2>POST방식 요청 - form submit방식<br>
- form태그의 method속성값을 'post'로 설정한 경우
</h2>
<form action="http://localhost/servletTest/servletTest03.do" method="post">
<input type="submit" value="POST방식 요청">
</form>
<br><hr><br>
</body>
</html>
ServletTest02
package kr.or.ddit.basic;
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;
/*
* 이 예제는 애노테이션을 이용하여 서블릿을 등록하는 예제입니다.
* 애노테이션(@WebServlet)은 Servlet버전 3.0이상에서 사용할 수 있다.
*/
/*
* @WebService 애노테이션의 속성들
* 1) name : 서블릿 이름을 설정한다.(기본값 : 빈문자열(""))
* 2) urlPattern : 서블릿의 요청 URL패턴의 목록을 설정한다.(기본값 : 빈배열({})
* 예) urlPatterns="/url1" 또는 urlPattern={"/url1"} ==> 패턴이 1개일 경우
* 예) urlPatterns={"/url1", "/url2", ...} ==> 패턴이 2개 이상일 경우
* 3) value : urlPattern 속성과 동일한 기능을 한다.
* 4) description : 주석(설명글)을 설정한다.
*
*
*
*/
@WebServlet(urlPatterns="/servletTest02.do",
description="애노테이션을 이용한 서블릿 설정 예제")
public class ServletTest02 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
//처리한 내용을 PrintWriter객체를 이용하여 출력
//(이 작업이 곧 응답 데이터를 클라이언트로 보내는 작업이됨)
//방법2 : print()메서드 또는 println()메서드 이용하기
out.println("<html>");
out.println("<head><head><meta charset='utf-8'>"
+ "<title>두번째 서블릿 예제</title></head>");
out.println("<body>");
out.println("<h1 style='text-align:center;'>");
out.println("안녕하세요. 두번째 서블릿 예제입니다.<br>");
out.println("애너테이션을 이용하여 설정했습니다.<br><br>");
out.println("실행 ContextPath : "+ request.getContextPath() + "</h1>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
ServletTest03
package kr.or.ddit.basic;
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;
//서블릿의 LifeCycle 예제
@WebServlet("/servletTest03.do")
public class ServletTest03 extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
System.out.println("Servlet : "+ this.getServletName()
+ "에서 init()메서드 호출...");
}
public void destroy() {
System.out.println("Servlet : "+ this.getServletName()
+ "에서 destroy()메서드 호출...");
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("service() 메서드 시작...");
//GET방식과 POST방식에 맞는 메서드를 호출하기
// 방법1 ==> HttpServlet의 service()메서드로 위임해서 처리한다.
//super.service(request, response);
//방법2 ==> 클라이언트의 전송방식(GET, POST등)을 구분해서 직접 메서드 호출하기
String method = request.getMethod(); //전송방식을 반환하는 메서드
System.out.println("method = " + method);
if("GET".equals(method)) {
doGet(request, response);
}else if("POST".equals(method)) {
doPost(request, response);
}else {
System.out.println("알 수 없는 전송방식입니다.");
return;
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet()메서드 시작...");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html><head><meta charset='utf-8'></head>");
out.println("<body><h1>doGet()메서드를 처리한 결과~~~~</h1></body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost()메서드 시작...");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html><head><meta charset='utf-8'></head>");
out.println("<body><h1>doPost()메서드를 처리한 결과~~~~</h1></body></html>");
}
}
ServletTest04
package kr.or.ddit.basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
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 ServletTest04
*/
@WebServlet("/ServletTest04.do")
public class ServletTest04 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Servlet 환경 정보 알아보기
// ==> Servlet클래스나 JSP페이지의 환경에 관련된 정보는
// javax.servlet.ServletContext 인터페이스 타입의 객체를
// 이용해서 얻을 수 있다.
//ServletContext객체 구하기
ServletContext context = this.getServletContext();
String serverInfo = context.getServerInfo();
int majorVersion = context.getMajorVersion();
int minorVersion = context.getMinorVersion();
String servletName = this.getServletName();
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html><head><meta charset='utf-8'>");
out.println("<title>웹 서버 정보 보기</title></head>");
out.println("<body>");
out.println("웹 서버 종류(ServerInfo): " + serverInfo + "<br>");
out.println("servletName : " + servletName + "<br>");
out.println("지원하는 Servlet버전 : " + majorVersion + "." + minorVersion+"<br>");
out.println("</body></html>");
}
/**
* @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);
}
}
requestTest.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Request 연습 Form</title>
</head>
<body>
<h2>Request 연습 Form</h2><hr>
<form name="testForm" method="post" action="http://localhost/servletTest/requestTest01.do">
<table border="1">
<tr>
<td>이름</td>
<td><input type="text" size="10" name="username"></td>
</tr>
<tr>
<td>직업</td>
<td>
<select name ="job">
<option value="무직">무직</option>
<option value="회사원">회사원</option>
<option value="전문직">전문직</option>
<option value="공무원">공무원</option>
<option value="학생">학생</option>
</select>
</td>
</tr>
<tr>
<td>취미</td>
<td>
<input type="checkbox" name="hobby" value="여행" id="hobby1">
<label for="hobby1">여행</label>
<input type="checkbox" name="hobby" value="게임" id="hobby2">
<label for="hobby1">게임</label>
<input type="checkbox" name="hobby" value="배드민턴" id="hobby3">
<label for="hobby1">배드민턴</label>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<input type="submit" value="확인">
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
</body>
</html>
requestTest01
package kr.or.ddit.basic.reqreusp;
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 requestTest01
*/
@WebServlet("/requestTest01.do")
public class requestTest01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//클라이언트가 보내온 데이터를 가져오기
//post방식으로 전송되어 온 데이터의 인코딩 방식 설명
request.setCharacterEncoding("utf-8");
//request.getParameter("파마미터명");
// ==> 해당 '파라미터명'에 설정된 '값'을 문자열로 가져온다.
// http://localhost/servletTest/서블릿URL패턴?파라미터명=값&파마리터명=값
String userName = request.getParameter("username");
String job = request.getParameter("job");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html><head><meta charset='utf-8'>");
out.println("<title>Request객체로 전송값 구하기</title></head>");
out.println("<body>");
out.println("<h2>클라이언트가 보내온 값</h2>");
out.println("<table border='1'>");
out.println("<tr><td>이름</td>");
out.println("<td>" + userName + "</td></tr>");
out.println("<tr><td>직업</td>");
out.println("<tr>" + job + "</td></tr>");
out.println("</table>");
out.println("</body></html>");
}
}