JavaServletProgramming.PDF

Similar documents
14-Servlet

KYO_SCCD.PDF

I T C o t e n s P r o v i d e r h t t p : / / w w w. h a n b i t b o o k. c o. k r

JavaGeneralProgramming.PDF

chapter6.doc

04장

2장 변수와 프로시저 작성하기

rmi_박준용_final.PDF

12-file.key

歯JavaExceptionHandling.PDF

Microsoft PowerPoint - 7강.pptx

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D D382E687770>

서블릿의라이프사이클 뇌를자극하는 JSP & Servlet

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

자바-11장N'1-502

API STORE 키발급및 API 사용가이드 Document Information 문서명 : API STORE 언어별 Client 사용가이드작성자 : 작성일 : 업무영역 : 버전 : 1 st Draft. 서브시스템 : 문서번호 : 단계 : Docum

J2EE Concepts

뇌를 자극하는 JSP & Servlet 슬라이드

01-OOPConcepts(2).PDF

Microsoft PowerPoint - 04-UDP Programming.ppt

02 C h a p t e r Java

ilist.add(new Integer(1))과 같이 사용하지 않고 ilist.add(1)과 같이 사용한 것은 자바 5.0에 추가된 기본 자료형과 해당 객체 자료 형과의 오토박싱/언박싱 기능을 사용한 것으로 오토박싱이란 자바 컴파일러가 객체를 요구하는 곳에 기본 자료형

뇌를 자극하는 JSP & Servlet 슬라이드

JMF2_심빈구.PDF

웹 개발자를 위한 서블릿/JSP

JMF3_심빈구.PDF

Data Provisioning Services for mobile clients

3ÆÄÆ®-14

1217 WebTrafMon II

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

Interstage5 SOAP서비스 설정 가이드

혼자서일을다하는 JSP. 이젠일을 Servlet 과나눠서한다. JSP와서블릿의표현적인차이 - JSP는 <html> 내에서자바를사용할수있는수단을제공한다. - 서블릿은자바내에서 <html> 을작성할수있는수단을제공한다. - JSP나서블릿으로만웹페이지를작성하면자바와다양한코드가

untitled

11 템플릿적용 - Java Program Performance Tuning (김명호기술이사)

CD-RW_Advanced.PDF

교육2 ? 그림

Microsoft PowerPoint - aj-lecture3.ppt [호환 모드]

<param-value> 파라미터의값 </param-value> </init-param> </servlet> <servlet-mapping> <url-pattern>/ 매핑문자열 </url-pattern> </servlet-mapping> - 위의예에서 ServletC

07 자바의 다양한 클래스.key

신림프로그래머_클린코드.key

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Remote UI Guide

Microsoft PowerPoint - aj-lecture7.ppt [호환 모드]

NoSQL

Microsoft PowerPoint - 03-TCP Programming.ppt

뇌를 자극하는 JSP & Servlet 슬라이드

09-interface.key

SRC PLUS 제어기 MANUAL

chapter3.doc

JAVA Bean & Session - Cookie

JSP 의내장객체 response 객체 - response 객체는 JSP 페이지의실행결과를웹프라우저로돌려줄때사용되는객체이다. - 이객체는주로켄텐츠타입이나문자셋등의데이터의부가정보 ( 헤더정보 ) 나쿠키 ( 다음에설명 ) 등을지정할수있다. - 이객체를사용해서출력의방향을다른

3장

Java Agent Plugin Guide

다른 JSP 페이지호출 forward() 메서드 - 하나의 JSP 페이지실행이끝나고다른 JSP 페이지를호출할때사용한다. 예 ) <% RequestDispatcher dispatcher = request.getrequestdispatcher(" 실행할페이지.jsp");

MasoJava4_Dongbin.PDF

Eclipse 와 Firefox 를이용한 Javascript 개발 발표자 : 문경대 11 년 10 월 26 일수요일

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Java

T100MD+

13-Java Network Programming

IBM blue-and-white template

Page 2 of 6 Here are the rules for conjugating Whether (or not) and If when using a Descriptive Verb. The only difference here from Action Verbs is wh

ORANGE FOR ORACLE V4.0 INSTALLATION GUIDE (Online Upgrade) ORANGE CONFIGURATION ADMIN O

<4D F736F F F696E74202D20C1A63235C0E520B3D7C6AEBFF6C5A920C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

歯Writing_Enterprise_Applications_2_JunoYoon.PDF

Contents Contents 2 1 Abstract 3 2 Infer Checkers Eradicate Infer....

Data Provisioning Services for mobile clients

슬라이드 1

05-class.key

1

PHP & ASP

뇌를 자극하는 JSP & Servlet 슬라이드

13주-14주proc.PDF

PowerPoint 프레젠테이션

thesis-shk

휠세미나3 ver0.4

0. 들어가기 전


