Server-side Programming

Download Report

Transcript Server-side Programming

Server-side Programming
Copyright (C) 2009 Dr.Yong Uk Song
Yonsei University Wonju Campus
Architecture of WWW
user
input
GUI
user
output
content
File Input
request with
arguments
Web
Browser
HTTP
response
Web Server
HTML
file
CGI input
CGI
CGI output
CGI
program
Architecture of WWW
 What happens if Web servers support only HTML files?
Architecture of WWW (?)
user
input
GUI
user
output
content
File Input
request with
arguments
Web
Browser
HTTP
response
Web Server
HTML
file
CGI input
CGI
CGI output
CGI
program
Architecture of WWW
 What happens if Web servers support only HTML files?
 Static Web Pages vs. Dynamic Web Pages
 The dynamic Web pages are used for:
 Login
 Registration
 Shopping cart
 Payment
 Enrollment
…
Dynamic Web Pages
 What if Web servers themselves process the dynamics?
 Fast
 Developing Web servers requires expertise, so it would be
complicated and even risky for application developers to modify
a Web server.
 Alternative approach?
 An independent program executed by a Web server
Architecture of WWW
user
input
GUI
user
output
content
File Input
request with
arguments
Web
Browser
HTTP
response
Web Server
HTML
file
CGI input
CGI
CGI output
CGI
program
Dynamic Web Pages
 Requirements for Dynamic Web Pages
 User input
 → Webform by HTML FORM Tag
 Processing based on the user input
 → CGI standard for the interface between a Web server and a CGI
program
Digression
Webform
Webform
 A webform on a web page allows a user to enter data that is
sent to a server for processing.
 Webforms resemble paper forms because internet users fill
out the forms using checkboxes, radio buttons, or text fields.
 For example, webforms can be used to enter shipping or
credit card data to order a product or can be used to retrieve
data (e.g., searching on a search engine).
Webform: FORM Tag
 Syntax
<FORM
METHOD="POST"/"GET"
ACTION="server-side-program"
ENCTYPE="application/x-www-form-urlencoded">
...
</FORM>
 The FORM tag is just an envelop for a Webform. Additional
tags like INPUT, TEXTAREA, SELECT are required for a
Webform.
Webform: INPUT Tag
 Syntax
<INPUT NAME="name"
VALUE="value"
SIZE="n"
MAXLENGTH="n"
TYPE = TEXT/PASSWORD
/CHECKBOX/RADIO
/SUBMIT/RESET>
 Used to input a line of characters
Webform: INPUT Tag
 e.g.
<HTML>
<BODY>
<FORM METHOD="POST" ACTION="login.jsp">
Username: <INPUT TYPE="TEXT" NAME="UN"> <BR>
Password: <INPUT TYPE="PASSWORD" NAME="PW">
<BR>
<INPUT TYPE="SUBMIT" VALUE="Login">
</FORM>
</BODY>
</HTML>
Webform: TEXTAREA Tag
 Syntax
<TEXTAREA NAME="name" ROWS="n" COLS="n">
Line 1
Line 2
…
Line n
</TEXTAREA>
 Used to input multiple lines of text
Webform: TEXTAREA Tag
 e.g.
<HTML>
<BODY>
<FORM METHOD="POST" ACTION="hello.jsp">
<DL>
<DT>
<B> Comment:</B>
<DD>
<TEXTAREA NAME="Comment" ROWS="8" COLS="55">
Hello!
How is it going?
Fine, thank you.
</TEXTAREA>
</DL>
</FORM>
</BODY>
</HTML>
Webform: SELECT Tag
 Syntax
<SELECT NAME="name" SIZE="n" [MULTIPLE]>
<OPTION> option 1
<OPTION> option 2
…
<OPTION> option n
</SELECT>
 Used to support a list box or a combo box
Webform: SELECT Tag
 e.g.
<HTML>
<BODY>
<FORM METHOD="POST" ACTION="select.jsp">
<SELECT NAME="group" SIZE="3" MULTIPLE>
<OPTION> Title
<OPTION> Description
<OPTION> URL
</SELECT>
</FORM>
</BODY>
</HTML>
Exercise 1: Edit Box <INPUT TYPE="TEXT" …>
Exercise 2: Edit Box with Initial Value
<INPUT TYPE="TEXT" VALUE="Song" …>
Exercise 3: Edit Box and Button
<INPUT TYPE="SUBMIT" …>
Exercise 4: Edit Box and Button <BR>
Exercise 5: Login
Exercise 6: Check Box
<INPUT TYPE="CHECKBOX" …>
Exercise 7: Radio Button
<INPUT TYPE="RADIO" NAME="…" VALUE="…">
Exercise 8: Form with Table
Exercise 9: Colspan <TD COLSPAN="2">…</TD>
Exercise 10: Colspan and Align
<TD COLSPAN="2" ALIGN="CENTER">…</TD>
Exercise 11: Table without Border
Exercise 12: General Form
Common Gateway Interface
(CGI)
Common Gateway Interface
 The Common Gateway Interface (CGI) is a standard protocol for
interfacing external application software with an information
server, commonly a web server.
 The two basic methods for the Web server to do this are the
following:
 If the request identifies a file stored on disk, then return the contents
of that file.
 If the request identifies an executable command and possibly
arguments, then run the command and return its output.
 CGI defines a standard way of doing the second. It defines how
information about the server and the request is passed to the
command in the form of arguments and environment variables,
and how the command can pass back extra information about the
output (such as the type) in the form of headers.
Architecture of WWW
user
input
GUI
user
output
content
File Input
request with
arguments
Web
Browser
HTTP
response
Web Server
HTML
file
CGI input
CGI
CGI output
CGI
program
CGI: Input

Input Media
 Environment Variable
 C/C++ : char *getenv(char *)
 Standard Input
 C/C++ : int scanf(char *, …), int getchar( ), …

Request
 GET method
 Environment Variable : QUERY_STRING
 C/C++ : getenv("QUERY_STRING") → "name=yusong&msg=Hello%2C+world%21"
 POST method
 Environment Variable : CONTENT_LENGTH
 Standard Input
 C/C++ : getenv("CONTENT_LENGTH") → "33"
 C/C++ : scanf("%s", …) → "name=yusong&msg=Hello%2C+world%21"

Request Format
 name1=value1&name2=value2&…&namen=valuen
 Values are encoded by URL encoding rule.
 e.g.
name=yusong&msg=Hello%2C+world%21
CGI: Input
Description
Environment Variables
are not request-specific and are set for all requests
SERVER_SOFTWARE
SERVER_NAME
GATEWAY_INTERFACE
are specific to the request being fulfilled by the
gateway program
SERVER_PROTOCOL
SERVER_PORT
REQUEST_METHOD
PATH_INFO
PATH_TRANSLATED
SCRIPT_NAME
QUERY_STRING
REMOTE_HOST
REMOTE_ADDR
AUTH_TYPE
REMOTE_USER
REMOTE_IDENT
CONTENT_TYPE
CONTENT_LENGTH
header lines received from the client
HTTP_ACCEPT
HTTP_USER_AGENT
Digression: URL Encoding
 Encoding rules
 A ~ Z, a ~ z, 0 ~ 1 → no conversion
 Blank
 Other characters
→ +
→ %xx (Hexadecimal ASCII Code)
 e.g.
Hello, world! → Hello%2C+world%21
CGI: Output
 Output Medium
 Standard output
 C/C++ : int printf(char *, …)
 e.g.) C/C++
printf("Content-type: text/html\n");
printf("\n");
printf("<HTML>\n");
…
printf("</HTML>\n");
// Header
// crlf
// Entity body
CGI: Example - GET
<HTML>
<BODY>
<FORM METHOD=GET ACTION="get.cgi">
Username: <INPUT TYPE=TEXT NAME=username> <BR>
Password: <INPUT TYPE=PASSWORD NAME=password>
<BR>
<INPUT TYPE=SUBMIT VALUE="OK">
</FORM>
</BODY>
</HTML>
CGI: Example - GET
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void main(void)
{
char *query_string;
query_string = getenv("QUERY_STRING");
printf("Content-type: text/html\n\n");
printf("<HTML>\n");
printf("<BODY>\n");
printf("Your input: %s\n", query_string);
printf("</BODY>\n");
printf("</HTML>\n");
}
CGI: Example - GET
CGI: Example - POST
<HTML>
<BODY>
<FORM METHOD=POST ACTION="post.cgi">
Username: <INPUT TYPE=TEXT NAME=username> <BR>
Password: <INPUT TYPE=PASSWORD NAME=password>
<BR>
<INPUT TYPE=SUBMIT VALUE="OK">
</FORM>
</BODY>
</HTML>
CGI: Example - POST
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void main(void)
{
int i, length, c;
length = atoi(getenv("CONTENT_LENGTH"));
printf("Content-type: text/html\n\n");
printf("<HTML>\n<BODY>\nYour input: ");
for (i = 0; i < length; i++)
{
c = getchar();
putchar(c);
}
printf("\n</BODY>\n</HTML>\n");
}
CGI: Example - POST
CGI: Drawbacks
 Drawbacks
 This is a low-tech approach.
 Calling a command (i.e. running a program) generally means the
