Building Blocks for Electronic Commerce Applications

Download Report

Transcript Building Blocks for Electronic Commerce Applications

Building Blocks for Electronic
Commerce Applications
Copyright (C) 2009 Dr.Yong Uk Song
Yonsei University Wonju Campus
TCP/IP Programming
Building Block: Server Sockets
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
…
… String request = input.readLine();
…
… output.println("Response from server");
…
output.close();
Receive
input.close();
clientConn.close();
serverSocket.close();
Send
} catch (Exception e) {
System.err.println(e);
}
Building Block: Client Sockets
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8000);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
…
…output.println("Request from client");
…
… String response = input.readLine();
…
output.close();
Send
input.close();
socket.close();
Receive
} catch (Exception e) {
System.err.println(e);
}
Building Block: if statement
 Syntax
if (expression) {
statement(s)1
} else {
statement(s)2
}
 Control and execution
 If evaluation result of the
"expression" is true, then
"statement(s)1" is executed.
 Otherwise, "statement(s)2" is
executed.
 e.g.
if (n > 0) {
a = 1;
} else {
a = 0;
}
Building Block: for statement
 Syntax
for (expression1; expression2;
expression3) {
statement(s)
}
 Control and execution
 The "expression1" is evaluated.
 If evaluation result of the
"expression2" is true, then
"statement(s)" is executed.
 After the execution, the
"expression3" is evaluated.
 Go to the evaluation of the
"expression2".
 Otherwise, the whole "for"
statement is finished.
 e.g.
for (i = 0; i < 100; i++)
{
System.out.println(i);
}
Building Block: Standard Output
 Syntax
 void System.out.print(Object)
 void System.out.println(Object)
 e.g.
System.out.print("String");
System.out.print(123);
System.out.println("String");
System.out.println(123);
 The command "print" does not print out an EOLN(i.e.
[Enter]) character.
Building Block: Standard Input
 Syntax
 BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
 String BufferedReader.readLine( ) throws IOException
 e.g.
import java.io.*;
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
System.out.print("You typed - ");
System.out.println(str);
} catch (Exception e) {
System.err.println(e);
}
Building Block: Multi-threading
Thread
public class MyThread
implements Runnable
{
public String m_msg;
public MyThread() {
m_msg = "";
}
…
public void run() {
m_msg = "message to the
Main";
…
}
…
}
Main
MyThread myThread = new
MyThread(…);
Thread m_thread = new
Thread(myThread);
m_thread.start( );
…
myThread.m_msg =
"message to the thread";
Building Block: Thread.sleep Method
 e.g.
try {
...
Thread.sleep(500);
...
} catch (Exception e) {
System.err.println(e);
}
Building Block: Java Libraries
 String.contains(substring)
 e.g. boolean b = request.contains("love");
 String.equals(string)
 e.g. boolean b = request.equals("Q");
 String.replaceFirst(string, string)
 e.g. String newStr = str.replaceFirst("old part", "new part");
 String.isEmpty( )
 e.g. boolean b = str.isEmpty();
 Integer.parseInt(string)
 e.g. int d = Integer.parseInt("3095");
HTTP Programming
Building Block: URL
 Format
 resource_type://domain:port/filepathname?query_string#anc
hor
e.g.
http://dragon.yonsei.ac.kr/~yusong/index.html
http://yonsei.ac.kr:8000/~yusong/a.cgi?user=yusong&b=b
ftp://dragon.yonsei.ac.kr/~yusong/sample.file
telnet://dragon.yonsei.ac.kr
rlogin://[email protected]
HTTP (1) : Client using GET Method
 Request Message
GET http://www.miami.muohio.edu/ HTTP/1.1
Host: www.example.com
crlf
HTTP (1) : Client using GET Method
HTTP1Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("www.miami.muohio.edu", 80);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println("GET http://www.miami.muohio.edu/ HTTP/1.1");
output.println("Host: www.example.com");
output.println("");
String response;
for (; (response = input.readLine()) != null;) {
Host
Port
System.out.println(response);
}
output.close();
input.close();
socket.close();
Request
} catch (Exception e) {
System.err.println(e);
}
Response
HTTP (2) : Client using POST Method
 Request Message
POST /HTTP2Server/login.jsp HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
crlf
username=yusong&password=10000
HTTP (2) : Client using POST Method
HTTP2Client
import java.io.*;
import java.net.*;
try {
Socket socket = new Socket("localhost", 8080);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println("POST /HTTP2Server/login.jsp HTTP/1.1");
output.println("Host: www.example.com");
output.println("Content-Type: application/x-www-form-urlencoded");
output.println("Content-Length: 30");
output.println("");
output.println("username=yusong&password=10000");
Host
Port
String response;
for (; (response = input.readLine()) != null;) {
System.out.println(response);
}
output.close();
Request
input.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
}
Response
HTTP (3) : Web Server
 Response Message
