17
April 2015 ED1.0 HR Kwon ([email protected] ) IT 강의자료 Web Server Page (ASP,PHP,JSP)

Web server page_ed10

  • Upload
    hungrok

  • View
    161

  • Download
    2

Embed Size (px)

Citation preview

April 2015 ED1.0

HR Kwon ([email protected] )

IT 강의자료 Web Server Page (ASP,PHP,JSP)

1

WSP 일반

Web Server Page

. Web Client 의 http 요청에 대한 Web Server 의 동적인 action 으로 정의한다

. 일반적 으로 Client 가 html 페이지를 요청 (Request) 하는 것은

서버에서 특정한 action 없이, 서버가 지닌 해당 html page 를 가공 없이 응답 (Response) 하는 정적 인 것이다

. 이에 반해, 동적인 action 은 아래와 같이 두 가지 포괄적인 기능을 갖는 것이다

(1) html page 를 동적으로 만들어 Client 에게 Response 한다

(2) 특정한 action 을 수반한다 (예. DB, Email, File Handling,,)

. Web Server Page 일반

(1) html page 내에 Script 형태 로 표현된다

(2) ASP (Active) , PHP (Hypertext Preprocessor) , JSP (Java) 가 대표 적 인 서버에서 지원되는 Server Page 지원 Software 이다

(3) html page 확장자가 asp, php, jsp 로 특정화 되어있다

(4) Web Server 는 특정화 된 확장자 를 갖는 page 요청이 오면, 대응되는 각 Server Page 를 실행 시킨다

Web Client

Web Server

ASP

index.html

HTTP Request index.asp

HTTP Response

index.asp

동적 생성

Action

2

HTTP

Hyper Text Transfer Protocol

. TCP (connection oriented) 응용 계층으로, Web 상에서 서버 와 client 간 data 전송방법

. Text 기반 Message, Message 의 종류를 구분하는 것을 Method 라 칭 하며, 작업 의 종류를 구분한다

. HTTP Message 는 Header 와 Body 로 구성

MAC Header IP Header TCP Header HTTP Message

Packet Switching Network

HTTP

TCP

IP

Socket

Data Link & PHY

HTTP

TCP

IP

Socket

Data Link & PHY

Web Browser Client

Web Browser Server

< Method > GET retrieve header and body POST insert PUT update DELETE delete HEAD retrieve header only OPTIONS supported methods TRACE echo test

WebKit

index.html

http://www.hungrok.com:80/index.html www.hungrok.com

3

HTTP

URI (Uniform Resource Identifier)

. URI = URL (Locator) + URN (Name)

. URN : 불변하지 않는 자원이름, 거의 사용이 되지 않는다

. URL

주1. 서버의 resource 를 지칭 하며, 위치 및 query parameter 를 포함 할 수 있다 : http://host [:port] [ abs_path [?query]]

주2. 특정한 자원이 지정되지 않으면, 서버는 default 자원을 대상으로 한다 (/index.html)

주3. query parameter 는 Get Method 시 에만 사용된다 (?)

Method 상세 설명

. 사용자 가 브라우저 에서 지정하여 사용하는 방식은 GET method 를 사용한다

Method 설명

GET . Request URI 에 명기된 Information 을 가져오는 것 (retrieve) 이다 . Information 은 정적인 data 뿐만 아니라 data producing process 도 의미한다 . 상기 사유로 Form 에 대하여 Get Method 를 사용하는 것이 가능하다 . Request Line : GET do1.asp ?name=kwon&age=28 HTTP/1.1

POST . Request URI 에 지정된 서버의 resource 에 새로운 종속물로서 Entity 를 보낸다 . Submit 개념으로 종속물은 Entity Body 로 간다 . 서버의 리소스는 서버의 action 을 의미하며, 무슨 action 을 하는지는 서버의 고유사항 이다 . 예 : Posting message, Providing a block of data (Form), Extending a database, File 송부 . Request Line : POST do1.asp HTTP/1.1 Entity Body : name=kwon&age=28

PUT . Request URI 에 지정된 서버의 resource 하부 (under) 에 stored 하는 목적으로 enclosed entity 를 보낸다 . Upload 개념으로 enclosed entity 는 Entity body 로 간다 . 만약 기존에 있는 resource 라고 하면, Replace 되어야 한다 . 보안을 위하여 서버에서 일반적으로 사용되지 않는다 . Request Line : PUT /image/mypicture.jpg HTTP/1.1 단일 파일만 전송가능 할 것이다 (?)