invocation of a newly created process. Starting up the process can
take up much more time and memory than the actual work of
generating the output, especially when the program still needs to be
interpreted or compiled.
 If the program is called often, the workload can quickly overwhelm
Web servers.
 Alternatives
 Simple Common Gateway Interface(SCGI), FastCGI
 ASP (Active Server Pages), PHP (Personal Home Page, Professional
Hypertext Preprocessor, …, PHP: Hypertext Preprocessor), JSP
(Java Server Pages)
Digression
Web Server Setup in NetBeans IDE
Web Server Setup An Empty Folder
Web Server Setup Tools/Servers
Web Server Setup GlassFish V2
Web Server Setup Create Personal Domain
Web Server Setup Non-existent Folder
Web Server Setup admin/adminadmin
Web Server Setup Port Numbers
Web Server Setup
Creating New Project
Creating New Project
Creating New Project GlassFish V2 (1)
Creating New Project
Java Server Pages (JSP)
JSP: Getting Started
What is JSP?
 Java Server Pages
 Based on Java programming language
 State-of-the-art technology to build Web pages having
dynamic contents
 Contrasts to Web pages having static contents by using HTML
only
 JSP-based Web pages delivers "different" Web contents to
different persons, while HTML-based Web pages delivers
"same" Web contents to different persons.
JSP: Hello, World! - I JSP1/hello.html
<HTML>
<BODY>
Hello, World!
</BODY>
</HTML>
JSP: Hello, World! - II JSP1/hello.jsp
<HTML>
Scriptlet
<BODY>
<%
String visitor = request.getParameter("name");
if (visitor == null) visitor = "World";
%>
Hello, <%= visitor %>!
</BODY>
Expression
</HTML>
JSP: Visiting Hello, World! - II
 http://localhost:8080/JSP1/hello.jsp
 http://localhost:8080/JSP1/hello.jsp?name=Song
Quiz 3: "Hello, Dr. Song!",
revisited on JSP
Quiz 3 "Hello, Dr. Song!", revisited on
JSP
 Develop a JSP program which displays "Hello, Dr. Song!" and an
enrollment form on a Web browser. (See next page for example)
 Project name
 JSPHelloDrSong
 Note:
 Due date: 07/29/2009
 This quiz is a group project.
 Each group of students should bring a program developed by each
group in a memory device on the due date and run the program
during the class.
 Bring only the folders and files under "web" folder. Students would
create a new NetBeans project for the program during the class.
 Instructor will evaluate the running result.
Quiz 3 "Hello, Dr. Song!", revisited on
JSP
Evaluating Quiz 3
 Run NetBeans IDE.
 Set up a Web server domain for your computer.
 Create a project "JSPHelloDrSong".
 Overwrite "*.html" and "*.jsp" files under the "web" folder
in your memory device onto the "web" folder under the
"NetBeansProjects/JSPHelloDrSong" folder.
 Wait until instructor investigates the program.
JSP: Scripting elements
JSP Tag Styles
 Scripting-oriented tags
 <% … %>
 e.g.
 <%@ page import="java.io.*" %>
 <% r = 7.5; %>
 <%= r * 2 %>
 XML-based tags
 <jsp:tag attribute1=value1 … />
 <jsp:tag attribute1=value1 …> … </jsp:tag>
 e.g.
 <jsp:directive.page import="java.io.*" />
Scripting-oriented Tags
 JSP Directives
 <%@ page … %>
 e.g. <%@ page import="java.io.*" %>
 <%@ include … %>
 <%@ taglib … %>
 Scripting Elements
 <%! declarations %>
 <%= expression %>
 e.g. <%= r * 2 %>
 <% scriptlet %>
 e.g. <% r = 7.5; %>
Scripting Element: Expression
 Syntax
<%= expression %>
 e.g.
<%= a + b * 3 - f / d %>
<%= Math.sin(3.141592) %>
Scripting Element: Expression
JSP2/index.jsp
<HTML>
<BODY>
sin(3.14) = <%= Math.sin(3.14) %>
</BODY>
</HTML>
Scripting Element: Scriptlet
 Syntax
<% statements %>
 e.g.
<%
int i, f, s = 0;
for (i = 1, f = 0; i < f; i++)
s += i;
%>
Scripting Element: Scriptlet JSP3/index.jsp
<HTML>
<BODY>
<%
int i;
for (i = 0; i < 100; i++) {
out.println(i + "<BR>");
}
%>
</BODY>
</HTML>
Scripting Element: Hello, World! - II
<HTML>
<BODY>
<%
String visitor = request.getParameter("name");
if (visitor == null) visitor = "World";
%>
Hello, <%= visitor %>!
</BODY>
</HTML>
JSP : Implicit Objects
Implicit Objects
 Servlet-related objects
 page
 config
 Input/Output objects
 request
 response
 out
 Contextual objects
 session
 application
 pageContext
 Error-processing objects
 exception
JSP : request Object
request Object
 Request Contents
 getParameterNames()
 getParameter(String name)
 getParameterValues(String
name)
 Request Header






getHeaderNames()
getHeader(String name)
getHeaders(String name)
getIntHeader(String name)
getDateHeader(String name)
getCookies()
 Others
 getMethod()
 getRequestURL()
 getQueryString()
 getSession(flag)
 getRequestDispatcher(path)
 getRemoteHost()
 getRemoteAddr()
 getRemoteUser()
 getSession(flag)
request: getParameter JSP4
login.html
login.jsp
<HTML>
<BODY>
<FORM METHOD=POST
ACTION="login.jsp">
Username: <INPUT TYPE=TEXT
NAME="UN"> <BR>
Password: <INPUT TYPE=PASSWORD
NAME="PW"> <BR>
<INPUT TYPE=SUBMIT
VALUE="Login">
</FORM>
</BODY>
</HTML>
<HTML>
<BODY>
<%
String username =
request.getParameter("UN");
String password =
request.getParameter("PW");
out.println(username + "/" +
password);
%>
</BODY>
</HTML>
request: getParameter JSP4
 Request Message by a Web Browser
POST /JSP4/login.jsp HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 18
crlf
UN=yusong&PW=10000
Exercise 1: Edit Box JSP4X1
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
<input type=text name="username" value="Song"> <BR>
<input type=submit name="submit" value=" OK ">
</form>
</body>
</html>
Exercise 2: Login JSP4X2
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
Username: <input type=text name="un"> <BR>
Password: <input type=password name="pw"> <BR>
<input type=submit name="submit" value=" OK ">
</form>
</body>
</html>
Exercise 3: Check Box JSP4X3
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
Username: <input type=text name="un"> <BR>
Password: <input type=password name="pw"> <BR>
<input type=checkbox name="bs"> Secure mail <BR>
<input type=submit name="submit" value=" OK ">
</form>
</body>
</html>
Exercise 4: Radio Button JSP4X4
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
Username: <input type=text name="un"> <BR>
Password: <input type=password name="pw"> <BR>
<input type=checkbox name="bs"> Secure mail <BR>
<input type=radio name="sx"> Female <input type=radio name="sx">
Male<BR>
<input type=submit name="submit" value=" OK ">
</form>
</body>
</html>
Exercise 5: Colspan and Align JSP4X5
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
<table>
<tr>
<td>Username:</td> <td><input type=text name="un"> </td>
</tr>
<tr>
<td>Password:</td> <td><input type=password name="pw"> </td>
</tr>
<tr>
<td colspan=2 align="center"><input type=submit name="submit" value="
OK "></td>
</tr>
</form>
</body>
</html>
Exercise 6: General Form JSP4X6
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
<table>
<tr> <td>Username:</td> <td><input type=text name="un"> </td> </tr>
<tr> <td>Password:</td> <td><input type=password name="pw"> </td> </tr>
<tr> <td>Gender:</td> <td><input type=radio name="sx">F <input type=radio
name="sx">M</td> </tr>
<tr>
<td>Hobby:</td> <td><input type=checkbox name="h1">Music <input
type=checkbox name="h2">Stamp <input type=checkbox name="h3">Hiking
<input type=checkbox name="h4">Soccer</td>
</tr>
<tr> <td colspan=2 align="center"><input type=submit name="submit" value=" OK
"></td> </tr>
</form>
</body>
</html>
Digression
HttpURLConnection Class, Revisited
HTTP (5) : HttpURLConnection Class,
revisited
 Exercise
 Make a Java program such that:
 Send a request to the Web page at