HTTP/1.1 200 OK
crlf
<HTML>
<BODY><H1>This is a stupid Web server.</H1></BODY>
</HTML>
HTTP (3) : Web Server HTTP3Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request;
for (; (request = input.readLine()).isEmpty() == false;) {
System.out.println(request);
}
output.println("HTTP/1.1 200 OK");
output.println("");
output.println("<HTML>");
output.println("<BODY><H1>This is a stupid Web server.</H1></BODY>");
output.println("</HTML>");
output.close();
input.close();
Response
clientConn.close();
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Request
Port
HTTP (3) : Web Server for Redirect
 Response Message
HTTP/1.1 302 Found
Location: http://www.miami.muohio.edu/
crlf
We moved.
HTTP (3) : Web Server for Redirect
HTTP3X1Server
import java.io.*;
import java.net.*;
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request;
for (; (request = input.readLine()).isEmpty() == false;) {
System.out.println(request);
}
output.println("HTTP/1.1 302 Found");
output.println("Location: http://www.miami.muohio.edu/");
output.println("");
output.println("We moved.");
output.close();
input.close();
clientConn.close();
Request
serverSocket.close();
} catch (Exception e) {
System.err.println(e);
}
Response
Port
HTTP (4) : URL Class HTTP4Client
import java.io.*;
import java.net.*;
try {
URL url = new URL("http://www.miami.muohio.edu/");
BufferedReader input = new BufferedReader(new
InputStreamReader(url.openStream()));
String line;
for (; (line = input.readLine()) != null;) {
System.out.println(line);
URL
}
} catch (Exception e) {
System.err.println(e);
}
Response
HTTP (5) : HttpURLConnection Class
HTTP5Client
import java.io.*;
import java.net.*;
try {
URL url = new URL("http://localhost:8080/HTTP2Server/login.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("username=yusong&password=10000");
output.flush();
// Response
String res = urlConnection.getResponseMessage();
System.out.println("Response message - " + res);
// OK
Request
String enc = urlConnection.getContentType();
System.out.println("Content Type - " + enc);
// text/html;charset=UTF-8
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
System.err.println(e);
}
Server-side 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
<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>
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>
Client-side Programming
JavaScript Programming in HTML
 Syntax
 Inserting JavaScript codes in an HTML document
<SCRIPT LANGUAGE="JavaScript">
… JavaScript codes here
</SCRIPT>
 Using a JavaScript source code file
<SCRIPT LANGUAGE="JavaScript" SRC="script.js">
</SCRIPT>
 Note : ".js" is used for JavaScript source code files.
JavaScript: User Interface Methods
 alert(string)
 e.g.
alert("Hello there!");
 confirm(string)
 e.g.
bSure = confirm("Are you sure?");
 prompt(string, string)
 e.g.
sName = prompt("Enter your name", "name");
JavaScript: List of Events (partial)
Category
Type
Attribute
Description
Fires when the pointing device button is clicked over an element. A click is defined as a mousedo
click
onclick
wn and mouseup over the same screen location. The sequence of these events is: mousedown, m
ouseup, and click
dblclick
ondblclick
Fires when the pointing device button is double clicked over an element.
mousedown onmousedown Fires when the pointing device button is pressed over an element.
Mouse
mouseup
onmouseup
Fires when the pointing device button is released over an element.
mouseover onmouseover Fires when the pointing device is moved onto an element.
mousemove onmousemove Fires when the pointing device is moved while it is over an element.
mouseout
onmouseout
Fires when the pointing device is moved away from an element.
keypress
onkeypress
Fires after keydown, when a key on the keyboard is pressed.
Keyboard keydown
onkeydown
Fires when a key on the keyboard is pressed.
keyup
onkeyup
Fires when a key on the keyboard is released.
Fires when the user agent finishes loading all content within a document, including window, fra
load
onload
mes, objects and images. For elements, it fires when the target element and all of its content has
finished loading.
Fires when the user agent removes all content from a window or frame. For elements, it fires w
HTML
unload
onunload
hen the target element or any of its content has been removed.
frame/
abort
onabort
Fires when an object/image is stopped from loading before completely loaded.
object
error
onerror
Fires when an object/image/frame cannot be loaded properly.
resize
onresize
Fires when a document view is resized.
scroll
onscroll
Fires when a document view is scrolled.
select
onselect
Fires when a user selects some text in a text field, including input and textarea.
change
onchange
Fires when a control loses the input focus and its value has been modified since gaining focus.
submit
onsubmit
Fires when a form is submitted.
HTML form
reset
onreset
Fires when a form is reset.
focus
onfocus
Fires when an element receives focus either via the pointing device or by tab navigation.
blur
onblur
Fires when an element loses focus either via the pointing device or by tabbing navigation.
JavaScript: Timeout
 Syntax
Timeout = setTimeout(function-call-in-string, milliseconds)
clearTimeOut(Timeout)
 e.g.
timeVar = setTimeout("timeoutFunction()", 10000);
clearTimeout(timeVar);
JavaScript: Interval
 Syntax
Interval = setInterval(function-call-in-string, milliseconds)
clearInterval(Interval)
 e.g.
timeVar = setInterval("intervalFunction()", 10000);
clearInterval(timeVar);
CSS: Defining in HTML Documents
 Format
<STYLE TYPE="text/css">
tag { style-definition }
#id-name { style-definition }
tag#id-name { style-definition }
.class-name { style-definition }
tag.class-name { style-definition }
…
</STYLE>
style-definition = name1: v1 v2 …; name2: v1 v2 …; …
CSS: Defining In-line Styles
 Format
<tag STYLE="style-definition"> … </tag>
 e.g.
<H1 STYLE="font: bold large"> … </H1>
CSS: Linking
 Format
<LINK REL=STYLESHEET TITLE="title" TYPE="text/css"
HREF="filename">
 e.g.
<LINK REL=STYLESHEET TITLE="master style"
TYPE="text/css" HREF="styles.css">
CSS: Importing
 Format
<STYLE TYPE="text/css">
@IMPORT URL(address);
</STYLE>
 e.g.
<STYLE TYPE="text/css">
@IMPORT URL(http://localhost:8080/CSS/styles.css);
</STYLE>
CSS: Font Properties
 font-family
 font-size : small, large, x-large, xx-large, …
 font-style : oblique, italic, normal
 font-weight : normal, bold, bolder, lighter
 font-variant : small-caps, normal
 font : font-weight + font-size + font-style …
 color : #RGB / black, white, red, green, …
 text-decoration : underline, overline, line-through, blink
* RGB - Red(0…FF)+Green(0…FF)+Blue(0…FF)
e.g. #FF0000, #00FF00, #0000FF, #FFFFFF, #000000
CSS: Background Properties
 background-color : #RGB / transparent
 background-image : URL(address) / none
 background-repeat : repeat, repeat-x, repeat-y, no-repeat
 background-attachment : scroll, fixed
 background-position : combination of top, center, bottom,
left, right / x% y%
 background : background-color + image + repeat +
attachment + position
CSS: Text Align Properties
 vertical-align : baseline, middle, sub, super, text-top, text-
bottom / top, bottom
 text-align : left, center, right, justify
 text-indent : nin, ncm, npx, n%
CSS: Spacing Properties
 word-spacing : n, normal
 letter-spacing : n, normal
 line-height : n, n%, normal
 white-space : normal, pre, nowrap
CSS: Box Properties (1)
 margin-top : npx, n%, auto
 margin-right : npx, n%, auto
 margin-bottom : npx, n%, auto
 margin-left : npx, n%, auto
 margin
CSS: Box Properties (2)
 border-width: thin, medium, thick, none
 border-color: #RGB / black, red, green, …
 border-style: none, dotted, dashed, solid, …
 border-top: width style color
 border-right: width style color
 border-bottom: width style color
 border-left: width style color
 border
CSS: Box Properties (3)
 padding-top : npx, n%, auto
 padding-right : npx, n%, auto
 padding-bottom : npx, n%, auto
 padding-left : npx, n%, auto
 padding
CSS: Box Properties (4)
 width: npx
 height: npx
 e.g.
IMG { width: 250px; height: 250px }
 float : left, right, none
 e.g.
IMG { float: left; margin: 0px; border: none }
DOM: Page Elements
 e.g.
<IMG NAME="aImg" SRC="home.gif" WIDTH="50"
HEIGHT="35" BORDER="1">
Object:
Attributes:
name
src
width
height
border
aImg
"aImg"
"home.gif"
50
35
1
DOM: Style Sheet Objects
 e.g
<H1 ID=aH1 STYLE="color: blue; text-align: center;"> Head
</H1>
Object:
Attributes:
color
textAlign
aH1.style
'blue'
'center'
 Note: text-align → textAlign