PWR PWR HDD HDD USB USB Quick Network Setup Guide xdsl/cable Modem PC DVR 1~3 1.. DVR DVR IP xdsl Cable xdsl Cable PC PC DDNS (

untitled

Mobile Service > IAP > Android SDK [ ] IAP SDK TOAST SDK. IAP SDK. Android Studio IDE Android SDK Version (API Level 10). Name Reference V

SMB_ICMP_UDP(huichang).PDF

USB USB DV25 DV25 REC SRN-475S REC SRN-475S LAN POWER LAN POWER Quick Network Setup Guide xdsl/cable Modem PC DVR 1~3 1.. DVR DVR IP xdsl Cable xdsl C

Modern Javascript

LXR 설치 및 사용법.doc

<4D F736F F F696E74202D20B5A5C0CCC5CDBAA3C0CCBDBA5F3130C1D6C2F75F31C2F7BDC32E >

Chap12

목차 BUG offline replicator 에서유효하지않은로그를읽을경우비정상종료할수있다... 3 BUG 각 partition 이서로다른 tablespace 를가지고, column type 이 CLOB 이며, 해당 table 을 truncate

PowerPoint 프레젠테이션

목차 INDEX JSON? - JSON 개요 - JSONObject - JSONArray 서울시공공데이터 API 살펴보기 - 요청인자살펴보기 - Result Code - 출력값 HttpClient - HttpHelper 클래스작성 - JSONParser 클래스작성 공공

Cluster management software

5장.key

PowerPoint 프레젠테이션

Polly_with_Serverless_HOL_hyouk

fundamentalOfCommandPattern_calmglow_pattern_jstorm_1.0_f…

PowerPoint Presentation

Hi-MO 애프터케어 시스템 편 5. 오비맥주 카스 카스 후레쉬 테이블 맥주는 천연식품이다 편 처음 스타일 그대로, 부탁 케어~ Hi-MO 애프터케어 시스템 지속적인 모발 관리로 끝까지 스타일이 유지되도록 독보적이다! 근데 그거 아세요? 맥주도 인공첨가물이

10주차.key

Transcription:

(1999 10 ) from Yongwoo s Park Java Servlet Programming from Yongwoo s Park 1

Java Servlet Programming from Yongwoo s Park 2

(SERVLET) 4 11 (GENERICSERVLET ) 4 111 112 113 114 115 116 117 118 119 Servlet 4 GenericServlet 5 ServletRequest 7 ServletResponse 9 ServletInputStream 9 ServletOutputStream 10 (GenericServlet) 11 ServletConfig 14 ServletContext 14 12 HTTP (HTTPSERVLET )18 121 122 123 124 HttpServlet 18 HttpServletRequest 19 HttpServletResponse 20 HTTP 24 13 38 131 132 133 134 135 136 Cookie 38 HttpSession 44 HttpSessionBindingListener 45 HttpSessionBindingEvent 45 46 HttpUtils 54 14 55 141 142 55 SMTP(Send Mail Transfer Protocol) 59 Java Servlet Programming from Yongwoo s Park 3

from Yongwoo s Park javalangobject javaioinputstream javaxservletgenericservlet javaiooutputstream javaxservletservletinputstream javaxservletservletoutputstream javaxservletservlet javaxservletservletconfig javaxservletservletcontext javaxservletservletrequest javaxservletservletresponse javaxservletrequestdispatcher javaxservletsinglethreadmodel 1 javaxservlet HTTP(Hyper-Text Transfer Protocol),, Servlet, javaxservletgenericservlet (generic Servlet) javaxservlethttphttpservlet HTTP Servlet, (life-cycle), :, init Java Servlet Programming from Yongwoo s Park 4

: :, destroy,, finalize interface Servlet { WWW Request Response init(config) service(req, res) destroy() Load MyServletclass getservletconfig() getservletinfo() Unload 2,, (startup) getservletconfig (author), (version), (copyright) getservletinfo Servlet, void init(servletconfig config):,, void service(servletrequest req, ServletResponse res): void destroy():, ServletConfig getservletconfig(): / ServletConfig javalangstring getservletinfo(): (author), (version), (copyright) Java Servlet Programming from Yongwoo s Park 5

GenericServlet, (Web site) HTTP, HttpServlet GenericServlet Servlet ServletConfig, GenericServlet HttpServlet, GenericServlet HttpServlet, Servlet GenericServlet init destroy (lifecycle) ServletConfig,, GenericServlet ServletContext log, MyServlet extends GenericServlet { Request ServletRequest req WWW WWW ServletResponse res Response ServletInputStream ServletOutputStream service(req, res) init(config) destroy() 3, getservletinfo, - (sevlet-wide) init destroy GenericServlet, void init(): void init(servletconfig config):,, abstract void service(servletrequest req, ServletResponse res):, GenericServlet Java Servlet Programming from Yongwoo s Park 6

void destroy():, javalangstring getinitparameter(javalangstring name): javautilenumeration getinitparameternames(): enumeration ServletConfig getservletconfig(): / ServletConfig ServletContext getservletcontext(): ServletContext javalangstring getservletinfo(): (author), (version), (copyright) void log(javalangstring msg): void log(javalangstring message, javalangthrowable t): ServletRequest, ServletRequest, HttpServletRequest HTTP MIME, MIME, MIME, getreader, getinpuetstream, Multipart MIME Java Servlet Programming from Yongwoo s Park 7

ServletRequest, javautilenumeration getattributenames(): Enumeration javalangobject getattribute(javalangstring name) : void setattribute(javalangstring key, javalangobject o): javalangstring getcharacterencoding(): int getcontentlength():, 1 javalangstring getcontenttype(): MIME null javautilenumeration getparameternames(): Enumeration javalangstring getparameter(javalangstring name): javalangstring[] getparametervalues(javalangstring name): (list) (choicebox), javaiobufferedreader getreader(): BufferedReader ServletInputStream getinputstream():, ServletInputStream javalangstring getprotocol(): HTTP/11 major/minor javalangstring getremoteaddr(): IP(Internet Protocol) javalangstring getremotehost(): javalangstring getscheme(): http, https, ftp javalangstring getservername(): int getserverport(): javalangstring getrealpath(javalangstring path): API 21 ServletContextgetRealPath(javalangString) Java Servlet Programming from Yongwoo s Park 8

ServletResponse, MIME, ServletResponse, ServletResponse service ServletRequest, MIME ServletResponse getoutputstream ServletOutputStream, MIME getwriter PrintWriter, ServletResponse, javalangstring getcharacterencoding(): MIME ServletOutputStream getoutputstream(): ServletOutputStream javaioprintwriter getwriter(): PrintWriter void setcontentlength(int len): void setcontenttype(javalangstring type): ServletInputStream readline, (input stream) HTTP POST PUT ServletInputStream, ServletRequestgetInputStream ServletInputStream ServletInputStream, service, ServletInputStream Java Servlet Programming from Yongwoo s Park 9 ServletOutputStream service

, ServletInputStream javaioinputstreamread ServletInputStream, int readline(byte[] b, int off, int len):, 1 ServletOutputStream, (output stream) ServletInputStream ServletResponsegetOutputStream ServletOutputStream ServletInputStream ServletOutputStream,, ServletOutputStream, javaiooutputstream write(int) ServletOutputStream, void print(boolean b): b void print(char c): c void print(double d): d void print(float f): f void print(int i): i void print(long l): l void print(javalangstring s): s void println(): CRLF(carriage return-line feed) void println(boolean b): b CRLF void println(char c): c CRLF void println(double d): d CRLF void println(float f): f CRLF void println(int i): i CRLF void println(long l): l CRLF void println(javalangstring s): s CRLF Java Servlet Programming from Yongwoo s Park 10

, Setvlet GenericServlet, init, service, destroy, getservletinfo getservletconfig javaappletapplet, init, start, stop, destroy, paint, getappletinfo, (GenericServlet) import javaio*; import javautilenumeration; import javaxservlet*; public class HelloGenericServlet extends GenericServlet { static String initialname; public void init(servletconfig config) throws ServletException { superinit(config); initialname=configgetinitparameter("name"); public void service(servletrequest req, ServletResponse res) throws ServletException, IOExc eption { PrintWriter out=resgetwriter(); String name=reqgetparameter("name"); outprintln("hello, "+initialname+":init, "+name+":req"); outprintln("attribute names in this request:"); Enumeration e = reqgetattributenames(); while(ehasmoreelements()) { String key =(String)enextElement(); Object value = reqgetattribute(key); outprintln(" " + key + " = " + value); outprintln(); outprintln(" Protocol: " + reqgetprotocol()); outprintln(" Scheme: " + reqgetscheme()); outprintln(" Server Name: " + reqgetservername()); outprintln(" Server Port: " + reqgetserverport()); outprintln(" Remote Addr: " + reqgetremoteaddr()); outprintln(" Remote Host: " + reqgetremotehost()); outprintln("character Encoding: " + reqgetcharacterencoding()); outprintln(" Content Length: " + reqgetcontentlength()); outprintln(" Content Type: " + reqgetcontenttype()); Java Servlet Programming from Yongwoo s Park 11

outprintln(); outprintln("parameter names in this request"); e = reqgetparameternames(); while(ehasmoreelements()) { String key =(String)enextElement(); String[] values = reqgetparametervalues(key); outprint(" " + key + " = "); for(int i=0;i<valueslength;i++) { outprint(values[i] + " "); outprintln(); /* * File: d:\java\jsdk21\webpages\web-inf\servletsproperties hellocode=hellogenericservlet helloinitparams=name=yongwoo's Park */ < 1 HelloGenericServletjava>,,, HTML Java Servlet Programming from Yongwoo s Park 12

HTML (GenericServlet) HTML import javaio*; import javautilenumeration; import javaxservlet*; public class HelloGenericServlet2 extends GenericServlet { public void service(servletrequest req, ServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html; charset=euc-kr"); PrintWriter out=resgetwriter(); String name=reqgetparameter("name"); outprintln("<html>"); outprintln("<head><title>hello, "+name+"</title></head>"); outprintln("<body>"); outprintln("<h1>hello, "+name+"</h1>"); outprintln("<h2> "+reqgetparameter(" ")+" </H2>"); outprintln("</body>"); outprintln("</html>"); /* * File: d:\java\jsdk21\webpages\web-inf\servletsproperties hello2code=hellogenericservlet2 hello2initparams= */ < 2 HelloGenericServlet2java> Java Servlet Programming from Yongwoo s Park 13

ServletResponse setcontenttype, ( ) MIME text/html, HTML Content Type: text/html; charset=euc-kr, MIME, ISO- 8859-1, name/value, ServletContext ServletConfig, javalangstring getinitparameter(javalangstring name): name/value, javautilenumeration getinitparameternames(): Enumeration ServletContext getservletcontext(): ServletContext MIME Java Servlet Programming from Yongwoo s Park 14

, ServletContext, ServletConfiggetServletContext () ServletContext, (multiple) (virtual), ServletContext ServletContext ServletConfig, ServletgetServletConfig ServletConfig ServletContext, javalangobject getattribute(javalangstring name): javautilenumeration getattributenames(): Enumeration void removeattribute(javalangstring name): (contect) void setattribute(javalangstring name, javalangobject object): (contect) ServletContext getcontext(javalangstring uripath): URL ServletContext int getmajorversion(): API major version int getminorversion(): API minor version javalangstring getmimetype(javalangstring file): MIME javalangstring getrealpath(javalangstring path): RequestDispatcher getrequestdispatcher(javalangstring urlpath): wrapper RequestDispatcher javaneturl getresource(javalangstring path): javaioinputstream getresourceasstream(javalangstring path): javautilenumeration getservlets(): API 20 void log(javalangexception exception, javalangstring msg) : API 21 log(string message, Throwable throwable) void log(javalangstring msg): void log(javalangstring message, javalangthrowable throwable): Java Servlet Programming from Yongwoo s Park 15

javalangstring getserverinfo(): Servlet getservlet(javalangstring name): API 21 javautilenumeration getservletnames(): API 21 (GenericServlet) /* $Id: SnoopServletjava,v 11 1999/03/17 01:17:20 duncan Exp $ * */ import javaioioexception; import javautilenumeration; import javaxservlet*; import javaxservlethttp*; /** * @author James Duncan Davidson <duncan@engsuncom> */ public class SnoopGenericServlet extends GenericServlet { public void service(servletrequest req, ServletResponse res) throws ServletException, IOException { ServletConfig config = getservletconfig(); ServletOutputStream out = resgetoutputstream(); ressetcontenttype("text/html; charset=8859-1"); outprintln("<html>"); outprintln("<head><title>generic Snoop Servlet</title></head>"); outprintln("<body>"); outprintln("<h3>generic Snoop Servlet</H3><br>"); outprintln("init Parameters<br>"); Enumeration e = configgetinitparameternames(); while(ehasmoreelements()) { String key =(String)enextElement(); String value = configgetinitparameter(key); outprintln("\t" + key + " = " + value + "\t"); outprintln("<br>"); outprintln("server Info:"+getServletConfig()getServletContext()getServerInfo()); outprintln("<br>"); outprintln("context attributes:"); ServletContext context = configgetservletcontext(); e = contextgetattributenames(); while(ehasmoreelements()) { String key =(String)enextElement(); Object value = contextgetattribute(key); Java Servlet Programming from Yongwoo s Park 16

outprintln("\t" + key + " = " + value + "<br>"); outprintln("java Server: "+contextgetmajorversion()+""+contextgetminorversion()); outprintln("<br>"); outprintln("attributes<br>"); e = reqgetattributenames(); while(ehasmoreelements()) { String key =(String)enextElement(); Object value = reqgetattribute(key); outprintln("\t" + key + " = " + value + "<br>"); outprintln("<br>"); /* * outprintln("parameters<br>"); e = reqgetparameternames(); while(ehasmoreelements()) { String key =(String)enextElement(); String[] values = reqgetparametervalues(key); outprint("\t" + key + " = "); for(int i=0;i<valueslength;i++) { outprint(values[i] + " "); outprintln("<br>"); outprintln("</body>"); outprintln("</html>"); # $Id: servletsproperties,v 12 1999/04/02 02:04:22 duncan Exp $ snoop2code=snoopgenericservlet snoop2initparams=initarg1=foo,initarg2=bar */ Java Servlet Programming from Yongwoo s Park 17

< 3 SnoopGenericServletjava> javalangobject javaioinputstream javaxservletgenericservlet javaiooutputstream javaxservletservletinputstream javaxservletservletoutputstream javaxservletservlet javaxservletservletconfig javaxservletservletcontext javaxservletservletrequest javaxservletservletresponse javaxservletrequestdispatcher javaxservletsinglethreadmodel 4 javaxservlethttp HttpServlet HTTP HTTP,, HttpServlet doget : HTTP GET dopost : HTTP POST doput : HTTP PUT dodelete : HTTP DELETE init destroy :, init, destroy getservletinfo: Java Servlet Programming from Yongwoo s Park 18

GET Request MyServlet extends HttpServlet { Response POST Request Response PUT Request Response WWW HttpServletRequest req HttpServletResponse res doget(req, res) dopost(req, res) doput(req, res) dodelete(req, res) ServletInputStream service( ) ServletOutputStream 5 HTTP ServletRequest HttpServletRequest HTTP HTTP HTTP HttpServlet service HttpServletRequest HttpServletRequest HTTP, javalangstring getauthtype(): (authentication scheme), "BASIC" "SSL" Cookie[] getcookies(): long getdateheader(javalangstring name): Date long javalangstring getheader(javalangstring name): javautilenumeration getheadernames(): Enumeration int getintheader(javalangstring name): javalangstring getmethod(): GET, POST, PUT, DELETE (request method) Java Servlet Programming from Yongwoo s Park 19

javalangstring getpathinfo(): URL javalangstring getpathtranslated(): servlet (query string), javalangstring getquerystring(): javalangstring getremoteuser():, HTTP (authentication), javalangstring getrequestedsessionid(): (session) ID javalangstring getrequesturi(): HTTP URL javalangstring getservletpath(): URL HttpSession getsession():, HttpSession getsession(boolean create):, create boolean isrequestedsessionidfromcookie(): ID boolean isrequestedsessionidfromurl(): API 21 isrequestedsessionidfromurl() boolean isrequestedsessionidfromurl(): ID URL boolean isrequestedsessionidvalid(): HttpSessionContext HTTP HTTP HttpServletResponse HttpServletResponse service HTTP,, HTTP HttpServletResponse, HttpServletResponse, void addcookie(cookie cookie): Java Servlet Programming from Yongwoo s Park 20

boolean containsheader(javalangstring name): javalangstring encoderedirecturl(javalangstring url): encoderedirecturl(string url) javalangstring encoderedirecturl(javalangstring url): URL sendredirect javalangstring encodeurl(javalangstring url) : encodeurl(string url) javalangstring encodeurl(javalangstring url): URL ID void senderror(int sc): void senderror(int sc, javalangstring msg): void sendredirect(javalangstring location): URL void setdateheader(javalangstring name, long date): void setheader(javalangstring name, javalangstring value) : void setintheader(javalangstring name, int value): void setstatus(int sc): void setstatus(int sc, javalangstring sm): HTTP (GenericServlet) GET POST, import javaio*; import javaxservlet*; import javaxservlethttp*; public class HelloHttpServlet extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws IOException, ServletException { ressetcontenttype("text/html; charset=euc-kr"); PrintWriter out = resgetwriter(); Java Servlet Programming from Yongwoo s Park 21

outprintln("<html>"); outprintln("<body>"); outprintln("<head>"); outprintln("<title>hello</title>"); outprintln("</head>"); outprintln("<body>"); outprintln("<h1> "+reqgetparameter("name")+"!</h1>"); outprintln("<h3> "+reqgetparameter("job")+" </H3>"); outprintln("</body>"); outprintln("</html>"); public void dopost(httpservletrequest req, HttpServletResponse res) throws IOException, ServletException { ressetcontenttype("text/html; charset=euc-kr"); PrintWriter out = resgetwriter(); outprintln("<html>"); outprintln("<body>"); outprintln("<head>"); outprintln("<title>hello</title>"); outprintln("</head>"); outprintln("<body>"); outprintln("<h1> "+toksc5601(reqgetparameter("name"))+"!</h1>"); outprintln("<h3> "+toksc5601(reqgetparameter("job"))+" </H3>"); outprintln("</body>"); outprintln("</html>"); public static String toksc5601(string str) throws UnsupportedEncodingException { if(str == null) { return(null); return(new String(strgetBytes("8859_1"), "KSC5601")); /* * 1) GET 1) POST Java Servlet Programming from Yongwoo s Park 22

*/ < 4 HelloHttpServletjava>, HTTP (GenericServlet) POST HTML <HTML> <HEAD> <META http-equiv="content-type" content="text/html; charset=euc-kr"> <TITLE>Form Test</TITLE> </HEAD> <BODY> <H1>POST </H1> <P> <FORM action="http://park:8080/servlet/hellohttpservlet" method="post"> : <input type="text" name="name" size=16><br> : <input type="text" name="job" size=40><br> <input type="submit" value=" "> </FORM> </BODY> </HTML> /* * */ Java Servlet Programming from Yongwoo s Park 23

< 5 HelloHttpServlethtml> HTTP,, HTML, HTML HTTP HTML <HTML> <HEAD> <TITLE>File Upload</TITLE> </HEAD> <BODY> <H1> </H1> <P> <FORM method="post" action="http://parkkonkukackr:8080/servlet/fileuploadechoservlet" enctype=multipart/form-data> : <input type="text" name="name" size=16><br> : <input type="file" name="binary"><br> <input type="submit" value=" "> </FORM> </BODY> </HTML> /* * */ < 6 FileUploadEchoServlethtml> Java Servlet Programming from Yongwoo s Park 24

, <FORM> <FORM> method="post" POST, GET, POST action="http://parkkonkukackr:8080/servlet/fileuploadechoservlet" enctype=multipart/form-data,, multipart/form-data : <input type="file" name="binary"> - input file,, HTML, HTTP, HTTP import javaio*; import javautil*; import javaxservlet*; import javaxservlethttp*; public class FileUploadEchoServlet extends HttpServlet { public void dopost(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html; charset=euc-kr"); PrintWriter out = resgetwriter(); outprintln("<html>"); outprintln("<body>"); outprintln("<head>"); outprintln("<title>file Upload Result</TITLE>"); outprintln("</head>"); outprintln("<body>"); outprintln("<h2> </H2>"); outprintln(" Content type: ["+reqgetcontenttype()+"]<br>"); outprintln("content length: ["+reqgetcontentlength()+"]<br>"); Java Servlet Programming from Yongwoo s Park 25

InputStreamReader isr = new InputStreamReader(reqgetInputStream(), "EUC-KR"); BufferedReader br = new BufferedReader(isr); for(string line;(line=brreadline())!=null;) { outprintln(line+"<br>"); outclose(); /* * outprintln("</body>"); outprintln("</html>"); */ < 7 FileUploadEchoServletjava>,, HTML, HTTP, HTTP HTML HTML <HTML> <BODY> <HEAD> <TITLE>File Upload Result</TITLE> </HEAD> <BODY> Java Servlet Programming from Yongwoo s Park 26

<H2> </H2> Content type: [multipart/form-data; boundary=--------------------------- 7cfc2164e07da]<BR> Content length: [10558]<BR> -----------------------------7cfc2164e07da<BR> Content-Disposition: form-data; name="name"<br> <BR> <BR> -----------------------------7cfc2164e07da<BR> Content-Disposition: form-data; name="binary"; filename="d:\temp\bigpenguingif"<br> Content-Type: image/gif<br> <BR> -----------------------------7cf1124e07da--<BR> 6, HTML,, Content Type reqgetcontenttype MIME, MIME multipart/form-data?? multipart/form-data; boundary=---------------------------7cfc2164e07da -----------------------------7cf1124e07da enctype=multipart/form-data (name) (binary), Content-Disposition: (name= ), (filename= ), MIME,,?? Content-Disposition: form-data; name="name" (name),, name name?? Content-Disposition: form-data; name="binary"; filename="d:\temp \bigpenguingif" (ninary), name binary, Java Servlet Programming from Yongwoo s Park 27

filename "D:\Temp\bigpenguingif"?? Content-Type: image/gif MIME MIME image/gif,,, -----------------------------7cf1124e07da-- -, ID --,, HTTP HTML HTTP HTML <HTML> <HEAD> <TITLE>File Upload</TITLE> </HEAD> <BODY> <H1> </H1> <P> <FORM method="post" action="http://parkkonkukackr:8080/servlet/ FileUploadServlet " enctype=multipart/form-data> : <input type="text" name="name" size=16><br> : <input type="file" name="binary"><br> <input type="submit" value=" "> </FORM> </BODY> </HTML> /* * Java Servlet Programming from Yongwoo s Park 28

*/ < 8 FileUploadServlethtml> import javaio*; import javautil*; import javaxservlet*; import javaxservlethttp*; public class FileUploadServlet extends HttpServlet { public void dopost(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html; charset=euc-kr"); PrintWriter out = resgetwriter(); /* OutputStreamWriter osw = new OutputStreamWriter(resgetOutputStream(); PrintWriter out = new PrintWriter(osw, "KSC5601") ); */ try { MultipartRequest multi = new MultipartRequest(req, "", 5*1024*1024); outprintln("<html>"); outprintln("<head><title>file Upload</TITLE></HEAD>"); outprintln("<body>"); outprintln("<h1> </H1>"); outprintln("<h3>params:</h3>"); outprintln("<pre>"); Enumeration params = multigetparameternames(); while(paramshasmoreelements()) { String name = (String)paramsnextElement(); String value = multigetparameter(name); outprintln(name + " = " + value); outprintln("</pre>"); outprintln("<h3>files:</h3>"); outprintln("<pre>"); Enumeration files = multigetfilenames(); while(fileshasmoreelements()) { Java Servlet Programming from Yongwoo s Park 29

String name = (String)filesnextElement(); String filename = multigetfilesystemname(name); String type = multigetcontenttype(name); File f = multigetfile(name); outprintln("name: " + name); outprintln("filename: " + filename); outprintln("type: " + type); if(f!= null) { outprintln("length: " + flength()); outprintln(); outprintln("</pre>"); catch(exception e) { outprintln("<pre>"); eprintstacktrace(out); outprintln("</pre>"); outprintln("</body></html>"); /* * */ < 9 FileUploadServletjava> import javaio*; import javautil*; import javaxservlet*; public class MultipartRequest { Java Servlet Programming from Yongwoo s Park 30

private static final int DEFAULT_MAX_POST_SIZE=1024*1024; // 1 Mega private ServletRequest req; private File dir; private int maxlen; private Hashtable parameters = new Hashtable(); // name - value private Hashtable files = new Hashtable(); // name - UploadedFile public MultipartRequest(ServletRequest req, String uploaddir) throws IOException { this(req, uploaddir, DEFAULT_MAX_POST_SIZE); public MultipartRequest(ServletRequest req, String uploaddir, int maxlen) throws IOException { // Sanity check values if(req == null) { throw new IllegalArgumentException("request cannot be null"); if(uploaddir == null) { throw new IllegalArgumentException("saveDirectory cannot be null"); if(maxlen <= 0) { throw new IllegalArgumentException("maxPostSize must be positive"); // Save the request, dir, and max size thisreq = req; dir = new File(uploadDir); thismaxlen = maxlen; // Check savedirectory is truly a directory if(!dirisdirectory()) { throw new IllegalArgumentException("Not a directory: " + uploaddir); // Check savedirectory is writable if(!dircanwrite()) { throw new IllegalArgumentException("Not writable: " + uploaddir); // Now parse the request saving data to "parameters" and "files"; // write the file contents to the savedirectory readrequest(); public Enumeration getparameternames() { return parameterskeys(); public Enumeration getfilenames() { return fileskeys(); public String getparameter(string name) { try { String param =(String)parametersget(name); if(""equals(param)) { return(null); return(param); catch(exception e) { return(null); Java Servlet Programming from Yongwoo s Park 31

public String getfilesystemname(string name) { try { UploadedFile file =(UploadedFile)filesget(name); return(filegetfilesystemname()); // may be null catch(exception e) { return null; public String getcontenttype(string name) { try { UploadedFile file =(UploadedFile)filesget(name); return(filegetcontenttype()); // may be null catch(exception e) { return(null); public File getfile(string name) { try { UploadedFile file =(UploadedFile)filesget(name); return(filegetfile()); // may be null catch(exception e) { return(null); protected void readrequest() throws IOException { String type = reqgetcontenttype(); if((type == null) (!typetolowercase()startswith("multipart/form-data"))) { throw new IOException("Posted content type isn't multipart/form-data"); // Check the content length to prevent denial of service attacks int len = reqgetcontentlength(); if(len > maxlen) { throw new IOException("Content length: "+len+", Limit: "+maxlen); // Get the boundary string; it's included in the content type // Should look something like "------------------------12012133613061" String boundary = extractboundary(type); if(boundary == null) { throw new IOException("Separation boundary was not specified"); // Construct the special input stream we'll read from MultipartInputStreamHandler in = new MultipartInputStreamHandler(reqgetInputStream(), boundary, len); // Read the first line, should be the first boundary String line = inreadline(); if(line == null) { throw new IOException("Corrupt form data: premature ending"); Java Servlet Programming from Yongwoo s Park 32

// Verify that the line is the boundary if(!linestartswith(boundary)) { throw new IOException("Corrupt form data: no leading boundary"); // Now that we're just beyond the first boundary, loop over each part boolean done = false; while(!done) { done = readnextpart(in, boundary); protected boolean readnextpart(multipartinputstreamhandler in, String boundary) throws IOException { // Read the first line, should look like this: // content-disposition: form-data; name="field1"; filename="file1txt" String line = inreadline(); if(line == null) { // No parts left, we're done return(true); // Parse the content-disposition line String[] dispinfo = extractdispositioninfo(line); String disposition = dispinfo[0]; String name = dispinfo[1]; String filename = dispinfo[2]; // Now onto the next line This will either be empty // or contain a Content-Type and then an empty line line = inreadline(); if(line == null) { // No parts left, we're done return(true); // Get the content type, or null if none specified String contenttype = extractcontenttype(line); if(contenttype!= null) { // Eat the empty line line = inreadline(); if((line == null) (linelength() > 0)) { // line should be empty throw new IOException("Malformed line after content type: " + line); else { // Assume a default content type contenttype = "application/octet-stream"; // Now, finally, we read the content(end after reading the boundary) if(filename == null) { // This is a parameter String value = readparameter(in, boundary); parametersput(name, value); else { // This is a file readandsavefile(in, boundary, filename); if("unknown"equals(filename)) { filesput(name, new UploadedFile(null, null, null)); else { filesput(name, new UploadedFile(dirtoString(), filename, contenttype)); Java Servlet Programming from Yongwoo s Park 33

return(false); // there's more to read protected String readparameter(multipartinputstreamhandler in, String boundary) throws IOException { StringBuffer sbuf = new StringBuffer(); String line; while((line = inreadline())!= null) { if(linestartswith(boundary)) { break; sbufappend(line + "\r\n"); // add the \r\n in case there are many lines if(sbuflength() == 0) { return(null); // nothing read sbufsetlength(sbuflength() - 2); // cut off the last line's \r\n return(sbuftostring()); // no URL decoding needed protected void readandsavefile(multipartinputstreamhandler in, String boundary, String filename) throws IOException { File f = new File(dir + Fileseparator + filename); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream out = new BufferedOutputStream(fos, 8 * 1024); // 8K byte[] bbuf = new byte[100*1024]; // 100K int result; String line; // ServletInputStreamreadLine() has the annoying habit of // adding a \r\n to the end of the last line // Since we want a byte-for-byte transfer, we have to cut those chars boolean rnflag = false; while((result = inreadline(bbuf, 0, bbuflength))!= -1) { // Check for boundary if(result > 2 && bbuf[0] == '-' && bbuf[1] == '-') { // quick pre-check line = new String(bbuf, 0, result, "ISO-8859-1"); if(linestartswith(boundary)) { break; // Are we supposed to write \r\n for the last iteration? if(rnflag) { outwrite('\r'); outwrite('\n'); rnflag = false; // Write the buffer, postpone any ending \r\n if((result>=2)&&(bbuf[result-2]=='\r')&&(bbuf[result-1]=='\n')) { outwrite(bbuf, 0, result - 2); // skip the last 2 chars rnflag = true; // make a note to write them on the next iteration else { outwrite(bbuf, 0, result); outflush(); Java Servlet Programming from Yongwoo s Park 34

outclose(); fosclose(); // Extracts and returns the boundary token from a line // private String extractboundary(string line) { int index = lineindexof("boundary="); if(index == -1) { return null; String boundary = linesubstring(index + 9); // 9 for "boundary=" // The real boundary is always preceeded by an extra "--" boundary = "--" + boundary; return boundary; // Extracts and returns disposition info from a line, as a String array // with elements: disposition, name, filename Throws an IOException // if the line is malformatted // private String[] extractdispositioninfo(string line) throws IOException { // Return the line's data as an array: disposition, name, filename String[] retval = new String[3]; // Convert the line to a lowercase string without the ending \r\n // Keep the original line for error messages and for variable names String origline = line; line = origlinetolowercase(); // Get the content disposition, should be "form-data" int start = lineindexof("content-disposition: "); int end = lineindexof(";"); if(start == -1 end == -1) { throw new IOException("Content disposition corrupt: " + origline); String disposition = linesubstring(start + 21, end); if(!dispositionequals("form-data")) { throw new IOException("Invalid content disposition: " + disposition); // Get the field name start = lineindexof("name=\"", end); // start at last semicolon end = lineindexof("\"", start + 7); // skip name=\" if(start == -1 end == -1) { throw new IOException("Content disposition corrupt: " + origline); String name = origlinesubstring(start + 6, end); // Get the filename, if given String filename = null; start = lineindexof("filename=\"", end + 2); // start after name end = lineindexof("\"", start + 10); // skip filename=\" if(start!= -1 && end!= -1) { // note the!= filename = origlinesubstring(start + 10, end); // The filename may contain a full path Cut to just the filename int slash = Mathmax(filenamelastIndexOf('/'), filenamelastindexof('\\')); if(slash > -1) { filename = filenamesubstring(slash + 1); // past last slash Java Servlet Programming from Yongwoo s Park 35

if(""equals(filename)) { filename = "unknown"; // sanity check // Return a String array: disposition, name, filename retval[0] = disposition; retval[1] = name; retval[2] = filename; return(retval); // Extracts and returns the content type from a line, or null if the // line was empty Throws an IOException if the line is malformatted // private String extractcontenttype(string line) throws IOException { String contenttype = null; // Convert the line to a lowercase string String origline = line; line = origlinetolowercase(); // Get the content type, if any if(linestartswith("content-type")) { int start = lineindexof(" "); if(start == -1) { throw new IOException("Content type corrupt: " + origline); contenttype = linesubstring(start + 1); else if(linelength()!= 0) { // no content type, so should be empty throw new IOException("Malformed line after disposition: " + origline); return contenttype; // A class to hold information about an uploaded file // class UploadedFile { private String dir; private String filename; private String type; UploadedFile(String dir, String filename, String type) { thisdir = dir; thisfilename = filename; thistype = type; public String getcontenttype() { return(type); public String getfilesystemname() { return(filename); public File getfile() { if(dir == null filename == null) { Java Servlet Programming from Yongwoo s Park 36

return(null); else { return(new File(dir + Fileseparator + filename)); // A class to aid in reading multipart/form-data from a ServletInputStream // It keeps track of how many bytes have been read and detects when the // Content-Length limit has been reached This is necessary since some // servlet engines are slow to notice the end of stream // class MultipartInputStreamHandler { ServletInputStream in; String boundary; int totalexpected; int totalread = 0; byte[] buf = new byte[8 * 1024]; public MultipartInputStreamHandler(ServletInputStream in, String boundary, int totalexpected) { this in = in; thisboundary = boundary; thistotalexpected = totalexpected; // Reads the next line of input Returns null to indicate the end // of stream // public String readline() throws IOException { StringBuffer sbuf = new StringBuffer(); int result; String line; do { result = thisreadline(buf, 0, buflength); // thisreadline() does += if(result!= -1) { sbufappend(new String(buf, 0, result)); //, "ISO-8859-1")); while(result == buflength); // loop only if the buffer was filled if(sbuflength() == 0) { return(null); // nothing read, must be at the end of stream sbufsetlength(sbuflength() - 2); // cut off the trailing \r\n return(sbuftostring()); // A pass-through to ServletInputStreamreadLine() that keeps track // of how many bytes have been read and stops reading when the // Content-Length limit has been reached // public int readline(byte b[], int off, int len) throws IOException { if(totalread >= totalexpected) { return(-1); else { int result = inreadline(b, off, len); if(result > 0) { totalread += result; Java Servlet Programming from Yongwoo s Park 37

return(result); public static String toksc5601(string str) throws UnsupportedEncodingException { if(str == null) { return(null); return(new String(strgetBytes("8859_1"), "KSC5601")); < 10 MultipartRequestjava> Cookie,,,, (commnent), (path and domain qualifiers), (maximum age), (version number) HTTP-Response Header Set-Cookie Cookie, Set-Cookie: NAME=VALUE; expires=date; path=path; domain=domain_name; secure 7, NAME=VALUE, Java Servlet Programming from Yongwoo s Park 38

Set-Cookie: NAME=VALUE; expires=date;,,,,, WINDOW_ROOT\\Profiles\\ ID\\Cookie domain=domain_name;, path=path; Secure, secure SSL, HTTP HttpServletResponse addcookie, HttpServletResponse addcookie HTTP (HTTP response headers) 20, 4KB HTTP (HTTP request headers), HttpServletRequest getcookies Cookie, Netscape 0 RFC 2109 1 0 Cookie, Cookie(javalangString name, javalangstring value): javalangstring getcomment(): javalangstring getdomain(): int getmaxage(): javalangstring getname(): javalangstring getpath(): boolean getsecure(): javalangstring getvalue(): Java Servlet Programming from Yongwoo s Park 39

int getversion(): void setcomment(javalangstring purpose): version 0 void setdomain(javalangstring pattern): void setmaxage(int expiry): void setpath(javalangstring uri): void setsecure(boolean flag): HTTPS SSL void setvalue(javalangstring newvalue): void setversion(int v):,,, <HTML> <HEAD> <META http-equiv="content-type" content="text/html; charset=euc-kr"> <TITLE>Login</TITLE> </HEAD> <BODY> <H1> </H1> <P> <FORM action="http://parkkonkukackr:8080/servlet/loginservlet" method="post"> USER: <input type=text name=user><br> PASS: <input type=password name=pass><br> <input type=submit value="login"> </FORM> </BODY> </HTML> /* * Java Servlet Programming from Yongwoo s Park 40

*/ < 11 Loginhtml> import javaio*; import javautil*; import javaxservlet*; import javaxservlethttp*; public class LoginServlet extends HttpServlet { public void dopost(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html;charset=euc-kr"); PrintWriter out = resgetwriter(); outprintln("<html>"); outprintln("<body>"); outprintln("<head>"); outprintln("<title>login</title>"); outprintln("</head>"); outprintln("<body>"); String user = reqgetparameter("user"); user = new String(usergetBytes("ISO-8859-1"), "EUC-KR"); String pass = reqgetparameter("pass"); if(("park"equals(user)) && ("Park"equals(pass))) { Cookie logincookie = new Cookie("BBS-Park", "Login"); Cookie usercookie = new Cookie("Username", user); resaddcookie(logincookie); resaddcookie(usercookie); outprintln("<h1> </H1><BR>"); outprintln("<a HREF=\"http://parkkonkukackr:8080/servlet/StartServiceServlet\"> "); else { outprintln("<h1> </H1><BR>"); outprintln("<a HREF=\"/Loginhtml\"> "); outprintln("</body>"); outprintln("</html>"); Java Servlet Programming from Yongwoo s Park 41

/* * outclose(); */ < 12 LoginServletjava> import javaio*; import javaxservlet*; import javaxservlethttp*; public class StartServiceServlet extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws IOException, ServletException { ressetcontenttype("text/html; charset=euc-kr"); PrintWriter out = resgetwriter(); outprintln("<html>"); outprintln("<body>"); outprintln("<head>"); outprintln("<title>hello</title>"); outprintln("</head>"); outprintln("<body>"); int match=0; String user = null; boolean login=false; Cookie[] cookies = reqgetcookies(); if(cookies!= null) { for(int i=0;i<cookieslength;i++) { if(("bbs-park"equals(cookies[i]getname())) && ("Login"equals(cookies[i]getValue()))) { login = true; match++; else if("username"equals(cookies[i]getname())) { user = cookies[i]getvalue(); match++; if(match >= 2) { break; Java Servlet Programming from Yongwoo s Park 42

outprintln("<center>"); if(login) { outprintln("<h2> "+user+"!</h2>"); outprintln("<h3> </H3>"); else { outprintln("<h2> </H2><BR>"); outprintln("<a HREF=\"/Loginhtml\"> "); outprintln("</body>"); outprintln("</html>"); /* * public void dopost(httpservletrequest req, HttpServletResponse res) throws IOException, ServletException { doget(req, res); 1) 2) ( http://parkkonkukackr:8080/servlet/startserviceservlet ) */ < 13 LoginServletjava> Java Servlet Programming from Yongwoo s Park 43

, Loginhtml: HTML LoginServletjava: HTML,, StartServiceServletjava:,, HTML,, HttpSession,,,, ( ),,, ( ), HttpSession (session identifier), (creation time ), (session context) HttpSession, javalangstring getid(): ID long getcreationtime(): January 1, 1970 GMT long getlastaccessedtime(): int getmaxinactiveinterval(): Java Servlet Programming from Yongwoo s Park 44

javalangobject getvalue(javalangstring name ): javalangstring[] getvaluenames(): void invalidate():, boolean isnew(): void putvalue(javalangstring name, javalangobject value): void removevalue(javalangstring name): void setmaxinactiveinterval(int interval): HttpSessionBindingListener HttpSessionBindingListener HttpSessionBindingEvent HttpSessionBindingListener void valuebound(httpsessionbindingevent event): void valueunbound(httpsessionbindingevent event): HttpSessionBindingEvent HttpSessionBindingListener, HttpSession putvalue, HttpSession removevalue HttpSessionBindingEvent Java Servlet Programming from Yongwoo s Park 45

, HttpSessionBindingEvent(HttpSession session, javalangstring name): javalangstring getname(): HttpSession getsession(): HTTP HTTP, (persistence),,,, HttpSession,,, HTTP import javaio*; import javautil*; import javaxservlet*; import javaxservlethttp*; public class SessionSnoop extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html;charset=euc-kr"); PrintWriter out = resgetwriter(); HttpSession session = reqgetsession(true); outprintln("<html>"); outprintln("<body>"); outprintln("<head>"); outprintln("<title>session Snoop</TITLE>"); outprintln("</head>"); Java Servlet Programming from Yongwoo s Park 46

outprintln("<body>"); outprintln("<h1>session Snoop</H1>"); Integer count = (Integer)sessiongetValue("SessionSnoopCount"); if(count == null) { count = new Integer(1); else { count = new Integer(countintValue() + 1); sessionputvalue("sessionsnoopcount", count); outprintln(" : "+count+"<br>"); outprintln("<p>"); outprintln("<h3> :</H3>"); String[] names = sessiongetvaluenames(); for(int i=0;i<nameslength;i++) { outprintln(names[i]+": "+sessiongetvalue(names[i])+"<br>"); outprintln("<h3> :</H3>"); outprintln(" ID: " + sessiongetid() + "<BR>"); outprintln(" : " + sessionisnew() + "<BR>"); outprintln(" : " + sessiongetcreationtime()); outprintln("<i>(" + new Date(sessiongetCreationTime()) + ")</I><BR>"); outprintln(" : " + sessiongetlastaccessedtime()); outprintln("<i>(" + new Date(sessiongetLastAccessedTime()) + ")</I><BR>"); outprintln(" ( ): " + reqisrequestedsessionidfromcookie() + "<BR>"); outprintln(" (URL): " + reqisrequestedsessionidfromurl() + "<BR>"); outprintln(" : " + reqisrequestedsessionidvalid() + "<BR>"); outprintln("<a HREF=\""+resencodeURL(reqgetRequestURI())+"\">"); outprintln("url </A>"); /* * outprintln("</body>"); outprintln("</html>"); 1) Java Servlet Programming from Yongwoo s Park 47

*/ < 14 LoginServletjava> HTTP import javaio*; import javautil*; import javaxservlet*; import javaxservlethttp*; public class SessionSnoop extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html;charset=euc-kr"); PrintWriter out = resgetwriter(); HttpSession session = reqgetsession(true); outprintln("<html>"); outprintln("<body>"); outprintln("<head>"); outprintln("<title>session Snoop</TITLE>"); outprintln("</head>"); outprintln("<body>"); outprintln("<h1>session Snoop</H1>"); Integer count = (Integer)sessiongetValue("SessionSnoopCount"); if(count == null) { count = new Integer(1); else { Java Servlet Programming from Yongwoo s Park 48

count = new Integer(countintValue() + 1); sessionputvalue("sessionsnoopcount", count); outprintln(" : "+count+"<br>"); outprintln("<p>"); outprintln("<h3> :</H3>"); String[] names = sessiongetvaluenames(); for(int i=0;i<nameslength;i++) { outprintln(names[i]+": "+sessiongetvalue(names[i])+"<br>"); outprintln("<h3> :</H3>"); outprintln(" ID: " + sessiongetid() + "<BR>"); outprintln(" : " + sessionisnew() + "<BR>"); outprintln(" : " + sessiongetcreationtime()); outprintln("<i>(" + new Date(sessiongetCreationTime()) + ")</I><BR>"); outprintln(" : " + sessiongetlastaccessedtime()); outprintln("<i>(" + new Date(sessiongetLastAccessedTime()) + ")</I><BR>"); outprintln(" ( ): " + reqisrequestedsessionidfromcookie() + "<BR>"); outprintln(" (URL): " + reqisrequestedsessionidfromurl() + "<BR>"); outprintln(" : " + reqisrequestedsessionidvalid() + "<BR>"); outprintln("<a HREF=\""+resencodeURL(reqgetRequestURI())+"\">"); outprintln("url </A>"); /* * outprintln("</body>"); outprintln("</html>"); 1) Java Servlet Programming from Yongwoo s Park 49

*/ < 15 SessionSnoopjava>, HttpSession HttpServletRequest getsession(boolean), boolean HttpSession true HttpSession true HttpSession, isnew, 30, 30,, HttpSession, ( SessionSnopcount), HTTP import javaio*; import javaxservlet*; import javaxservlethttp*; public class ShoppingCartServlet extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html;charset=euc-kr"); Java Servlet Programming from Yongwoo s Park 50

PrintWriter out = resgetwriter(); HttpSession session = reqgetsession(true); outprintln("<html>"); outprintln("<body>"); outprintln("<head>"); outprintln("<title>park Home Shopping</TITLE>"); outprintln("</head>"); outprintln("<body>"); outprintln("<h1> </H1><BR>"); String shoppingitems[] = { "Mouse", "Keyboard", "Monitor", "Speaker", "CDROM", "Floppy Disk", "Hard Disk", "Network Adapter", "Modem", "VGA Adapter", "Printer", "Case" ; int shoppingchecks[] = { 10000, 10000, 200000, 30000, 70000, 15000, 100000, 50000, 40000, 120000, 350000, 50000 ; String shoppingstep = reqgetparameter("shoppingstep"); if("checkout"equals(shoppingstep)) { String[] items = (String[])sessiongetValue("ShorppingCartitems"); if(items == null) { outprintln("<h2> </H2>"); sessionputvalue("shorppingcartcheck", new Integer(0)); else { int check=0; outprintln(" :<BR>"); outprintln("<ul>"); for(int i=0;i<itemslength;i++) { outprintln("<li>"+items[i]); for(int j=0;j<shoppingitemslength;j++) { if(shoppingitems[j]equals(items[i])) { check += shoppingchecks[j]; outprintln("</ul>"); sessionputvalue("shorppingcartcheck", new Integer(check)); Integer i = (Integer)sessiongetValue("ShorppingCartcheck"); outprintln("<h2> "+i+" </H2>"); else { if("additem"equals(shoppingstep)) { String addeditems[] = reqgetparametervalues("addeditems"); if(addeditems == null) { outprintln("<h2> </H2>"); else { String olditems[] = (String[])sessiongetValue("ShorppingCartitems"); String newitems[] = null; int addedcount = 0; if(olditems!= null) { newitems = new String[oldItemslength+addedItemslength]; for(int i=0;i<olditemslength;i++) { newitems[addedcount++] = olditems[i]; else { newitems = new String[addedItemslength]; Java Servlet Programming from Yongwoo s Park 51

for(int i=0;i<addeditemslength;i++) { newitems[addedcount++] = addeditems[i]; sessionputvalue("shorppingcartitems", newitems); String[] items = (String[])sessiongetValue("ShorppingCartitems"); if(items == null) { outprintln("<b> </B>"); else { outprintln(" :<BR>"); outprintln("<ul>"); for(int i=0;i<itemslength;i++) { outprintln("<li>"+items[i]); outprintln("</ul>"); outprintln("<form ACTION=\"http://parkkonkukackr:8080/servlet/ShoppingCartServlet\" METHOD=POST>"); outprintln(" <input type=hidden name=shoppingstep value=additem multiple>"); outprintln(" <select name=\"addeditems\" size=4 multiple>"); for(int i=0;i<shoppingitemslength;i++) { outprintln(" <option value=\""+shoppingitems[i]+"\">"+shoppingitems[i]); outprintln(" </select>"); outprintln(" <input type=submit value=\" \">"); outprintln("</form>"); outprintln("<form ACTION=\"http://parkkonkukackr:8080/servlet/ShoppingCartServlet\" METHOD=POST>"); outprintln(" <input type=hidden name=shoppingstep value=checkout multiple>"); outprintln(" <input type=submit value=\" \">"); outprintln("</form>"); outprintln("</body>"); outprintln("</html>"); outclose(); /* * public void dopost(httpservletrequest req, HttpServletResponse res) throws IOException, ServletException { doget(req, res); Java Servlet Programming from Yongwoo s Park 52

*/ < 16 ShoppingCartServletjava> HTTP, FORM HIDDEN URL, GET, POST POST 8 Java Servlet Programming from Yongwoo s Park 53

9, 10 HttpUtils HTTP Java Servlet Programming from Yongwoo s Park 54

HttpUtils, HttpUtils(): HttpUtils static javalangstringbuffer getrequesturl(httpservletrequest req): HttpServletRequest URL static javautilhashtable parsepostdata(int len, ServletInputStream in): HTTP POST application/x-www-form-urlencoded MIME HTML static javautilhashtable parsequerystring(javalangstring s):, getrequesturl URL, getquerystring GET HTTP, parsepostdata POST, getquerystring GET = (key) (value) Hashtable, parsepostdata POST = Hashtable,,, HTML FORM CGI,, servletproperties, HTML <HTML> <HEAD><TITLE>GuestBook</TITLE></HEAD> <BODY> <CENTER> Java Servlet Programming from Yongwoo s Park 55

<H1> </H1> <FORM action=http://parkkonkukackr:8080/servlet/guestbook method=post> <input type=hidden name=function value=write> <center> <table bgcolor=#faeddc cellspacing=0 cellpadding=6> <tr> <td><br><input type=text name=author size=10></td> <td><br><input type=text name=phone size=14></td> </tr> <tr><td colspan=2> <br><input type=text name=title size=40></td></tr></td></tr> <tr><td colspan=2> <br><textarea name=content rows=3 cols=40></textarea></td></tr> <tr> <td>html<br><input type=text name=html size=30></td> <td>e-mail<br><input type=text name=e_mail size=30></td> </tr> <tr> <br> <td align=right><input type=reset value= ></td> <td align=left> <input type=submit value= ></td> </tr> </table> </FORM> </BODY> </HTML> /* * */ < 17 GuestBookhtml> Java Servlet Programming from Yongwoo s Park 56

import javaio*; import javautil*; import javaxservlet*; import javaxservlethttp*; public class GuestBookServlet extends HttpServlet implements SingleThreadModel { String guestbookpath; public void init(servletconfig config) throws ServletException { superinit(config); guestbookpath = getinitparameter("guestbookpath"); if(guestbookpath == null) { Enumeration initparams = getinitparameternames(); Systemerrprintln(" : "); while(initparamshasmoreelements()) { Systemerrprintln(initParamsnextElement()); Systemerrprintln(" "); throw new UnavailableException (this, "!"); public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html; charset=euc-kr"); PrintWriter out = resgetwriter(); outprintln("<html>"); outprintln("<head>"); outprintln("<title>writing</title>"); outprintln("</head>"); outprintln("<body>"); try { String functionstr = reqgetparametervalues("function")[0]; if(functionstrequalsignorecase("write")) { // FileWriter guestbookfile = new FileWriter(guestBookPath, true); // PrintWriter tofile = new PrintWriter(guestBookFile); tofileprintln("<begin>"); TimeZone tz = new SimpleTimeZone(9*60*60*1000, "KST"); //, Date today = new Date(); TimeZonesetDefault(tz); tofileprintln("date: " + todaytostring()); Enumeration values = reqgetparameternames(); // while(valueshasmoreelements()) { String name = (String)valuesnextElement(); String value = reqgetparametervalues(name)[0]; Java Servlet Programming from Yongwoo s Park 57

if(namecompareto("submit")!= 0) { tofileprintln(name + ": " + toksc5601(value)); tofileprintln("<end>"); guestbookfileclose(); outprintln("<h1>"); outprintln("success"); outprintln("</h1>"); else { outprintln("<h1>"); outprintln("fail" + functionstr + "" + guestbookpath); outprintln("</h1>"); catch(ioexception e) { // eprintstacktrace(); outprintln("<h1>"); outprintln(" "); outprintln("</h1>"); outprintln("</body>"); outprintln("</html>"); outclose(); public void dopost(httpservletrequest req, HttpServletResponse res) throws IOException, ServletException { doget(req, res); public static String toksc5601( String str ) throws UnsupportedEncodingException { if(str == null) { return(null); return(new String(strgetBytes("8859_1"), "KSC5601")); /* * */ < 18 GuestBookServletjava> Java Servlet Programming from Yongwoo s Park 58

servletproperties # $Id: servletsproperties,v 12 1999/04/02 02:04:22 duncan Exp $ # Define servlets here # <servletname>code=<servletclass> # <servletname>initparams=<name=value>,<name=value> snoopcode=snoopservlet snoopinitparams=initarg1=foo,initarg2=bar snoop2code=snoopgenericservlet snoop2initparams=initarg1=foo,initarg2=bar hellocode=hellogenericservlet helloinitparams=name=yongwoo's Park hello2code=hellogenericservlet2 hello2initparams= jspcode=comsunjspruntimejspservlet # guestbook servlet # # D:\\Java\\jsdk21\\webpages\\guestbook\\GuestBooktxt guestbookcode=guestbookservlet guestbookinitparams=guestbookpath=d:\\java\\jsdk21\\webpages\\guestbook\\guestbooktxt < 19 servletsproperties > <BEGIN> Date: Wed Oct 27 04:00:55 GMT+09:00 1999 HTML: http://parkkonkukackr Author: Title: Phone: 02-22xx-xxxx Content: ~ E_Mail: ywpark@csekonkukackr Function: Write <END> < 20 D:\\Java\\jsdk21\\webpages\\guestbook\\GuestBooktxt > Java Servlet Programming from Yongwoo s Park 59

E-mail, SMTP(Simple Mail Transfer Protocol), SMTP,,, (SUBJECT), ( ),,, HTML FORM CGI,, servletproperties, HTML <HTML> <HEAD><TITLE>Send Mail</TITLE></HEAD> <BODY> <CENTER> <H1> </H1> <FORM action=http://parkkonkukackr:8080/servlet/sendmail method=post> <table bgcolor=#faeddc cellspacing=0 cellpadding=6> <tr> <td> <br><input type=text name=mailfrom size=40></td> <td><br><input type=text name=rtcpto size=40></td> </tr> <tr><td colspan=2> <br><input type=text name=subject size=40></td></tr></td></tr> <tr><td colspan=2> <br><textarea name=body rows=3 cols=60></textarea></td></tr> <tr> <br> <td align=right><input type=reset value= ></td> <td align=left> <input type=submit value= ></td> </tr> </table> </FORM> </BODY> </HTML> Java Servlet Programming from Yongwoo s Park 60

/* * */ < 21 SendMailServlethtml> SMTP import javaio*; import javanet*; import javautil*; import javaxservlet*; import javaxservlethttp*; public class SendMailServlet extends HttpServlet implements SingleThreadModel { String smtpserver; PrintStream ps = null; BufferedReader dis = null; public void init(servletconfig config) throws ServletException { superinit(config); smtpserver = getinitparameter("smtpserver"); if(smtpserver == null) { Enumeration initparams = getinitparameternames(); Systemerrprintln(" : "); while(initparamshasmoreelements()) { Systemerrprintln(initParamsnextElement()); Systemerrprintln("SMTP "); Java Servlet Programming from Yongwoo s Park 61

throw new UnavailableException (this, "Not given a SMTP server to send a mail!"); public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ressetcontenttype("text/html; charset=euc-kr"); PrintWriter out = resgetwriter(); outprintln("<html>"); outprintln("<head>"); outprintln("<title>send Mail</TITLE>"); outprintln("</head>"); outprintln("<body>"); String END_OF_DATA = "\r\n\r\n"; Socket smtp = null; try { smtp = new Socket(smtpServer, 25); // SMTP 25 OutputStream os = smtpgetoutputstream(); ps = new PrintStream(os); InputStream is = smtpgetinputstream(); dis = new BufferedReader(new InputStreamReader(is)); catch(ioexception e) { Systemoutprintln("Error connecting: " + e); String mailfrom = toksc5601(reqgetparameter("mailfrom")); String rcptto = toksc5601(reqgetparameter("rtcpto")); String subject = toksc5601(reqgetparameter("subject")); String body = toksc5601(reqgetparameter("body")); outprintln("<h1>"); if(mailfrom == null rcptto == null subject == null body == null) { outprintln("mailfrom or rtcpto or subject or body is empty"); else { try { String localhost = InetAddressgetLocalHost()getHostName(); // Local send("helo " + localhost); receive(); send("mail FROM: " + mailfrom); receive(); send("rcpt TO: " + rcptto); receive(); send("data"); receive(); send("subject: " + subject); receive(); send(body+end_of_data); receive(); send("quit"); receive(); smtpclose(); outprintln(" "); catch(ioexception e) { outprintln(" "); outprintln("</h1>"); outprintln("</body>"); outprintln("</html>"); Java Servlet Programming from Yongwoo s Park 62

outclose(); void send(string s) throws IOException { psprintln(s); psflush(); Systemoutprintln("Java request: " + s); void receive() throws IOException { String readstr = disreadline(); Systemoutprintln("SMTP response: " + readstr); public void dopost(httpservletrequest req, HttpServletResponse res) throws IOException, ServletException { doget(req, res); public static String toksc5601( String str ) throws UnsupportedEncodingException { if(str == null) { return(null); return(new String(strgetBytes("8859_1"), "KSC5601")); /* * */ < 22 SendMailServletjava> SMTP servletproperties # $Id: servletsproperties,v 12 1999/04/02 02:04:22 duncan Exp $ # Define servlets here # <servletname>code=<servletclass> # <servletname>initparams=<name=value>,<name=value> Java Servlet Programming from Yongwoo s Park 63