"http://localhost:8080/HTTP2X1Server/register.jsp", with an entity
body of
"name=X&username=X&password=X&password2=X&address=X&zip
=X".
 Print out the response from the Web server.
 Project names
 HTTP2X1Server/register.html
 HTTP2X1Server/register.jsp
 HTTP5X1Client (which emulates the action after the regsiter.html)
Website (2) : Register, revisited
HTTP2X1Server/register.html
<html>
<body>
<h1>Register</h1>
<form method="post" action="login.jsp">
<table>
<tr> <td>Name:</td> <td><input type="text" name="name"></td> </tr>
<tr> <td>User name:</td> <td><input type="text" name="username"></td> </tr>
<tr> <td>Password:</td> <td><input type="password" name="password"></td>
</tr>
<tr> <td>Password (retype):</td> <td><input type="password" name="password2">
</td> </tr>
<tr> <td>Address:</td> <td><input type="text" name="address"></td> </tr>
<tr> <td>ZIP code:</td> <td><input type="text" name="zip"></td> </tr>
<tr> <td colspan="2"><input type="submit" value="Register"></td> </tr>
</table>
</form>
</body>
</html>
Website (2) : Register, revisited
HTTP2X1Server/register.jsp
<%
String name = request.getParameter("name");
String username = request.getParameter("username");
String password = request.getParameter("password");
String password2 = request.getParameter("password2");
String address = request.getParameter("address");
String zip = request.getParameter("zip");
%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Hello "<%= name %>"!</h1>
<h3>Your information (<%= username %>, <%= password %>, <%= password2
%>, <%= address %>, <%= zip %>) will be processed later.</h3>
</body>
</html>
HTTP (5) : HttpURLConnection Class,
revisited HTTP5X1Client
import java.io.*;
import java.net.*;
try {
URL url = new URL("http://localhost:8080/HTTP2X1Server/register.jsp");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Request
urlConnection.setRequestMethod("POST");
urlConnection.setFollowRedirects(true);
URL
urlConnection.setDoOutput(true);
PrintWriter output = new PrintWriter(urlConnection.getOutputStream(), true);
output.print("name=X&username=X&password=X&password2=X&address=X&zip=X");
output.flush();
// Response
String res = urlConnection.getResponseMessage();
System.out.println("Response message - " + res);
Request
String enc = urlConnection.getContentType();
System.out.println("Content Type - " + enc);
BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
for (; (line = input.readLine()) != null;) {
System.out.println(line);
}
urlConnection.disconnect();
} catch (Exception e) {
Response Entity Body
System.err.println(e);
}
HTTP (5) : HttpURLConnection Class,
revisited
 Request Message
POST /HTTP2X1Server/register.jsp HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 56
crlf
name=X&username=X&password=X&password2=X&address=
X&zip=X
HTTP (5) : HttpURLConnection Class,
revisited
 Response Message
Response message - OK
Content Type - text/html;charset=UTF-8
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Hello "X"!</h1>
<h3>Your information (X, X, X, X, X) will be processed later.</h3>
</body>
</html>
JSP : response Object
response Object

Content Setting











setContentType()
getCharacterEncoding()
addCookie(cookie)
containsHeader(name)
setHeader(String name, String value)
setIntHeader(String name, int value)
setDateHeader(String name, Date value)
addHeader(String name, String value)
addIntHeader(String name, int value)
addDateHeader(String name, Date value)
Response Setting
 setStatus(code)
 sendError(status, msg)
 sendRedirect(url)

URL Encoding
 encodeRedirectURL(url)
 encodeURL(name)
response: sendRedirect JSP5
login.html
login.jsp
<HTML>
<BODY>
<FORM METHOD=POST
ACTION="login.jsp">
Username: <INPUT TYPE=TEXT
NAME="UN"> <BR>
Password: <INPUT TYPE=PASSWORD
NAME="PW"> <BR>
<INPUT TYPE=SUBMIT
VALUE="Login">
</FORM>
</BODY>
</HTML>
<HTML>
<BODY>
<%
String username =
request.getParameter("UN");
String password =
request.getParameter("PW");
if (username.equals("a") &&
password.equals("b"))
out.println("Login success!<BR>");
else
response.sendRedirect("login.html");
%>
</BODY>
</HTML>
response: sendRedirect
 Response Message
HTTP/1.1 302 Found
Location: http://localhost:8080/JSP5/login.html
crlf
We moved.
JSP : out Object
out Object
 print()
 println()
 isAutoFlush()
 getBufferSize()
 getRemaining()
 clearBuffer()
 clear()
 newLine()
 flush()
 close()
out: print, println JSP61
login.html
login.jsp
<HTML>
<BODY>
<FORM METHOD=POST
ACTION="login.jsp">
Username: <INPUT TYPE=TEXT
NAME="UN"> <BR>
Password: <INPUT TYPE=PASSWORD
NAME="PW"> <BR>
<INPUT TYPE=SUBMIT
VALUE="Login">
</FORM>
</BODY>
</HTML>
<HTML>
<BODY>
<%
String username =
request.getParameter("UN");
String password =
request.getParameter("PW");
out.print(username);
out.print(" / ");
out.println(password);
%>
</BODY>
</HTML>
out: print, println JSP62
login.html
login.jsp
<HTML>
<BODY>
<FORM METHOD=POST
ACTION="login.jsp">
Username: <INPUT TYPE=TEXT
NAME="UN"> <BR>
Password: <INPUT TYPE=PASSWORD
NAME="PW"> <BR>
<INPUT TYPE=SUBMIT
VALUE="Login">
</FORM>
</BODY>
</HTML>
<HTML>
<BODY>
<%
String username =
request.getParameter("UN");
String password =
request.getParameter("PW");
%>
<%= username %> /
<%= password %>
</BODY>
</HTML>
out: print, println
Scriptlet
Expression
<HTML>
<BODY>
<%
int age = 20;
if (a < 13)
out.println("Child");
else if (a < 20)
out.println("Teenager");
else
out.println("Not Teenager");
%>
</BODY>
</HTML>
<HTML>
<BODY>
<%
int age = 20;
if (a < 13)%>
<%= "Child"%>
<%else if (a < 20) %>
<%= "Teenager"%>
<%else%>
<%= "Not Teenager"%>
</BODY>
</HTML>
Exercise 1: Check Box JSP6X1
Exercise 1: Check Box JSP6X1/login.html
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
Username: <input type=text name="un"> <BR>
Password: <input type=password name="pw"> <BR>
<input type=checkbox name="bs"> Secure mail <BR>
<input type=submit name="submit" value=" OK ">
</form>
</body>
</html>
Exercise 2: Radio Button JSP6X2
Exercise 2: Radio Button JSP6X2/login.html
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
Username: <input type=text name="un"> <BR>
Password: <input type=password name="pw"> <BR>
<input type=checkbox name="bs"> Secure mail <BR>
<input type=radio name="sx"> Female <input type=radio name="sx">
Male<BR>
<input type=submit name="submit" value=" OK ">
</form>
</body>
</html>
Exercise 3: General Form JSP6X3
Exercise 3: General Form JSP6X3/login.html
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
<table>
<tr> <td>Username:</td> <td><input type=text name="un"> </td> </tr>
<tr> <td>Password:</td> <td><input type=password name="pw"> </td> </tr>
<tr> <td>Gender:</td> <td><input type=radio name="sx">F <input type=radio
name="sx">M</td> </tr>
<tr>
<td>Hobby:</td> <td><input type=checkbox name="h1">Music <input
type=checkbox name="h2">Stamp <input type=checkbox name="h3">Hiking
<input type=checkbox name="h4">Soccer</td>
</tr>
<tr> <td colspan=2 align="center"><input type=submit name="submit" value=" OK
"></td> </tr>
</form>
</body>
</html>
Exercise 4: Edit Box for Number
JSP6X4
Exercise 4: Edit Box for Number
JSP6X4/age.html
<html>
<body>
<h1>Web Programming</h1>
<form method=post action="a.jsp">
Age: <input type=text name="age"> <BR>
<input type=submit name="submit" value=" OK ">
</form>
</body>
</html>
Exercise 4: Edit Box for Number
JSP6X4/age.jsp
<HTML>
<BODY>
<%
String stringAge = request.getParameter("age");
int age = Integer.parseInt(stringAge);
if (age < 13)
out.println("Child");
else if (age < 20)
out.println("Teenager");
else
out.println("Not Teenager");
%>
</BODY>
</HTML>
JSP : session Object
Session
 A session is a semi-permanent interactive information exchange,