4

HTTP

POST MultiPart 전송

. Multi Entity 를 보내는 것을 의미한다 (email 에서 다수의 첨부파일 송부 도 마찬가지 개념)

. Entity Header 의 Content-Type 에 정의를 한다 (이를 MIME 이라한다)

. HTML Form 을 사용하여 전송 시 Content-Type 사용 예

1) 단일 Part 송부, 쌍 (Key & Value) 으로 송부 : Content-Type = “application/x-www-form/urlencoded”

Entity Body = Name=Steve+Johnson&[email protected]

2) 단일 Part 송부, text 로 송부 : Content-Type = “text/plain”

3) MultiPart 송부 : Content-Type = “multipart/form-data;boundary=XXXX”

boundary 는 특정한 text 형식으로 (예. “-------end of part --------”), 서버에서 Parsing 을 용이하게 하기 위함이다

. 파일을 송부하는 경우에는 MultiPart 방식 으로만 가능하다

. Form 사용 시 MultiPart 전송 모습

Resource (action)

POST

Entity Header

Part 1 Entity Body

Part 2 Entity Body

Part 3 Entity Body

Boundary (Text)

Boundary (Text)

Boundary (Text)

Boundary (Text)

Content-Type =“multipart/form-data;boundary=XXXX” Content-Disposition; form-data; name=“Name” Content-Disposition; form-data; name=“email” Content-Disposition; form-data; name=“upload”, filename=“x” Content-Type =“text/html

5

HTTP

MultiPart 전송

. JAVA 에서 POST 를 사용하여 file 송부 하는 template code

HttpURLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; DataInputStream inStream = null; InputStream is = null; OutputStream os = null; boolean ret = false; String StrMessage = ""; String exsistingFileName = "C:\account.xls"; String lineEnd = " "; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1*1024*1024; String responseFromServer = ""; String urlString = "http://localhost:8080/FileUpload/requestupload"; FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) ); url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); dos = new DataOutputStream( conn.getOutputStream() ); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name="upload";" + " filename="" + exsistingFileName +""" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

6

HTTP

Message 구성

. Request Line : GET /my/main.html HTML/1.1

. Response Line : HTTP/1.1 200 OK

< Request Header > Accept Accept-Charset Accept-Encoding Accept-Language Authorization Expect From Host If-Match If-Modified-Since If-None-Match If-Range If-Unmodified-Since Max-Forwards Proxy-Authorization Range Referrer TE User-Agent

< Response Header > Accept-Ranges Age ETag Location Proxy-Authenticate Retry-After Server Vary WWW-Authenticate

< General Header > Cache-Control Connection Date Pragma Trailer Transfer-Encoding Upgrade Via Warning

< Entity Header > Allow Content-Encoding Content-Language Content-Length Content-Location Content-MD5 Content-Range Content-Type Expires Last-Modified

< Cookie Header > Set-Cookie Cookie

Request Message . Request Line . General Header . Request Header . Cookie Header . Entity Header

Entity Body

If Entity Header

Response Message . Response Line . General Header . Response Header . Cookie Header . Entity Header

Entity Body

If Entity Header

7

ASP

Active Server Page

. Microsoft 가 제공한다

. Window 가 제공하는 Web Server 기능 및 APS 엔진 기능이 활성화 되어야 한다

: 제어판 (Control Panel) Window feature enable / disable IIS (Internet Information Server) 활성화

. 내장객체 (제공되는 ASP 객체) 를 제공한다

. Active-X 를 사용하여 개발된 것 이다

제공되는 ASP 객체 (Object) 의 사용

. 제공되는 객체는 아래와 같이 4가지 로 분류 할 수 있다

1) VBScript Function 으로 제공 (Built-in Functions)

2) 직접사용 객체 : Request, Response

3) Instance 생성 객체 : by CreateObject

4) Server 객체 를 통해서 사용하는 객체 : by Server.CreateObject

객체의 구성

. 객체들은 아래 4 가지 를 지니고 있다. 특정한 객체 는 Property 만으로 구성 되기도 한다

1) Contents (Collection) : 해당 객체가 지니는 Data Set

2) Property

3) Method

4) Event

8

ASP

ASP 내장객체 모습

. CDO : Collaboration Data Objects for email

. ADO : ActiveX Data Objects for database

ASP 엔진

Instance 생성객체 . CDO

Server 객체

. Session 객체

. Application 객체

. FileSystem

. Dictionary

. AdRotator

. Browser Capa.

. Content Linking

. Content Lotator

. ADO

직접사용 객체 . Request . Response

ASP

<Script>

CreateObject

Server.CreateObject

FileSystem 하부 . File . TextStream . Driver . Folder

file

Data Base

email

ADO 세부 . Command . Connection . Field . Parameter . Property . Record . Recordset . Stream

VBScript Function . Date, Time . String, Array . Conversion . Format . Math . Others

Global.asa

html

9

ASP

Script

. 종류 : VBScript, JavaScript

. <% ….. %> 로 표현된다

. Script 내부구성

1) Variable

2) Procedure : <head> 내부에 위치한다

3) Statements : Function, Conditional, Looping,,

4) Directive : #include

Variable

. 선언 (특정한 data type 선언이 없다) : dim xyz, dim abc(x) // abc (x) is for Array

. 위치에 따른 Scope

1) Local 변수 : Procedure 내부에 위치, Procedure 실행이 종료되면 소멸

2) 전역변수 : 하나의 ASP file 내에서 만 access

3) 광역변수 : 여러 ASP file (하나의 Application 내) 에서 access , Session variable 과 Application variable 에 해당

< VBScript > <!DOCTYPE html> <html> < body> < % response.write("Hello World!") %> < /body> < /html>

< JavaScript > <%@ language="javascript"%> <!DOCTYPE html> <html> < body> < % Response.Write("Hello World!") %> < /body> < /html>

< Procedure > <head> < % sub vbproc(num1,num2) response.write(num1*num2) end sub %> < Function> Function myfunction() some statements myfunction=some value End Function

10

ASP

Session Object

. 각 사용자 고유정보 (Cookie) 를 관리하기 위한 Interface 역할을 하는 Object 이다

. 사용자 별 하나의 Session Object 이 배당된다

. Global.asa 파일에 Session_OnStart Procedure 로 시작된다

Application Object

. 다수의 ASP 파일 과 함께 특정한 기능을 수행하는 것을 의미한다

. 전체 User 가 Share 한다

. Global.asa 파일에 Application_OnStart Procedure 로 시작된다

Global.asa 파일

. Server Object 가 사용하는 파일로 아래 5가지 를 표현한다

1) Application events : Application Object 의 procedure (Start, End)

2) Session events : Session Object 의 procedure (Start, End)

3) <Object> 선언 : 서버객체를 통하여 사용되는 객체들을 선언

4) TypeLibrary 선언 :

5) #include Directive :

11

PHP

Hypertext Pre Processor

. Open 소스기반 Script Language 로 범용적 으로 사용된다.

. 윈도우 용과 Linux 용으로 제공되며, PHP License 와 GPL License 를 지닌다 (www.php.net)

. Web Server 역할까지 하는 것은 아니다 (IIS 나 Apache 같은 Web Server 를 필요로 한다)

. 아래와 같은 내장객체를 지원한다

1) Super Global 변수 : $GLOBALS, $_SERVER, $_GET, $_POST, $_REQUEST, $_FILES,$_ENV, $_COOKIE, $_SESSION

2) Array, String

3) Date, Time, Calendar, TimeZone, Math

4) ZIP, XML

5) FTP, HTTP, Mail

6) Cookie

7) Database (MySQL), MySQL is provided from Oracle

8) File System

9) Session Manager

10) Filter

Script

. Script 표현 : <?php ……. ?>

. 구성

1) 상수 : define (A, 3)

2) 변수 : $abc = 10

3) 객체모형 (Class) : Data type 이 Object 이다

4) Function : function myFunction() {}

5) Statements : Conditional, Looping, include, require

12

PHP

Variable

. 아래와 같이 3가지 scope

1) Local : Function 내부에 변수, Function 이 종료되면 소멸

2) Static : Function 내부에 변수이나 Static 으로 선언, Function 이 종료되어도 Scope 에 존재한다

3) Global : Function 외부에 존재, Function 내부에서 사용시 global keyword 로 사용하여야 한다

. 명시적 이지 않은 Data Type : String, Integer, Float, Boolean, Array, Object, Null, Resource

주1. $cars = array(“ab” “ac” “ad” ) ;

주2. Array 는 3가지

1) Indexed Array : 순서가 있는 일반 Array

2) Associative Array : 쌍 (key 와 Value) 가 있는 Array

3) Multidimensional Array

주3. 객체모형 (Class) 에 의하여 생성된 객체의 Data type 이 Object 이다

13

PHP

Script

. Template Scripts

<?php define("GREETING", "Welcome to W3Schools.com!"); // 상수 $x = 5; // global variable function myTest() { global x ; echo "<p>Variable x inside function is: $x</p>"; } myTest(); class Car { function Car() { $this->model = "VW"; } } // create an object and show object properties $herbie = new Car(); echo $herbie->model; $t = date("H"); if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>

14

JSP

JSP (Java Server Page) , Servlet

. 서버에서 실행되는 Java Class 로서 , 아래 와 같은 목적 이다

(1) Dynamic html page ; 주어진 Parameter 에 대응하는 HTML page 를 동적으로 만들어서 client 에 제공한다, http://URL/index.jsp

(2) Interact with FORM ; Post 되어진 FORM 객체에 대하여 특정한 기능을 수행한다 , FORM action = /Servlet/test1

. MVC (Model View Control) 사용모델

(1) JSP Only : View, Controller 역할을 JSP 혼자 담당

(2) JSP / Servlet : View 는 JSP 가 담당하고, Controller 역할은 Servlet 이 담당

(3) JSP / JavaBean : View 는 JSP 가 담당하고, Controller 역할은 JavaBean 이 담당

Web Client

Web Server

Servlet (test1)

HTTP Post ?action=/Servelt/test1

Form action=/Servlet/test1

Do Action

Web Client

Web Server

JSP

index.html

HTTP Get ?name=kwon

HTTP Response

index.jsp

동적 생성

참고 (HTTP) . abs_path 및 Parameter 는 URL 의 Optional 정보로서 Request Line 에 포함된다

15

JSP

JSP

. HTML 문서 (Page) 내에 3가지 (지시어, Scripting, Action) Element 로 표현된다

. HTML 파일 확장 자 명 은 “jsp” 로 한다

. Runtime 에 javax.servlet.http.HttpServlet 을 상속받는 Servlet class 가 만들어 지고 JSP Container 가 life cycle 을 주관한다

(궁극적 으로는 Servlet 과 동류의 개념이다)

. Servlet 을 사용하면 HTML 문서를 만들기가 난이 하여 (PrintWriter 를 이용) , 편의 목적으로 나옴

. EE 에서 제공하는 JSP 의 암묵적 객체 : request, response, out, session, application, config, pageContext, page, exception

. MS 의 ASP (Active Server Page) 나 PHP 와 동일한 기능이다

. 지시어 Element : <%@ page ….. > , Page 와 Include 지시어 두 가지 이다

. Page 지시어 : language, import, session, buffer, autoFlush, isThreadSafe, info, errorPage, isErrorPage, : contentType, pageEncoding, extends .Scripting Element : (1) Declaration <%! ……. %> : 멤버변수 나 메소드 를 선언할 때 사용 (2) Expression <%= …… %> : 간단한 data 출력이나 메소드 호출에 사용 (3) Scriptlet <% …….. %> : 순수 Java code 만 가능, Page 의 간결성을 위하여 사용이 권고되지 않고 JavaBeans 를 대신사용 . Action Element : <jsp: ….. />

16

JSP

Servlet

. Client HTTP message 에서 URL (Parameter 가 포함된) 로 사용이 되어진다 (HTTP POST ?action=/Servlet/test1)

. Server 측에서 수행되는, JAVA 로 구현된 CGI (Common Gateway Interface) 이다

. Web.xml 파일을 필요로 한다

. 반드시 javax.servlet.http.HttpServlet 을 상속 하여야 한다

. Servlet Container 가 Life Cycle 을 관리한다 (init service destroy)

. 주요한 Servlet Container 로는 Tomcat, Jetty, Jboss 등이 있다

public class ServletTest extends HttpServelet { @Override public void init(){} @Override public void service(){} @Override public void doGet(){} @Override public void doPost(){} @Override public void destroy(){} }

Web Server

Servlet Container

Web Client

Servlet Class

Web Server

HTTP Request

HTTP Response

service doGet or doPost

By doGet or doPost

Web Application 설정파일 1) Servlet 정보 2) Error Page 정보 3) Listener 정보 4) Filter 정보 5) 보안설정 정보

web.xml