Web-DB Programming - Servlet/JSP

HTTP

□Overview

- Default port no.: 80

□Request

- Format

Request Line

Request Header Field

Entity Body

① Request Line

<METHOD>	: 요청방식 - GET/POST

<RESOURCE IDENTIFIER>	: 요청하는 file

<HTTP VERSION>

<cr/lf>	;  a carriage-return/line-feed char.

② Request Header Field: 부가적 정보 전송

NAME: VALUE<crlf>

③ Entity Data: optional 정보 전송

Ex) Request Format

GET /index.html HTTP/1.1

accept-language:ko

host:127.0.0.1

accept:*/*

user-agent:Mozilla/4.0(compatible; MSIE 5.0; Windows NT 5.0)

connection:Keep-Alive

accept-encoding:gzip, deflate

□Response

- Format

Response Header

Header Field

Entity Body

① Response Header

<HTTP Version>

<result code>	: success/fail 표시

OK - 200, error no. - 404 (can't find)

[<explanation>]

<cr/lf>

② Field: server의 속성과 HTML 문서에 관한 정보 전송 - NAME: VALUE<crlf>

③ Entity Body: user가 요청한 *.html file

Ex) Response Format

HTTP/1.1 200 OK

Date: Mon, 26 Nov 2001 06:57:11 GMT

Content-type: text/html

<HTML>

<HEAD><TITLE><\TITLE><\HEAD>

<BODY>

…

<\BODY>

<\HTML>

Servlet Overview

□Two-tier C/S에서 application programming

- Remote Data Management: Applet

- Distributed Function: Stored procedure

- Remote Presentation: Servlet

□Web-DB Programming

- CGI: User의 request마다 새로운 process를 생성

- Servlet

□모든 servlet들은 하나의 servlet engine process에서 수행됨.

□User의 request마다 JVM상에서 thread를 생성하여 수행.

∀ 같은 process 내에 있는 thread들은 서로 resource를 공유.

∀ thread는 process보다 resource를 적게 사용.

∀ performance enhancement

Servlet Engine

□Installation

- Apache Web server: http://www.apache.org (or http://httpd.apache.org)

- Tomcat Jakarta	: http://jakarta.apache.org

□Administration

- Start-up

#startup.sh	// Servlet engine first...

#apachectl start	// Web server next...

- Shut-down

#apachectl stop	// Web server first...

#shutdown.sh	// Servlet engine next...

- Browser에서 test 수행

http://host_name/examples/servlets/

http://host_name/examples/jsp/

Servlet Programming

□Environment file 설정 ($TOMCAT_HOME/conf/tomcat.conf)

Ex)  # User defined directory...

Alias /tykim "/usr/local/jakarta-tomcat/webapps/tykim"

<Directory "/usr/local/jakarta-tomcat/webapps/tykim">

Options Indexes FollowSymLinks

</Directory>

ApJServMount /tykim/servlet /tykim

<Location "/tykim/WEB-INF/">

AllowOverride None

deny from all

</Location>

<Location "/tykim/META-INF/">

AllowOverride None

deny from all

</Location>

∀ Browser에서 /host_name/tykim/servlet/serv_pgm 수행

(program 위치: $TOMCAT_HOME/webapps/tykim/WEB-INF/classes/serv_pgbvb m.class)

□Environment file 설정 ($TOMCAT_HOME/conf/server.xml)

Ex)  # User defined directory...

<!-- ==================== Special webapps ==================== -->

<!-- You don't need this if you place your app in webapps/

and use defaults.

For security you'll also need to edit tomcat.policy

Defaults are: debug=0, reloadable=true, trusted=false

(trusted allows you to access tomcat internal objects

with FacadeManager ), crossContext=true (allows you to

access other contexts via ServletContext.getContext())

If security manager is enabled, you'll have read perms.

in the webapps dir and read/write in the workdir.

-->

<Context path="/tykim"

docBase="webapps/tykim"

crossContext="false"

debug="0"

reloadable="true" >

</Context>

∀ Disable Servlet Auto-Reloading (from $TOMCAT_HOME/doc/uguide/tomcat_ug.html)

Servlet auto-reloading is really useful for development time. However it is very expensive (in performance degradation terms) and may put your application in strange conflicts when classes that were loaded by a certain classloader cannot co-operate with classes loaded by the current classloader.

∀ From Release Notes for Tomcat 3.3

6.  KNOWN BUGS AND ISSUES

6.4 Automatic Servlet Reloading

Tomcat 3.2 and later include a feature whereby you can ask it to automatically reload servlet classes (loaded from either the WEB-INF/classes directory or a JAR file in the WEB-INF/lib directory) that have been 'changed'.  This feature is 'experimental', and may 'not be completely functional'.  In particular, changes to 'classes other than the servlet' you are requesting do not trigger class reloads -- you will need to 'restart Tomcat to reflect changes' in those classes.

Reloading is enabled by including a reloadable="true" attribute on the <Context> element in the "conf/server.xml" file.  Note that automatic reload support is not recommended for production applications because of its experimental nature, and the extra overhead required to perform 'the necessary checks on every request'.

□Introduction

Ex) Simple example (OutHeader.java)

import java.io.*;

import java.text.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class OutHeader extends HttpServlet {	// Subclass of HttpServlet...

// Executed as a thread on JVM...

// Processes an HTTP GET request...

public void doGet(HttpServletRequest request,	HttpServletResponse response)

throws IOException, ServletException

{

// REQUEST class (HttpServletRequest) methods (client to server)...

Enumeration header    = request.getHeaderNames();

String	clientURL = request.getRemoteAddr();

// RESPONSE class (HttpServletResponse) methods (server to client)...

response.setContentType("text/html; charset=eud-kr");

PrintWriter out = response.getWriter();

out.println("<html>");	// HTML Header...

out.println("<head>");

out.println("<title>" + " Header Information " + "</title>");

out.println("</head>");

// HTML Body...

out.println(" <body bgcolor=\"white\" text=\"black\" link=\"blue\" "

+" vlink=\"purple\" alink=\"red\" >");

out.println("<h1>" + " OutHeader.class " + "</h1>");

out.println(" Request client addr: "+clientURL+"<BR>");

while(header.hasMoreElements()){

Object headerrow = header.nextElement();

out.println("["+headerrow.toString()+"] "

+request.getHeader(headerrow.toString()) );

out.println("<BR>");

}

out.println("<p>&nbsp;</p>");

out.println("</body>");

out.println("</html>");

}//End of doGet

}

- Web client's request

∀ Two methods: GET/POST

① GET: To access a Web page, a client sends a GET request via HTTP.

② POST: To send the contents of a Web form, a client uses the POST request.

EX) HTML form request methods

<FORM METHOD=POST ACTION="URL">

……

</FORM>

- Web server's response

∀ Summary of HttpServlet methods:

□void doGet(HttpServletRequest request, HttpServletResponse response)

∀ Processes an HTTP GET request

□void doPost(HttpServletRequest request, HttpServletResponse response)

∀ Processes an HTTP POST request

- Summary of HttpServletRequest methods: Client's request

□String getCharacterEncoding()

∀ Returns the name of the character set used to encode the request.

□int getContentLength()

∀ Returns the length of the request.

□String getContentType()

∀ Returns the media type of the request.

□ServletInputStream getInputStream()

∀ Returns a ServletInputStream associated with the request.

□Object getAttribute(String name)

∀ Returns the value of the specified request attribute.

□String getParameter(String name)

∀ Returns the value of the specified request parameter.

□Enumeration getParameterNames()

∀ Returns an Enumeration containing the names of the request parameters.

□String[] getParameterValues(String name)

∀ Returns the values of the specified request parameter.

□String getProtocol

∀ Returns a description of the request protocol.

□BufferedReader getReader()

∀ Returns a BufferedReader associated with the request.

□String getRemoteAddr()

∀ Returns the Internet address of the client.

□String getRemoteHost()

∀ Returns the host name of the client.

□String getServerName()

∀ Returns the host name of the server.

□int getServerPort()

∀ Returns the port number of the server.

- Summary of HttpServletResponse methods: Server's response

□PrinterWriter getWriter()

∀ Returns a PrinterWriter for writing text responses.

□ServletOutputStream getOutputStream()

∀ Returns a ServletOutputStream for writing binary responses.

□void setContentType(String type)

∀ Sets the content type of the response.

□Form Request/Response

- Making a HTML Form

Ex) userinput.html

<html>

<head>  <title> User Input </title>

</head>

<body bgcolor="yellow" text="black" link="blue" vlink="purple" alink="red">

<p align="center"><font size="5" FACE="arial"><b> UserInput.class

</b></font></p>

<form method="post" action="http://comedudb2.cs.ucla.edu/tykim/servlet/UserInput">

<p align=""><font size="3"><b> Password

<input type="password" name="passwd">

</b></font></p>

<p align=""><font size="3"><b> Your Language

<input type="checkbox" name="english" value="on">English

<input type="checkbox" name="korean" value="on">Korean

<input type="checkbox" name="chinese" value="on">Chinese

<input type="checkbox" name="japanese" value="on">Japanese

</b></font></p>

<p align=""><font size="3"><b> Gender

<input type="radio" name="gender" value="male" checked> male

<input type="radio" name="gender" value="female"> female

</b></font></p>

<p align=""><font size="3"><b> City Lived

<select name="city">

<option selected>Seoul</option>

<option>Pusan</option>

<option>Daejun</option>

<option>Daegu</option>

<option>Kwangu</option>

<option>Inchun</option>

<option>Ulsan</option>

<option>Others</option>

</select>

</b></font></p>

<p align=""><font size="3"><b> Mailing Address

<input type="text" name="address">

</b></font></p>

<p align=""><font size="3"><b> Comments

<textarea name="comment" rows="5"></textarea>

</b></font></p>

<p align="center"><font size="3"><b>

<input type="submit" value="Submit">

</b></font></p>

</form>

</body>

</html>

- Writing a Servlet program

Ex) UserInput.java

import java.io.*;

import java.text.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class UserInput extends HttpServlet {	// Subclass of HttpServlet...

// Process an HTTP POST request...

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

{

// REQUEST from a client to a server...

String clientURL = request.getRemoteAddr();

String passwd = request.getParameter("passwd");

String english = request.getParameter("english");

String korean = request.getParameter("korean");

String chinese = request.getParameter("chinese");

String japanese = request.getParameter("japanese");

String gender = request.getParameter("gender");

String city = request.getParameter("city");

String address = request.getParameter("address");

String comment = request.getParameter("comment");

// RESPONSE from a server to a client...

response.setContentType("text/html; charset=EUC-KR");

PrintWriter out = response.getWriter();

out.println("<html>");	// Header...

out.println("<head>");

out.println("<title>" + " User Input by Form " + "</title>");

out.println("</head>");

out.println(" <body bgcolor=\"yellow\" text=\"black\" link=\"blue\" "

+" vlink=\"purple\" alink=\"red\" >");	// Body...

out.println("<p align=\"center\"><font size=\"5\" FACE=\"arial\"><b> "

+ " UserInput.class "+"</b></font></p>");

out.println(" Request client addr: "+clientURL+"<BR>");

out.println("<BR>Your Language:&nbsp;");

if(english!=null  && english.equals("on")) out.println("English ");

if(korean!=null   && korean.equals("on")) out.println("Korean ");

if(chinese!=null  && chinese.equals("on")) out.println("Chinese ");

if(japanese!=null && japanese.equals("on")) out.println("Japanese ");

out.println("<BR>gender&nbsp;:&nbsp;");

if(gender.equals("male"))

out.println("남 ");

else

out.println("여 ");

out.println("<BR>City&nbsp;:&nbsp;"+city);

out.println("<BR>Mailing Address:&nbsp;"+address);

out.println("<BR>Comments&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;"

+comment);

out.println("<p>&nbsp;</p>");

out.println("</body>");

out.println("</html>");

}//End of doPost

}

□JDBC programming

- Environment 설정: Servlet을 실행시키는 JVM의 CLASSPATH 설정

Ex) tomcat.properties

#CLASSPATH environment value passed to the JVM

# Syntax: wrapper.classpath=[path] (String)

# Default: NONE (Sun's JDK/JRE already have a default classpath)

# Note: if more than one line is supplied these will be concatenated using

#       ":" or ";" (depending wether Unix or Win32) characters. JVM must be

#       able to find JSDK and JServ classes and any utility classes used by

#       your servlets.

# Note: the classes you want to be automatically reloaded upon modification

#       MUST NOT be in this classpath or the classpath of the shell

#       you start the Apache from.

#

wrapper.classpath=@JSERV_CLASSES@

wrapper.classpath=@JSDK_CLASSES@

wrapper.classpath=/oradb/u01/app/oracle/product/8.0.5/jdbc/lib/classes12.zip

wrapper.classpath=/oradb/u01/app/oracle/product/8.0.5/jdbc/lib/nls_charset12.zip

- Form 작성

Ex) tabletest.html

<html>

<head>

<title> Table Test </title>

</head>

<body bgcolor="yellow" text="black" link="blue" vlink="purple" alink="red">

<p align="center"><font size="5" FACE="arial"><b>

tabletest.html

</b></font></p>

<form method="post" action="http://comedudb2.cs.ucla.edu/tykim/servlet/TableTest" >

<div align="center"><table border=1>

<tr><font size="3">

<td width="108"> DB User ID </td>

<td width="290"><input type="text" name="userid"> </td>

</tr>

<tr>

<td> DB Password </td>

<td><input type="password" name="passwd"> </td>

</tr>

<tr>

<td> Table </td>

<td> <select name="table">

<option selected>account</option>

<option>change</option>

<option>dept</option>

<option>emp</option>

</select>

</td>

</tr>

</table></div>

<p align="center"><font size="3"><b>

<input type="submit" value="Submit">

<input type="reset" value="Reset">

</b></font></p>

</form>

</body>

</html>

- Program 작성

Ex) TableTest.java

import java.io.*;

import java.text.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public class TableTest extends HttpServlet {

String DB_URL = "jdbc:oracle:thin:@comedudb2.cs.ucla.edu:1521:COMORA2";

String DB_USER="";

String DB_PASSWD="";

String DB_TABLE="";

Connection conn;

Statement  stmt;

ResultSet  rset;

ResultSetMetaData rsmd;

int    i;

int    rowno=1;

int    colsize;

String header="";

String col="";

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException

{

try{

// REQUEST from a client to a server...

String clientURL = request.getRemoteAddr();

String DB_USER   = request.getParameter("userid");

String DB_PASSWD = request.getParameter("passwd");

String DB_TABLE = request.getParameter("table");

// RESPONSE from a server to a client...

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head>");

out.println("<title>" + " TableTest " + "</title>");

out.println("</head>");

out.println(" <body bgcolor=\"yellow\" text=\"black\" link=\"blue\" "

+" vlink=\"purple\" alink=\"red\" >");	// Body...

out.println("<p align=\"center\"><font size=\"5\" FACE=\"arial\"><b> "

+ " TableTest.class "+"</b></font></p>");

out.println(" Request client addr: "+clientURL+"<BR><BR>");

Class.forName("oracle.jdbc.driver.OracleDriver");

conn = DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);

stmt = conn.createStatement();

rset = stmt.executeQuery("select * from "+DB_TABLE);

rsmd	= rset.getMetaData();

colsize = rsmd.getColumnCount();

header="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";	for(i=1;i<=colsize;i++){

header=header+"&nbsp;"+rsmd.getColumnLabel(i);

}

out.println(header+"<BR>");

col="&nbsp;"; rowno=1;

while(rset.next()){

for(i=1;i<=colsize;i++){

col = col+"&nbsp;"+rset.getString(i);

}

out.println("Row "+rowno+"&nbsp;:&nbsp;"+col+"<BR>");

rowno++; col="&nbsp;";

}

out.println("<BR><BR><a href=\"/tykim/tabletest.html\"> Back </a>");

rset.close();

stmt.close();

conn.close();

out.println("</body>");

out.println("</html>");

}catch(SQLException e){

String state=e.getSQLState();

response.setContentType("text/html");

PrintWriter out = response.getWriter();

if(state.equals("72000"))

out.println("\nERROR: user_id/passwd unknown...");

else

out.println("\nERROR: SQL query error...");

}catch(Exception e){

e.printStackTrace();

}

}// End of doPost

}

□Session

- User 작업들의 묶음

Ex)	Login

Session #1

Logout

- HTTP: Sessionless protocol

① connect

② request/response

③ disconnect

∀ Do not 'remember' previous works.

- How to implement a □session□ on the Web?

Ex) E-Commerce의 경우

Login

Buy book #1

Buy book #2

Refund book #3

Logout

JSP Overview

□Idea

- ASP/PHP와 같이 HTML을 사용하는 곳에는 HTML을 사용하고, programming logic이 들어가는 곳에는 특별한 tag(<%@ %>, <%! %>)를 사용하여 program을 작성.

Ex) JSP page - date.jsp

<%@ page import = "java.util.Date" %>

<%! Date today = new Date(); %>

<HTML>

<HEAD>

</HEAD>

</BODY	bgcolor="white" text="black" link="blue" vlink="purple" alink="red">

Hello, Today is <%= today.getDate() %>

</BODY>

</HTML>

□특징

- JSP page(xxx.jsp)의 Interface와 logic 부분을 분리하여 제작

①Interface: HTML, XML 사용

②Logic: JSP tag, Beans, EJB(Enterprise Java Beans)를 사용

∀ HTML/XML 부분: user에게 그대로 보여줌.

JSP tag: JSP engine에서 해석/수행되어 HTML/XML tag로 이루어진 결과를 browser에 전송

- Component의 재사용

□기존에 EJB로 만들어진 component가 있다면 JSP page안에 JSP tag를 사용하여 넣어서 수행이 가능.

∀ Program 개발자: Component를 개발

Web 개발자: Web page를 개발하고, 필요한 logic부분은 갖다가 사용

- Java 특징 계승: 모든 JSP page는 Java Servlet code로 만들어진 후에 compile되므로 Java의 장점을 그대로 수용.

- 쉬운 page 작성: xxx.jsp는 program 수행시 code의 변경 유무를 자동으로 판단해 compile하므로 Servlet처럼 다시 compile하는 번거로움이 없음.

JSP Programming

□

Wireless DB Access

□