also known as a dialogue, a conversation or a meeting, between
two or more communicating devices, or between a computer and
user.
A session is set up or established at a certain point in time, and
torn down at a later point in time.
A session is typically, but not always, stateful, meaning that at least
one of the communicating parts need to save information about
the session history in order to be able to communicate.
A session in Web is established between a Web browser and a Web
server, and the server needs to save information about the session
history.
e.g.
 Login session
Session & HTTP
 Is HTTP stateful?
 Does HTTP support a session?
 Does HTTP have a mechanism to save information about the session
history.
 Basically, no!
 HTTP is not stateful but stateless.
 However, HTTP provides headers for "Cookies" such as Set-Cookie
and Cookie which can be used to support a session.
 The implicit object "session" in JSP provides a set of commands
for a JSP program to save information about the session history.
 This session object is based on the Set-Cookie and the Cookie headers
of HTTP.
session Object
 getAttribute(name)
 getId()
 getCreationTime()
 getLastAccessTime()
 getMaxInactiveInterval()
 setAttribute(name, object)
 setMaxInactiveInterval(second)
 isNew()
 invalidate()
Exercise 1: My Name
 Project name
 JSP7X1
 Write a HTML program (a.html):
 Input user's name
 Write a JSP program (a.jsp):
 Memorize the user's name
 Write another JSP program (b.jsp):
 Retrieve and output the user's name
Exercise 1: My Name JSP7X1/a.html
<HTML>
<BODY>
<FORM method=post action="a.jsp">
Name:<input type=text name="n"><br>
<input type=submit value="OK">
</FORM>
</BODY>
</HTML>
Exercise 1: My Name JSP7X1
a.jsp
<HTML>
<BODY>
<%
String name =
request.getParameter("n");
session.setAttribute("name",
name);
out.println("You can enter <A
HREF='b.jsp'>our
site</A><BR>");
%>
</BODY>
</HTML>
b.jsp
<HTML>
<BODY>
<%
String n =
(String)session.getAttribute(
"name");
out.println("Your name is ");
out.println(n);
out.println(". Right?");
%>
</BODY>
</HTML>
Exercise 2: My Hobby
 Project name
 JSP7X2
 Write a HTML program (a.html):
 Input user's hobbies by using check boxes
 Write a JSP program (a.jsp):
 Memorize the user's hobbies
 Write another JSP program (b.jsp):
 Retrieve and output the user's hobbies
Exercise 2: My Hobby JSP7X2/a.html
Exercise 3: SSN
 Project name
 JSP7X3
 Write a HTML program (a.html):
 Input user's social security number
 Write a JSP program (a.jsp):
 Memorize the user's SSN
 Write another JSP program (b.jsp):
 Retrieve and output the user's SSN
Exercise 4: Login JSP7X4
login.jsp
main.jsp
<HTML>
<BODY>
<%
String username = request.getParameter("UN");
String password = request.getParameter("PW");
if (username.equals("a") && password.equals("b"))
{
session.setAttribute("Username", username);
out.println("Login success!<BR>");
out.println("You can enter <A
HREF='main.jsp'>our site</A><BR>");
}
else
{
out.println("Login failed!<BR>");
out.println("You can NOT enter <A
HREF='main.jsp'>our site</A><BR>");
}
%>
</BODY>
</HTML>
<HTML>
<BODY>
<%
String username =
(String)session.getAttribute("Username");
if (username != null)
{
out.println("Welcome!<BR>");
out.println("You can see everything in our
site.<BR>");
}
else
{
out.println("You are not allowed
here.<BR>");
}
%>
</BODY>
</HTML>
session: invalidate JSP8
<HTML>
<BODY>
<%
session.invalidate();
out.println("<A HREF='main.jsp'>Main</A>");
%>
</BODY>
</HTML>
Exercise 1: Logout
 Project name
 JSP8X1
 Write a JSP program (logout.jsp):
 Invalidate user's session
 Redirect to "login.html"
Digression
Java Database Connectivity (JDBC)
Java Database Connectivity
 Definitions
 JDBC is a standard Java interface for connecting from Java to
relational databases.
 JDBC is an API for the Java programming language that defines
how a client may access a relational database.
 It provides methods for querying and updating data in a
database.
 The JDBC standard was defined by Sun Microsystems,
allowing individual providers to implement and extend the
standard with their own JDBC drivers.
Steps in JDBC Programming
 Create a database
 Create a table
 Set up connection between JSP (or Java) and the database
 e.g. ODBC
 JDBC Programming in JSP
JDBC: Create a database (MS Access)
JDBC: Create a database (MS Access)
JDBC: Create a database (MS Access)
Exercise 1: Create a database
 Create a database file named "mydb.mdb"
Exercise 2: Create a database
 Create a database file named "shop.mdb"
JDBC: Create a table (MS Access)
JDBC: Create a table (MS Access)
JDBC: Create a table (MS Access)
JDBC: Create a table (MS Access)
Exercise 1: Create a table
 Create a table named "customer" in database "mydb.mdb",
of which schema are:
Field
Type
Size
cname
Text
20
username
Text
10
password
Text
20
address
Text
50
Exercise 2: Create a table
 Create a table named "product" in database "shop.mdb", of
which schema are:
Field
Type
Size
PID
Text
10
pname
Text
20
color
Integer
price
Integer
size
Double
JDBC: Set up ODBC connection (MS
Access)
JDBC: Set up ODBC connection (MS
Access)
JDBC: Set up ODBC connection (MS
Access)
JDBC: Set up ODBC connection (MS
Access)
JDBC: Set up ODBC connection (MS
Access)
JDBC: Set up ODBC connection (MS
Access)
JDBC: Set up ODBC connection (MS
Access)
JDBC: Set up ODBC connection (MS
Access)
Exercise 1: Set up a connection
 Set up an ODBC connection between a MS-Access file
"mydb.mdb" and a DSN "mydsn".
Exercise 2: Set up a connection
 Set up an ODBC connection between a MS-Access file
"shop.mdb" and a DSN "shopdsn".
JDBC: JDBC Programming in JSP
(ODBC)
 Syntax
<%@ page import="java.sql.*" %>
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection
("jdbc:odbc:dsn", "user", "password");
Statement stmt = conn.createStatement();
stmt.execute("…");
// SQL statement here
ResultSet rs = stmt.getResultSet();
…
rs.next();
s = rs.getString();
* Black words: reserved words
…
* Violet words: what you must change
rs.close();
* Red words: what you may change
stmt.close();
conn.close();
JDBC: Example (1) (ODBC) JDBC1
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
ResultSet rs;
String query = "SELECT * FROM customer";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
JDBC: Example (2) (ODBC) JDBC1
stmt.execute(query);
rs = stmt.getResultSet();
while (rs.next())
{
out.println(rs.getString("f_name") + " / ");
out.println(rs.getString("f_username") + " / ");
out.println(rs.getString("f_password") + " / ");
out.println(rs.getString("f_address") + " / ");
out.println("<BR>");
}
rs.close();
stmt.close();
conn.close();
%>
</BODY>
</HTML>
JDBC: Example (1) (Oracle) JDBC1
<%@ page import="java.sql.*" %>
<%@ page import="oracle.jdbc.*" %>
<%@ page import="oracle.sql.*" %>
<HTML>
<BODY>
<%
String DB_URL = "jdbc:oracle:thin:@134.53.40.6:1521:SBA";
String DB_USER = "songyu";
String DB_PASSWORD = "songyu";
Connection conn;
Statement stmt;
ResultSet rs;
String query = "SELECT * FROM customer";
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
JDBC: Example (2) (Oracle) JDBC1
stmt.execute(query);
rs = stmt.getResultSet();
for (; rs.next();) {
out.println(rs.getString("f_name") + " / ");
out.println(rs.getString("f_username") + " / ");
out.println(rs.getString("f_password") + " / ");
out.println(rs.getString("f_address") + " / ");
out.println("<BR>");
}
rs.close();
stmt.close();
conn.close();
%>
</BODY>
</HTML>
Exercise 1: JDBC Programming JDBCX1
 Write a JSP program which displays all data in "customer"
table of "mydb.mdb" database.
Exercise 2: JDBC Programming and
Table JDBCX2
 Write a JSP program which displays all data in "customer"
table of "mydb.mdb" database by using TABLE tag of HTML.
Exercise 3: JDBC Programming JDBCX3
 Write a JSP program which displays all data in "product"
table of "shop.mdb" database.
Exercise 4: JDBC Programming and
Table JDBCX4
 Write a JSP program which displays all data in "product"
table of "shop.mdb" database by using TABLE tag of HTML.
Digression
Structured Query Language (SQL)
INSERT
SQL: INSERT
INSERT INTO customer
(f_username, f_password, f_name, f_address)
VALUES
('yusong', '1234', 'Yong Uk Song', '234, Maji, Wonju')
INSERT INTO emp
(empno, ename, job, sal, comm, deptno)
VALUES
(7890, 'JINKS', 'CLERK', 1.2E3, NULL, 40)
SQL: INSERT Simple Sample (1)
SQL1S
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
String query = "INSERT INTO customer (f_name, f_username,
f_password, f_address) VALUES ('Yong Uk Song', 'yusong', '1234',
'234, Maji, Wonju')";
SQL: INSERT Simple Sample (2)
SQL1S
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL,
DB_USER, DB_PASSWORD);
stmt = conn.createStatement();
stmt.execute(query);
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: INSERT Advanced Sample (1)
SQL1A
<HTML>
<BODY>
<FORM method="post" action="insert.jsp">
Name:<input type=text name=name><br>
Userame:<input type=text name=username><br>
Password:<input type=text name=password><br>
Address:<input type=text name=address><br>
<input type=submit value="Add">
</FORM>
</BODY>
</HTML>
SQL: INSERT Advanced Sample (2)
SQL1A
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String name = request.getParameter("name");
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String query = "INSERT INTO customer (f_name, f_username,
f_password, f_address) VALUES ('" + name + "', '" + username
+ "', '" + password + "', '" + address + "')";
SQL: INSERT Advanced Sample (3)
SQL1A
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
stmt.execute(query);
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: INSERT Simple vs. Advanced
 "INSERT INTO customer (f_name, f_username, f_password,
f_address) VALUES ('Yong Uk Song', 'yusong', '1234', '234,
Maji, Wonju')"
 "INSERT INTO customer (f_name, f_username, f_password,
f_address) VALUES (' " + name + " ', ' " + username + " ', '
" + password + " ', ' " + address + " ')"
Exercise 1: INSERT SQL1X1
 Write a JSP program which adds a data into the "product"
table of "shop.mdb" database.
Exercise 2: INSERT SQL1X2
 Write an HTML file and a JSP program which inputs a data
from a user and adds the data into the "product" table of
"shop.mdb" database.
UPDATE
SQL: UPDATE
UPDATE customer
SET f_name = 'Hong', f_address = 'Oxford'
WHERE
f_username = 'yusong'
UPDATE emp
SET comm = NULL
WHERE
job = 'TRAINEE'
SQL: UPDATE Simple Sample (1)
SQL2S
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
String query = "UPDATE customer SET address='Wonju'
WHERE username='yusong' ";
SQL: UPDATE Simple Sample (2)
SQL2S
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL,
DB_USER, DB_PASSWORD);
stmt = conn.createStatement();
stmt.execute(query);
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: UPDATE Advanced Sample (1)
SQL2A
<HTML>
<BODY>
<FORM method="post" action="update.jsp">
Name:<input type=text name=name><br>
Userame:<input type=text name=username><br>
Password:<input type=text name=password><br>
Address:<input type=text name=address><br>
<input type=submit value="Update">
</FORM>
</BODY>
</HTML>
SQL: UPDATE Advanced Sample (2)
SQL2A
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String name = request.getParameter("name");
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String query = "UPDATE customer SET f_address='" +
address + "' WHERE f_username='" + username + "'";
SQL: UPDATE Advanced Sample (3)
SQL2A
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
stmt.execute(query);
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: UPDATE Simple vs. Advanced
 "UPDATE customer SET f_address='Wonju' WHERE
f_username='yusong' "
 "UPDATE customer SET f_address=' " + address + " '
WHERE f_username=' " + username + " ' "
Exercise 1: UPDATE SQL2X1
 Write a JSP program which updates a data in the "product"
table of "shop. mdb" database.
Exercise 2: UPDATE SQL2X2
 Write an HTML file and a JSP program which inputs a data
from a user and updates the data in the "product" table of
"shop.mdb" database.
DELETE
SQL: DELETE
DELETE FROM customer
WHERE
f_username = 'yusong'
DELETE FROM emp
WHERE
job = 'SALESMAN'
AND comm < 100
SELECT
SQL: SELECT (1)
SELECT f_name, f_address
FROM customer
WHERE f_username = 'yusong'
SELECT *
FROM tblasp
ORDER BY name
WHERE age < 30
SQL: SELECT (2)
SELECT *
FROM emp
WHERE deptno = 40
SELECT ename, job, sal, deptno
FROM emp
WHERE NOT (job = 'SALESMAN' AND deptno = 30)
ORDER BY deptno ASC, sal DESC
SQL: SELECT Simple Sample (1)
SQL4S
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
ResultSet rs;
String query = "SELECT password FROM customer WHERE
username='yusong'";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
SQL: SELECT Simple Sample (2)
SQL4S
stmt.execute(query);
rs = stmt.getResultSet();
if (!rs.next())
{
out.println("Unknown user");
}
else if (rs.getString("f_password").equals("1234"))
{
out.println("Login success");
}
else
{
out.println("Login failure");
}
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: Result Set (1)
Firstly,
yuso 123 Yong
ng
4 Song
Wonju,
Korea
wki
m
Seoul,
Korea
abc Woo
d Kim
spark qw Sang
er Park
slee
Suwon,
Korea
asd Soo Lee Ohio,
f
U.S.A
rs.getString("f_username")
→ Error
rs.getString("f_password")
→ Error
rs.getString("f_name")
→ Error
rs.getString("f_address")
→ Error
SQL: Result Set (2)
rs.next( )
→ true
yuso 123 Yong
ng
4 Song
Wonju,
Korea
wki
m
Seoul,
Korea
abc Woo
d Kim
spark qw Sang
er Park
slee
Suwon,
Korea
asd Soo Lee Ohio,
f
U.S.A
rs.getString("f_username")
→ "yusong"
rs.getString("f_password")
→ "1234"
rs.getString("f_name")
→ "Yong Song"
rs.getString("f_address")
→ "Wonju, Korea"
SQL: Result Set (3)
rs.next( )
→ true
yuso 123 Yong
ng
4 Song
Wonju,
Korea
wki
m
Seoul,
Korea
abc Woo
d Kim
spark qw Sang
er Park
slee
Suwon,
Korea
asd Soo Lee Ohio,
f
U.S.A
rs.getString("f_username")
→ "wkim"
rs.getString("f_password")
→ "abcd"
rs.getString("f_name")
→ "Woo Kim"
rs.getString("f_address")
→ "Seoul, Korea"
SQL: Result Set (4)
rs.next( )
→ true
yuso 123 Yong
ng
4 Song
Wonju,
Korea
wki
m
Seoul,
Korea
abc Woo
d Kim
spark qw Sang
er Park
slee
Suwon,
Korea
asd Soo Lee Ohio,
f
U.S.A
rs.getString("f_username")
→ "spark"
rs.getString("f_password")
→ "qwer"
rs.getString("f_name")
→ "Sang Park"
rs.getString("f_address")
→ "Suwon, Korea"
SQL: Result Set (5)
rs.next( )
→ true
yuso 123 Yong
ng
4 Song
Wonju,
Korea
wki
m
Seoul,
Korea
abc Woo
d Kim
spark qw Sang
er Park
slee
Suwon,
Korea
asd Soo Lee Ohio,
f
U.S.A
rs.getString("f_username")
→ "slee"
rs.getString("f_password")
→ "asdf"
rs.getString("f_name")
→ "Soo Lee"
rs.getString("f_address")
→ "Ohio, U.S.A"
SQL: Result Set (6)
rs.next( )
→ true
yuso 123 Yong
ng
4 Song
Wonju,
Korea
wki
m
Seoul,
Korea
abc Woo
d Kim
spark qw Sang
er Park
slee
Suwon,
Korea
asd Soo Lee Ohio,
f
U.S.A
rs.getString("f_username")
→ "jhong"
rs.getString("f_password")
→ "zxcv"
rs.getString("f_name")
→ "June Hong"
rs.getString("f_address")
→ "Seoul, Korea"
SQL: Result Set (7)
rs.next( )
→ false
yuso 123 Yong
ng
4 Song
Wonju,
Korea
wki
m
Seoul,
Korea
abc Woo
d Kim
spark qw Sang
er Park
slee
Suwon,
Korea
asd Soo Lee Ohio,
f
U.S.A
rs.getString("f_username")
→ Error
rs.getString("f_password")
→ Error
rs.getString("f_name")
→ Error
rs.getString("f_address")
→ Error
SQL: SELECT Advanced Sample (1)
SQL4A
<HTML>
<BODY>
<FORM method="post" action="login.jsp">
Userame:<input type=text name=username><br>
Password:<input type=text name=password><br>
<input type=submit value="Login">
</FORM>
</BODY>
</HTML>
SQL: SELECT Advanced Sample (2)
SQL4A
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String query = "SELECT f_password FROM customer WHERE
f_username='" + username + "'";
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
SQL: SELECT Advanced Sample (3)
SQL4A
stmt = conn.createStatement();
stmt.execute(query);
rs = stmt.getResultSet();
if (!rs.next())
{
out.println("Unknown user");
}
else if (rs.getString("f_password").equals(password))
{
out.println("Login success");
}
else
{
out.println("Login failure");
}
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: SELECT Simple vs. Advanced
 "SELECT f_password FROM customer WHERE
f_username='yusong'"
 "SELECT f_password FROM customer WHERE
f_username='" + username + "'"
SQL: SELECT Sample (1) JDBC1
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
ResultSet rs;
String query = "SELECT * FROM customer";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
SQL: SELECT Sample (2) JDBC1
stmt.execute(query);
rs = stmt.getResultSet();
while (rs.next())
{
out.println(rs.getString("f_name") + " / ");
out.println(rs.getString("f_username") + " / ");
out.println(rs.getString("f_password") + " / ");
out.println(rs.getString("f_address") + " / ");
out.println("<BR>");
}
rs.close();
stmt.close();
conn.close();
%>
</BODY>
</HTML>
Exercise 1: SELECT SQL4X1
 Write a JSP program which displays a product data in the
"product" table of "shop. mdb" database.
Exercise 2: SELECT SQL4X2
 Write an HTML file and a JSP program which inputs a
product name from a user and displays the data for the
product in the "product" table of "shop.mdb" database.
Quiz 4: Member Registration
Quiz 4 Member Registration
 Develop a Web site which processes a member registration .
 See the next page for the example of a registration form.
 Design a DB on your own.
 Project name
 JSPRegister
 Note:
 Due date: 08/03/2009
 This quiz is a group project.
 Each group of students should bring a program developed by each group in a
memory device on the due date and run the program during the class.
 Bring only the folders and files under "web" folder including a DB file.
Students would create a new NetBeans project for the program during the
class.
 Instructor will evaluate the running result.
Quiz 4 Member Registration
Evaluating Quiz 4
 Run NetBeans IDE.
 Set up a Web server domain for your computer.
 Create a project "JSPRegister".
 Overwrite "*.html", "*.jsp", and "*.mdb" files under the
"web" folder in your memory device onto the "web" folder
under the "NetBeansProjects/JSPRegister" folder.
 Set up the ODBC DSN for your computer.
 Wait until instructor investigates the program.
Digression
HttpURLConnection Class, Revisited (2)
HTTP (5) : HttpURLConnection Class,
revisited
 Exercise
 Make a Java program such that:
 Send a request to the Web page at
"http://localhost:8080/JDBCX5Server/register.jsp", with an entity
body of
"name=X&username=X&password=X&password2=X&address=X&zip
=X".
 Print out the response from the Web server.
 Project names
 JDBCX5Server/register.html (see next slide)
 JDBCX5Server/register.jsp (see next slide)
 HTTP5X1Client
Website (2) : Register, revisited
JDBCX5Server/register.html
<html>
<body>
<h1>Register</h1>
<form method="post" action="login.jsp">
<table>
<tr> <td>Name:</td> <td><input type="text" name="name"></td> </tr>
<tr> <td>User name:</td> <td><input type="text" name="username"></td> </tr>
<tr> <td>Password:</td> <td><input type="password" name="password"></td>
</tr>
<tr> <td>Password (retype):</td> <td><input type="password" name="password2">
</td> </tr>
<tr> <td>Address:</td> <td><input type="text" name="address"></td> </tr>
<tr> <td>ZIP code:</td> <td><input type="text" name="zip"></td> </tr>
<tr> <td colspan="2"><input type="submit" value="Register"></td> </tr>
</table>
</form>
</body>
</html>
Website (2) : Register, revisited
JDBCX5Server/register.jsp
<%
String name = request.getParameter("name");
String username = request.getParameter("username");
String password = request.getParameter("password");
String password2 = request.getParameter("password2");
String address = request.getParameter("address");
String zip = request.getParameter("zip");
//
// INSERT program here
//
%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Hello "<%= name %>"!</h1>
<h3>Your information (<%= username %>, <%= password %>, <%= password2 %>, <%=
address %>, <%= zip %>) was stored.</h3>
</body>
</html>
HTTP (5) : HttpURLConnection Class,
revisited HTTP5X1Client
import java.io.*;
import java.net.*;
try {
URL url = new URL("http://localhost:8080/HTTP2X1Server/register.jsp");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Request
urlConnection.setRequestMethod("POST");
urlConnection.setFollowRedirects(true);
URL
urlConnection.setDoOutput(true);
PrintWriter output = new PrintWriter(urlConnection.getOutputStream(), true);
output.print("name=X&username=X&password=X&password2=X&address=X&zip=X");
output.flush();
// Response
String res = urlConnection.getResponseMessage();
System.out.println("Response message - " + res);
Request
String enc = urlConnection.getContentType();
System.out.println("Content Type - " + enc);
BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
for (; (line = input.readLine()) != null;) {
System.out.println(line);
}
urlConnection.disconnect();
} catch (Exception e) {
Response Entity Body
System.err.println(e);
}
Quiz 5: Automatic Member
Registration
Quiz 5 Automatic Member Registration
 Develop a HTTP client which accesses the Web site of Quiz 4
JSPRegister to preoccupy usernames.
 Preoccupy usernames from "a" through "zzz".
 Project names
 JSPRegister (from Quiz 4)
 JSPRegisterClient
 Note:
 Due date: 08/05/2009
 This quiz is a group project.
 Each group of students should bring the programs developed by each group
in a memory device on the due date and run the programs during the class.
 Bring only the folders and files under the "src" and "web" folders including a
DB file. Students would create new NetBeans projects for the programs
during the class.
 Instructor will evaluate the running result.
Evaluating Quiz 5
 Run NetBeans IDE.
 Set up a Web server domain for your computer.
 Create projects "JSPRegister" and "JSPRegisterClient".
 Overwrite "*.java", "*.html", "*.jsp", and "*.mdb" files
under the "src" and the "web" folders in your memory
device onto the "src" and the "web" folders under
"NetBeansProjects/JSPRegister" and
"NetBeansProjects/JSPRegisterClient" folders.
 Set up the ODBC DSN for your computer.
 Wait until instructor investigates the program.
Application 1:
Online Storefront
Application 1
 Exercise
 Make a online storefront which is composed of Web pages such
as:
 Login (including session)
 Catalogue (Directory & Product List)
 Product Information
 Search
 Project name
 JSPA1
Application 1: DB Design
Table: member
Table: directory
Table: product
f_name
f_id
f_id
f_username
f_parentId
f_directoryId
f_password
f_name
f_name
f_status
f_price
Application 1 JSPA1/login.html
<HTML>
<BODY>
<FORM method="post" action="login.jsp">
Username:<input type="text" name="username"><br>
Password:<input type="text" name="password"><br>
<input type="submit" value="Login">
</FORM>
</BODY>
</HTML>
Application 1 JSPA1/login.jsp
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:dsnshop", "", "");
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM member WHERE f_username='" + username + "'");
ResultSet rs = stmt.getResultSet();
if (!rs.next()) {
out.println("Unknown user");
} else if (rs.getString("f_password").equals(password)) {
session.setAttribute("name", rs.getString("f_name"));
response.sendRedirect("catalog.jsp");
} else {
out.println("Login failure");
}
stmt.close();
conn.close();
%>
</BODY>
</HTML>
Application 1 JSPA1/catalog.jsp
<%@ page import="java.sql.*" %>
<%
String name = (String) session.getAttribute("name");
if (name == null) {
response.sendRedirect("login.html");
} else {
out.println("<FORM METHOD=\"GET\" ACTION=\"search.jsp\">");
out.println("<INPUT TYPE=\"TEXT\" NAME=keyword>");
out.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Search\">");
out.println("</FORM><BR>");
String pdid = request.getParameter("PDID");
if (pdid == null) {
pdid = "root";
}
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:dsnshop", "", "");
Statement stmt = conn.createStatement();
stmt.execute("select * from directory where f_parentId = '" + pdid + "'");
ResultSet rs = stmt.getResultSet();
for (; rs.next();) {
if (rs.getInt("f_status") == 1) {
out.print("<A HREF=\"catalog.jsp?PDID=" + rs.getString("f_id") + "\">");
out.print(rs.getString("f_name") + "</A>");
} else {
out.print("<A HREF=\"products.jsp?DID=" + rs.getString("f_id") + "\">");
out.print(rs.getString("f_name") + "</A>");
}
out.println("<BR>");
}
stmt.close();
conn.close();
}
%>
Application 1 JSPA1/products.jsp
<%@ page import="java.sql.*" %>
<%
String name = (String) session.getAttribute("name");
String did = request.getParameter("DID");
if (name == null) {
response.sendRedirect("login.html");
} else if (did == null) {
response.sendRedirect("catalog.jsp");
} else {
out.println("<FORM METHOD=\"GET\" ACTION=\"search.jsp\">");
out.println("<INPUT TYPE=\"TEXT\" NAME=keyword>");
out.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Search\">");
out.println("</FORM><BR>");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:dsnshop", "", "");
Statement stmt = conn.createStatement();
stmt.execute("select * from product where f_directoryId = '" + did + "'");
ResultSet rs = stmt.getResultSet();
for (; rs.next();) {
out.print("<A HREF=\"product.jsp?PID=" + rs.getString("f_id") + "\">");
out.print(rs.getString("f_name") + "</A>");
out.println("<BR>");
}
stmt.close();
conn.close();
}
%>
Application 1 JSPA1/product.jsp
<%@ page import="java.sql.*" %>
<%
String name = (String) session.getAttribute("name");
String pid = request.getParameter("PID");
if (name == null) {
response.sendRedirect("login.html");
} else if (pid == null) {
response.sendRedirect("catalog.jsp");
} else {
out.println("<FORM METHOD=\"GET\" ACTION=\"search.jsp\">");
out.println("<INPUT TYPE=\"TEXT\" NAME=keyword>");
out.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Search\">");
out.println("</FORM><BR>");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:dsnshop", "", "");
Statement stmt = conn.createStatement();
stmt.execute("select * from product where f_id = '" + pid + "'");
ResultSet rs = stmt.getResultSet();
for (; rs.next();) {
out.println("Product ID: " + rs.getString("f_id") + "<BR>");
out.println("Product Name: " + rs.getString("f_name") + "<BR>");
out.println("Price: $" + rs.getDouble("f_price") + "<BR>");
}
stmt.close();
conn.close();
}
%>
Application 1 JSPA1/search.jsp
<%@ page import="java.sql.*" %>
<%
String name = (String) session.getAttribute("name");
if (name == null) {
response.sendRedirect("login.html");
} else {
out.println("<FORM METHOD=\"GET\" ACTION=\"search.jsp\">");
out.println("<INPUT TYPE=\"TEXT\" NAME=keyword>");
out.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Search\">");
out.println("</FORM><BR>");
String keyword = request.getParameter("keyword");
String query;
if (keyword == null) {
query = "select * from product";
} else {
query = "select * from product where f_name like '%" + keyword + "%'";
}
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:dsnshop", "", "");
Statement stmt = conn.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
for (; rs.next();) {
out.print("<A HREF=\"product.jsp?PID=" + rs.getString("f_id") + "\">");
out.print(rs.getString("f_name") + "</A>");
out.println("<BR>");
}
stmt.close();
conn.close();
}
%>
Business model:
Electronic Commerce
Electronic Commerce
 Almost every Internet business models are implemented by
Server-side programming, of which platforms are:
 JSP
 ASP
 PHP
 They additionally use technologies like (but not always):
 Encoding (HTML, XML, CSS, …)
 Database
 Client-side programming
 Why they prefer Server-side programming?
 Platform independence
 Standardized GUI
→ Any time, any where
→ Easy to use
Recommendation System
 Recommendation System
 Content-based approach
 Collaborative filtering approach
 Amazon.com
 Customers Who Bought This Item Also Bought
 These systems require massive databases as well as server-
side programming.
Recommendation System
Logical Matrix from Sales Record
Book1
Book1
Book2
…
Bookn
1
Book2
2
1
0
…
Bookn
2
0
DB Table
Book
BoughtAlso
Count
Book1
Book2
1
Book1
Bookn
2
Book2
Book1
1
…
Recommendation System
 SQL Statement
SELECT
FROM
WHERE
ORDER BY
BoughtAlso
DBTable
Book='Electronic Commerce 2008'
Count DESC
 e.g.
For Book1 above:
BoughtAlso
Count
Bookn
2
Book2
1
Recommendation System
Hitbox
 Hitbox was a popular web counter and web analytics
product created by WebSideStory, now Omniture.
 A web counter or hit counter is a computer software
program that indicates the number of visitors, or hits, a
particular webpage has received. Once set up, these counters
will be incremented by one every time the web page is
accessed in a web browser.
 Web analytics is the measurement, collection, analysis and
reporting of internet data for purposes of understanding and
optimizing web usage.
Hitbox: Architecture
Web Site
Web
Browser
Image
File
Hitbox
Counter
Count
Hitbox: Architecture
Web Site
Web
Browser
Image
File
Hitbox
Counter
Count
Hitbox JSPB2Site/index.html
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
Content of this site here <BR>
Counter image: <img
src="http://localhost:8080/JSPB2Counter/index.jsp?userid=yu
song">
</body>
</html>
Hitbox: Architecture
Web Site
Web
Browser
Image
File
Hitbox
Counter
Count
Hitbox JSPB2Counter/index.jsp
<%@ page import="java.sql.*" %>
<%
String userid = request.getParameter("userid");
if (userid != null) {
int count;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:dsncounter", "", "");
Statement stmt = conn.createStatement();
stmt.execute("SELECT count FROM counter WHERE userid='" + userid + "'");
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
count = rs.getInt("count") + 1;
rs.close();
stmt.close();
stmt = conn.createStatement();
stmt.execute("UPDATE counter SET count=" + count + " WHERE userid='" + userid + "'");
stmt.close();
out.println(count);
} else {
rs.close();
stmt.close();
}
conn.close();
// Skipped: An image content should be responded here.
}
%>
Hitbox: Architecture
Web Site
Web
Browser
Image
File
Hitbox
Counter
Count
Hitbox JSPB2Counter/counter.mdb
Table: counter
userid
Text
count
Integer
Hitbox: Source of Revenue
 Web analytics service fee
 Toward a new search engine
 Search results are sorted based on the traffic count.
 Note) In Google, search results are sorted based on the number
of hyperlinks.
Building Blocks for JSP Programming
Webform: FORM Tag
 Syntax
<FORM
METHOD="POST"/"GET"
ACTION="server-side-program"
ENCTYPE="application/x-www-form-urlencoded">
...
</FORM>
Webform: INPUT Tag
 Syntax
<INPUT NAME="name"
VALUE="value"
SIZE="n"
MAXLENGTH="n"
TYPE = TEXT/PASSWORD
/CHECKBOX/RADIO
/SUBMIT/RESET>
Webform: TEXTAREA Tag
 Syntax
<TEXTAREA NAME="name" ROWS="n" COLS="n">
Line 1
Line 2
…
Line n
</TEXTAREA>
Webform: SELECT Tag
 Syntax
<SELECT NAME="name" SIZE="n" [MULTIPLE]>
<OPTION> option 1
<OPTION> option 2
…
<OPTION> option n
</SELECT>
Digression: URL Encoding
 Encoding rules
 A ~ Z, a ~ z, 0 ~ 1 → no conversion
 Blank
 Other characters
→ +
→ %xx (Hexadecimal ASCII Code)
 e.g.
Hello, world! → Hello%2C+world%21
Scripting Element: Expression
JSP2/index.jsp
<HTML>
<BODY>
sin(3.14) = <%= Math.sin(3.14) %>
</BODY>
</HTML>
Scripting Element: Scriptlet JSP3/index.jsp
<HTML>
<BODY>
<%
int i;
for (i = 0; i < 100; i++) {
out.println(i + "<BR>");
}
%>
</BODY>
</HTML>
request: getParameter JSP4
login.html
login.jsp
<HTML>
<BODY>
<FORM METHOD=POST
ACTION="login.jsp">
Username: <INPUT TYPE=TEXT
NAME="UN"> <BR>
Password: <INPUT TYPE=PASSWORD
NAME="PW"> <BR>
<INPUT TYPE=SUBMIT
VALUE="Login">
</FORM>
</BODY>
</HTML>
<HTML>
<BODY>
<%
String username =
request.getParameter("UN");
String password =
request.getParameter("PW");
out.println(username + "/" + password);
%>
</BODY>
</HTML>
response: sendRedirect JSP5
login.html
login.jsp
<HTML>
<BODY>
<FORM METHOD=POST
ACTION="login.jsp">
Username: <INPUT TYPE=TEXT
NAME="UN"> <BR>
Password: <INPUT TYPE=PASSWORD
NAME="PW"> <BR>
<INPUT TYPE=SUBMIT
VALUE="Login">
</FORM>
</BODY>
</HTML>
<HTML>
<BODY>
<%
String username = request.getParameter("UN");
String password = request.getParameter("PW");
if (username.equals("a") && password.equals("b"))
out.println("Login success!<BR>");
else
response.sendRedirect("login.html");
%>
</BODY>
</HTML>
session: setAttribute, getAttribute
JSP7X1
a.jsp
b.jsp
<HTML>
<BODY>
<%
String name =
request.getParameter("n");
session.setAttribute("name",
name);
out.println("You can enter <A
HREF='b.jsp'>our
site</A><BR>");
%>
</BODY>
</HTML>
<HTML>
<BODY>
<%
String n =
(String)session.getAttribute("na
me");
out.println("Your name is ");
out.println(n);
out.println(". Right?");
%>
</BODY>
</HTML>
session: invalidate JSP8
<HTML>
<BODY>
<%
session.invalidate();
out.println("<A HREF='main.jsp'>Main</A>");
%>
</BODY>
</HTML>
SQL: INSERT
INSERT INTO customer
(f_username, f_password, f_name, f_address)
VALUES
('yusong', '1234', 'Yong Uk Song', '234, Maji, Wonju')
INSERT INTO emp
(empno, ename, job, sal, comm, deptno)
VALUES
(7890, 'JINKS', 'CLERK', 1.2E3, NULL, 40)
SQL: INSERT Advanced Sample (1)
SQL1A
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String name = request.getParameter("name");
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String query = "INSERT INTO customer (f_name, f_username,
f_password, f_address) VALUES ('" + name + "', '" + username + "', '"
+ password + "', '" + address + "')";
SQL: INSERT Advanced Sample (2)
SQL1A
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
stmt.execute(query);
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: UPDATE
UPDATE customer
SET f_name = 'Hong', f_address = 'Oxford'
WHERE
f_username = 'yusong'
UPDATE emp
SET comm = NULL
WHERE
job = 'TRAINEE'
SQL: UPDATE Advanced Sample (1)
SQL2A
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String name = request.getParameter("name");
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String query = "UPDATE customer SET f_address='" + address
+ "' WHERE f_username='" + username + "'";
SQL: UPDATE Advanced Sample (2)
SQL2A
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
stmt.execute(query);
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: DELETE
DELETE FROM customer
WHERE
f_username = 'yusong'
DELETE FROM emp
WHERE
job = 'SALESMAN'
AND comm < 100
SQL: SELECT
SELECT f_name, f_address
FROM customer
WHERE f_username = 'yusong'
SELECT *
FROM tblasp
ORDER BY name
WHERE age < 30
SQL: SELECT Advanced Sample 1
(1) SQL4A
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String query = "SELECT f_password FROM customer WHERE
f_username='" + username + "'";
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
SQL: SELECT Advanced Sample 1
(2) SQL4A
stmt = conn.createStatement();
stmt.execute(query);
rs = stmt.getResultSet();
if (!rs.next())
{
out.println("Unknown user");
}
else if (rs.getString("f_password").equals(password))
{
out.println("Login success");
}
else
{
out.println("Login failure");
}
stmt.close();
conn.close();
%>
</BODY>
</HTML>
SQL: SELECT Advanced Sample 2
(1) JDBC1
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
ResultSet rs;
String query = "SELECT * FROM customer";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
SQL: SELECT Advanced Sample 2
(2) JDBC1
stmt.execute(query);
rs = stmt.getResultSet();
while (rs.next())
{
out.println(rs.getString("f_name") + " / ");
out.println(rs.getString("f_username") + " / ");
out.println(rs.getString("f_password") + " / ");
out.println(rs.getString("f_address") + " / ");
out.println("<BR>");
}
rs.close();
stmt.close();
conn.close();
%>
</BODY>
</HTML>
Exercises
Exercise (1)
 Project name
 JSPX1
 Build a login-based Web site, which is composed of Web
pages like:
 Login, for which "a" and "b" are used as the username and the
password
 A main page which is allowed only for authorized user
 For an unauthorized user, redirect the page to the login page.
 The HTML document for the main page is on the next slide.
 Logout
Exercise (1)
<HTML>
<BODY>
<H3>Hello, members! <A
HREF="logout.jsp">LOGOUT</A></H3>
Here is today’s special items.<BR>
Sorry, nothing for today.
</BODY>
</HTML>
Exercise (2)
 Project name
 JSPX2
 Build a login-based Web site, which is composed of Web pages like:
 Login, which is based on "customer" table on the next slide.
 A main page which is allowed only for authorized user
 For an unauthorized user, redirect the page to the login page.
 The main page shows the list (as on the next slide) of all products in "product" table,
of which schema appears on the next slide.
 Logout
 All the other names for data source, variables, etc. are on your own.
Exercise (2)
Table: customer
f_username
Text
f_password
Text
f_name
Text
Table: product
f_id
Text
f_name
Text
f_price
Double
Exercise (3)
 Project name
 JSPX3
 Build a login-based Web site, which is composed of Web pages like:
 Login, which is based on "customer" table on the next slide.
 A main page which is allowed only for authorized user
 For an unauthorized user, redirect the page to the login page.
 The main page shows the list (as on the next slide) of all products in "product" table,
of which schema appears on the next slide.
 Password change
 The users who logged in can edit their passwords.
 This page is based on "customer" table on the next slide.
 All the other names for data source, variables, etc. are on your own.
Exercise (3)
Table: customer
f_username
Text
f_password
Text
f_name
Text
Table: product
f_id
Text
f_name
Text
f_price
Double
Exercise (4)
 Exercise
 Make a Java program such that:
 The client sends a POST request to and receives the response from the
URL "http://localhost:8080/JSPX4Server/login.jsp".
 The "login.jsp" appears on the next slide.
 The username and password are "a" and "b", but send a wrong password
to the server and see what response the server sends.
 Use the HttpURLConnection class.
 Use "urlConnection.setFollowRedirects(false);" statement to see the
effect of "response.sendRedirect("login.html")" statement.
 Project name
 JSPX4Client
Exercise (4) JSPX4Server/login.jsp
<HTML>
<BODY>
<%
String username = request.getParameter("UN");
String password = request.getParameter("PW");
if (username.equals("a") && password.equals("b"))
out.println("Login success!<BR>");
else
response.sendRedirect("login.html");
%>
</BODY>
</HTML>
Appendix
Sun Microsystems
Application Server Administration
Create
C:> asadmin create-domain --domaindir "D:/My Documents/SADomains" --adminport
4848 --profile developer myDomain
Please enter the admin password> adminadmin[Enter]
Please enter the admin password again> adminadmin[Enter]
Please enter the master password [Enter to accept the default]:> [Enter]
Please enter the master password again [Enter to accept the default]:> [Enter]
Using port 4848 for Admin.
Using default port 8080 for HTTP Instance.
Using default port 7676 for JMS.
Using default port 3700 for IIOP.
Using default port 8181 for HTTP_SSL.
Using default port 3820 for IIOP_SSL.
Using default port 3920 for IIOP_MUTUALAUTH.
Using default port 8686 for JMX_ADMIN.
Domain being created with profile:developer, as specified on command line or
environment.
The file in given locale [ko_KR] at: [C:\Program
Files\Sun\AppServer\lib\install\templates\locales\ko_KR\index.html] could not be
found. Using default (en_US) index.html instead.
Security Store uses: JKS
Domain myDomain created.
Start, Stop, and Delete
C:> asadmin start-domain --domaindir "D:/My
Documents/SADomains" myDomain
C:> asadmin stop-domain --domaindir "D:/My
Documents/SADomains" myDomain
Domain myDomain stopped.
C:> asadmin delete-domain --domaindir "D:/My
Documents/SADomains" myDomain
Domain myDomain deleted