Sie sind auf Seite 1von 96

1

Web Development
Presented by:
Ung Yean

MS. Computer Science
American University, Washington DC, USA
2
Objective
To offer a conceptual understanding of the www
infrastructure & a hand-on experience on web
development from both the client and server side
using JSP (Java Server Page).
3
Table of Contents
1. Hello JSP
2. JSP Components
3. NetBeans
4. JSP Models
5. Requests
6. Response
7. Session
8. EJB (Enterprise JavaBean)
9. JDBC (Java Database Connectivity)
10. JSP Deployment
4
Introduction to Web Applications
What are J avaServer Pages (J SPs)?
Technology to create dynamic content on the Web. They are
server-side app that accepts a request and generate a
response. They are HTML documents that are interleaved
with Java to generate the dynamic contents.
5
HTTP(The Hypertext Transfer Protocol)
HTTP is the default protocol for JSP, which means that JSP
applications typically receive requests and send responses
over this protocol.

HTTP is also the basic protocol of the World Wide Web
6
Evolution of the Web

Static web

<HTML>
<HEAD><TITLE>Simple html</TITLE></HEAD>
<BODY> HTML Document </BODY>
</HTML>

Web Client Web Server
7
Evolution of the Web cont.

The Plug-In Web

<HTML>
<HEAD><TITLE>Simple html</TITLE></HEAD>
<BODY> HTML Document
<Applet code=. . .>
</applet></BODY>
</HTML>

Web Client Web Server
8
Evolution of the Web cont.

The Dynamic Web

<HTML>
<HEAD><TITLE>Simple html</TITLE></HEAD>
<BODY> HTML Document
<SCRIP LANGUAGE=. . .>
</BODY>
</HTML>

Web Client Web Server
9
Evolution of the Web cont.
The N-Tier Web
Web Client Web Server
EJB
Servlets
JSP
10
Use of NetBean
11
Create new project
12
Create new project cont.
13
Create new project cont.
14
Hello J SP
<html>
<head>
<title>hello</title>
</head>
<body>

<h1> Hello JSP </h1>

The time is: <%=new java.util.Date()%>

</body>
</html>
15
Introduction to Servlets
A servlet is a java class that implements the Servlet
interface and accepts requests and generates responses.

The HttpServlet accept HTTP requests and generates
HTTP responses.

16
How J SPs become to Servlets
Servlet
.java
Servlet
.class
Response
HTML doc
Web
Client
Translated Compiled Generated Sent to
17
J SP Components
JSP composes of:
Comment
HTML
JSP tags
JavaBeans java class
JSP implicit objects -- request, response, session
18
J SP Components cont.
HTML Comment
<!--HTML Comment -->
The comment will be sent but ignored by the browser

J SP Comment
<%-- JSP comment will not even go to the browser --%>
Ignored by the JSP and do not appear in the web page

J ava Comment
/* Java comment */
// Another Java Comment
19
J SP Components cont.
J SP Tags
Global declaration; all variables and methods are available to
throughout the JSP
<%! String str=This is a string;
int sum(int x, int y){ return(x+y); }
%>

J SP Expression Tags
<%=expression%>
Expression is evaluated and converted to String

Scriplet Tags
<% java code %> Used to embed java code
20
J SP Components
<html>
<!--HTML Comment get sent to the browser -->
<%-- JSP comment will not even go to the browser --%>

<%! // Global declaration;
String str="This is a string";
int sum(int x, int y){ return(x+y); } %>
<head>
<title>JSP Components</title>
</head>
<body>
<h1>Example JSP Components</h1>
The sum of 10+12 is <%=sum(10,12)%>
<br>Example using global var <%=str%></br>
<br>The time is: <%=new java.util.Date()%></br>
</body>
</html>
21
J SP Components cont.
J ava Applet
Java Applet is a java class that is downloaded to and get run by the
browser on the client machine.

<jsp:useBean id=book class=book.BookInfo/>
<jsp:setProperty name=book property=author value=Mr.Bill/>
<jsp:getProperty name=book property=author/>

The setProperty and getProperty are methods that set and get
property of BookInfo class.
22
J SP Components cont.
J ava Bean
Java bean is a java class written to perform certain function.

<jsp:useBean id=book class=book.BookInfo/>
<jsp:setProperty name=book property=author value=Mr.Bill/>
<jsp:getProperty name=book property=author/>

The setProperty and getProperty are methods that set and get
property of BookInfo class.
23
JSP Application Models
The Simple:
One JSP talks to the DB directly.

jsp
Web sever/App server
Response
Request
Database
24
JSP Application Models cont1
N-Tier:
EJB talks to the DB (not JSP) and return result to JSP
jsp
Web sever
Response
Request
Database
EJB
App server
25
JSP Application Models cont2
Include Request:
One or more JSPs are included in another.

jsp
Web sever
Response
Request
Database
EJB
App server
jsp
26
JSP Application Models cont3
Forward Request:
One JSP gets the request, forwards it to another which
returns the response.

jsp
Web sever
Response
Request
Database
EJB
App server
jsp
27
Example
Include Request
<html><head> <title>Music CD</title></head>
<body>
<jsp:include page="music.jsp"/>
</body>
</html>

Forward Request:
<html><head> <title>Music CD</title></head>
<body>
<jsp:forward page="music.jsp"/>
</body>
</html>

28
Request
A request contains client information which a JSP
can get access to through it methods.

An instance of request is generated automatically
and is available to the jsp which gets invoked.
29
URL Format
pro://adress:port/path?qry string

Eg.
http://localhost:80/CDLibrary?title=web development& name =val
Where:
pro: protocol, eg http, ftp
address: servers ip or name
port: server port
path: path of where the jsp is on the server
qry string: query string.

Note: Query string is a method whereby parameters can be
passed to the JSP
30
HTTPServletRequest
ServletRequest
(general request without protocols, ftp, http,etc)

HTTPServletRequest extends ServletRequest
Provides a wealth of information through it methods

A HTTPServletRequest
an instance of request (named request) is implicitly available
to the JSP.
31
Request methods Example
String getRemoteAddr() ip address of client computer
int getRemotePort() port numer of client computer
String getServerName() ip address or name of server
int getServerPort() port number of server
String getServletPath() path of the server
String getMethod() POST or GET
32
Assignment
Write a web page to display the following information (using the
request object)

Host and Port:
Remote adress (ip): 127.0.0.1
Remote port: 1399
Server name: localhost
Server port: 8084
Server path: /request/hostPort.jsp
Protocol: HTTP/1.1
Method: GET

Hint:
Server port: <%= request.getServerPort() %>
33
Query string
Query string can be hard coded into the URL directly or passed
through the HTML form.

Eg. <a href="myPref.jsp?acc=abc&color=blue>

acc=123&color=blue
is query string and two parameters are passed (separated by
& sign): acc and color. 123 is the value of the parameter acc
and blue is that of color.

34
Query string Example
<a href="myPref.jsp?acc=abc&color=blue&color=red>

--- myPref.jsp
<body><pre>
jsp to process the query string using request.getParameter

Parameters:
acc: <%=request.getParameter("acc")%>
<% String val[]=request.getParameterValues("color"); %>
color 1: <%=val[0]%>
color 2: <%=val[1]%>
</pre>
</body>
35
HTML Form
HTML form contains UI (User Interface) components such as
TextField, Radio button etc..

The form is filled out by the user and submit to the JSP that
processes the information.

The way the JSP processes the information is the same as that
of query string.


36
HTML Form Example
<form action="formTest.jsp" method="post" name="cdEntryF">
<h4>CD Information </h4>
Title <input name="title" type="text">
Publisher <input name="pub" type="text">

<input name="save" type="submit" value="Save">

</p></form>
37
HTML Form Example cont.
<form action="formTest.jsp" method="post" name="cdEntryF">
<pre><h4>CD Information </h4>
Title <input name="title" type="text">
Publisher <input name="pub" type="text">

<input name="save" type="submit" value="Save">
<hr>
</form>
Title: <%=request.getParameter("title")%>
Publisher: <%= request.getParameter("pub")%>
</pre>
38
J ava Review
39
Application, Applet, Servlet


Java is used to develop:
Desktop application regular application
Applet - embedded in a web page
Servlet - web application (Internet)

40
Define a class
A class define an object structure

public class HelloJava{
public static void main(String arg[]){ //entry point for the class

}
public void method(){
.
}
}



41
Instantiate a class and call a method
A class define an object structure

public class HelloJava{
public static void main(String arg[]){ //entry point for the class
HelloJava hello=new HelloJava(); //instantiation
hello.method();
}
public void method(){
.
}
}



42
J ava Package
A package contains any number of classes that are related in purpose, in
scope, or by inheritance.

Declaring Packages
package hello; // class HelloJava is in the package hello
public class HelloJava{
}

Importing Packages
package hello;
import java.awt.Button; // import a Button class
import java.awt.*; // import all classes used in the class
public class HelloJava{
}

Note: package name is usually in lower case

43
Data Type

int whole number 120
float floating point number 4.12
double
long
char character a
String a set of character my dear
Enumeration a collection of object, accessible in sequence
Vector a dynamic collection of object, similar to array

Variable declaration and initialization
int i=0;
String hello=Hello;
Vector vector=new Vector();

44
Array
Array a collection of object, accessible using index
e.g. String musicCD[]={All blues, Kloysne};
musicCD[0]=All blues;
musicCD[1]=Kloysne;

Note: Array can contain any data type



45
Example.
import java.awt.*; // package (container of similar classes)

public class ClassName extends ParentClass{
// inherits methods and properties
int i=0; // of ParentClass
public void method1(){ // nothing return
}
public int method2(){ // method return int

return 2;
}
}

ClassName id=new ClassName(); // object creation (instance)
id.method1(); // call method 1

46
if statement
Int age 25;
if(age<18){
.
}
elseif(age <40){
.
}
else{

}

47
Loop
Loop
for(int i=0;i<n;i++){ // repeat n times
}

Enumeration e=;
while(e.hasMoreElements()){ // true if theres more element
nextElement(); // get next element of e
}


48
Vector
Vector vector=new Vector();
for(int i=0;i<10;i++){
vector.add(object);
}

Vector methods
add(object); // append
get(int index); // get element at index
remove(int index) // remove element at index
size(); // # of elements in vector

Note indexing of vector works like arrays
after remove, the gap in the vector is closed

Note2 Enumeration and Vector are in the java.util package

49
Using J ava in J SP

Create a Java class in the Source Packages.
Right click (on Source Packages)/new/ java package
Right click (on package)/new/Java class

50
J ava class example

package book;

public class Book {
String title, author, publisher;
public Book(String title, String author, String publisher){
this.title=title; this.author=author; this.publisher=publisher;
}
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return title;
}
}
51
Reference J ava class from J SP

<%@page import = "book.*" %>

<%
Book book=new Book("a","b","c");
book.setTitle("Intro to JSP");
%>
<%= book.getTitle()%>
52
Cookies
Cookies are created by the response object and stored in the clients
hard disk. Basically a cookie is a string with name and value.

The response object use addCookie(cookie) method to create a
cookie

To retrieve previously stored cookies, use
Cookie[] request.getCookies();
e.g. Cookie cookies[]=request.getCookies(); //return array of cookies

53
Cookies methods
Constructor
Cookie(String name, String value); // create a cookie
Methods:
String getName(); // return name of the cookie
String getValue(); //
int getMaxAge();

void setValue(String value);
void setMaxAge(int second); //after second expire the cookie is not av

Note: second==0 cookie will be deleted
<0 cookie will be deleted after exit
>0 cookie will be stored persistently
54
Cookie methods cont.
Constructor
Cookie(String name, String value); // create a cookie
Methods:
String getName(); // return name of the cookie
String getValue(); //
int getMaxAge();

void setValue(String value);
void setMaxAge(int second); //after second expire the cookie is not av

Note: second==0 cookie will be deleted
<0 cookie will be deleted after exit
>0 cookie will be stored persistently
55
Session
HTTP is a stateless protocol ie there is no way a browser can
remember each time a user open a page.

A session is a method by which a browser can know about a
users visit to a site.

Every distinct user is associated with a unique session object.
This is possible by creating an ID and stored it as a cookie in
the clients machine.

Three mechanisms that JSP can keep stateful interaction are:

Cookies
Session object
URL encoding
56
Sessions methods
void setAttribute(String, Object); // bind object to string parameter
Object getAttribute(String); // return attribute of the given String
String getId(); //Returns the unique session ID.
Enumeration getAttributeNames();// return all strings for the session
57
Requests methods for session
HttpSession getSession(); // return current session, create one if does
// not exit
HttpSession getSession(boolean); // return current session
// or create one if true
String getRequestedSessionId(); // return session id
58
Encoding URLs
If the cookie is disabled, session cannot be used. In this case, to keep
stateful communication is to encode the session id in the URL.

e. g.
<%String link =response.encodeURL("link.html"); // encode session id
String sessionID=request.getRequestedSessionId();
%>
Note: if cookie is enabled, then encoding will not work and the original
URL is returned.
59
J DBC (J ava database Connectivity)
Jdbc allows connection to various databases through odbc.
Java applications
odbc
Ms access Ms Sql Others
60
Steps to connect to db
1. import java.sql.*;
2. Create a data source name through odbc
3. Write statements in java application to access the database:
a) Load driver
b) Create a Connection object
c) Create a Statement object // this object is used to execute
sql statements, eg. Select, insert, delete, update

61
Create a dsn (data source name)
Run Data Sources
1
62
Create a dsn cont.
2
Select Add
63
Create a dsn cont.
3
Select Ms Access Driver
Click Finish
64
Create a dsn cont.
4
Name the Data Source
This name will be used in the code
Select the database
65
Make the connection
try{
// load driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Make connect
String url = "jdbc:odbc:vehicle"; // vehicle is the dsn
Connection con = DriverManager.getConnection(url, user, pw);

// create Statement object
Statement stmt = con.createStatement(); // Statement object has
// methods for accessing
// the database
}catch(Exception e){}
66
The Statement methods
The statement methods are used to access the data base.

ResultSet executeQuery(String query) ;
use for select statement, return the ResultSet object which can
be used to loop through all records satisfying the query

int executeUpdate(String update);
use for insert, delete and update statements, return the number of
records updated.
67
The ResultSet interface
Used to browse and access resulting data from a query.

Methods to move through records
boolean next(); // move to next row
boolean previous() // prevous row

Methods to access a column (field)
String getString(int columnNumber); // get field
String getString(String columnName);
int getInt();
int getLong();

Note:
1. The column can be accessed by column number or name
2. The ResultSet instance has methods for all data types


68
Example select

try{
String sql=select * from tblCD;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String column1=rs.getString(1); // get column 1
String column1=rs.getString(colum1);

}
}catch(Exception e){}


69
Example delete
public void deleteVehicle(String lc){ // get from db table Hashtable
try{
String sql=delete from tblVehicle where license=+lc;
stmt.executeUpdate(sql);
}catch(Exception e){}
}

70
Example insert
public void deleteVehicle(String lc){ // get from db table Hashtable
try{
String sql=insert into tblVehicle values(col1, col2,);
stmt.executeUpdate(sql);
}catch(Exception e){}
}

71
The Connection methods
The Connection interface allows connection to the database as
well as create a statement for query the db.

Connection con =
DriverManager.getConnection(String url, String user, String pw);

Statement createStatement(); // create statement for query execution
void close(); // close the connection


72
Exercise

Book Library.
1. Implement a db (mdb) with a table containing the following columns: title,
author, publisher.
2. Write a JSP to connect to the db and select all rows into a table. Show the
table on browser.
3. Write an input form containing the three columns and a submit button. Use
the submit button to insert the columns into the table.
73
Example
1. <table width="100%" border=1> <th width="50%">Title</th>
2. <th width="50%">Vendor</th>
3. <% try{// connect to odbc database
4. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
5. String url = "jdbc:odbc:cdLibrary";
6. Connection con = DriverManager.getConnection(url,"", "");
7. Statement stmt = con.createStatement();
8. String sql="select * from tblCD";
9. ResultSet rs=stmt.executeQuery(sql);
10.
11. while(rs.next()){
12. %> <tr><td align=center><%=rs.getString(2)%></td>
13. <td align=center><%=rs.getString(5)%></td>
14. </tr>
15. <%}
16. if(stmt!=null)stmt.close();
17. if(con!=null)con.close();
18. }catch(Exception e){ System.out.println(e.getMessage()); }

74
JavaBeans
JavaBean is a Java class that has public set and get
methods for all of its properties.

The set and get methods are used to set and get the
properties of the class respectively.

The ( ) is replaced by the name of the property
75
Use of JavaBeans in JSP
<jsp:useBean id=bookInfo class=book.BookInfo/>
// bookInfo is an instance of BookInfo class.
// book is the package
// bookInfo object is used to invoke various methods of
BookInfo class

76
Example JavaBeans
package book;
public class BookInfo {
private String title="Web Development";
private String author="Anata Dhammo";

public String getTitle(){
return title;
}
public void setTitle(String title){
this.title=title;
}
}
77
Where to put JavaBeans
78
Example use JavaBean in JSP
1. <%@page contentType="text/html"%>
2. <%@page pageEncoding="UTF-8"%>
3. <jsp:useBean class="book.BookInfo" id="bookInfo"/>

4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7. <title>JavaBean Instance</title>
8. </head>
9. <body>
10. <h3>JavaBean Instance</h3>
11. <%=bookInfo.getTitle()%>
12. </body>
13. </html>
79
Exercise using get and set method
1. Add property author to BookInfo
2. Write method getAuthor() for BookInfo
3. Use getAuthor() in the JSP to show the author
4. Use set method from the JSP to set the title and author and
5. Use get method to retrieve the title and author and show them
80
Scope (life and death) of JavaBean
<jsp:useBean id=bookInfo class=book.BookInfo
scope=beanScope/>

beanScope has the following value:
page -the bean is stores in javax.servlet.jsp.PageContext
instance and only available for this page, e.g. not on the
included page.
request -the bean is stored in ServletRequest object, hence is
available for the included page that share the same request.
session the bean is stored in the HttpSession and is available
across HTTP requests.
application the bean is stored in the ServletContext and is
available for any objects run in the application server.
81
set, and get JavaBean properties from jsp
<jsp:useBean id=bookInfo class=book.BookInfo
scope=session/>

<jsp:setProperty name="bookInfo" property="title"
value="JavaBean"/>
<jsp:getProperty name="bookInfo" property="title"/>

The setProperty is the same as method invocation
bookInfo.setTitle() and getProperty as bookInfo.getTitle();
82
Using Form with JavaBean
To get the parameter from a form, we use request.getParameter().
To set this parameter to JavaBean property, we use
<jsp:setProperty name="bookInfo" property="title"
value=<%=request.getParameter%> />

To set multiple values which come from a form to a JavaBean we use
<jsp:setProperty name="bookInfo" property=*" />

Note:
The parameters names of the form must have the same name of
properties of JavaBean.
83
Exercise using get and set property
1. Implement a form that has the following fields, title, author,
publisher, year.
2. Implement a JavaBean that has the same properties as the
forms fields.
3. Write a JSP to set the JavaBean properties using forms fields.
4. Use the getProperty to show the properties in a web page.
84
Using JavaBeans for JDBC
JSP is a presentation layer, thus should not concern with the
implementation details of java or business logic, eg the
JDBC.

The JDBC implementation can be done in JavaBean which
exposes methods to be invoked from JSP.
85
JavaBeans that implement JDBC
To implement JDBC, JavaBeans should has the followings
methods which can be called from a JSP:

connect connect to the db
select select rows from a table
insert insert rows into a table
delete delete rows from a table
update update rows in the table

86
JavaBeans implements JDBC
1. package jdbc;
2. import java.sql.*;
3. import java.util.*;
4. import book.*;

5. public class BookJDBC{
6. String dsn; Connection con; Statement stmt;
7. public BookJDBC() { }
8. public boolean connect(){ }
9. public int insert(){} // insert row
10. public int delete(){ } // delete row
11. public int update(){ } // update row
12. public Vector select(){} // select rows and return result in a Vector
13. }

87
JavaBeans implements JDBC2
public boolean connect(){
try{// connect to odbc database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:bookLibrary";
con = DriverManager.getConnection(url,"", "");
stmt = con.createStatement();
}catch (Exception e){ return false;}
return true;
}

88
JavaBeans implements JDBC3
public Vector select(){ // select rows and return result in a Vector
Vector vec=new Vector();
ResultSet rs=null;
try {
rs=stmt.executeQuery("select * from tblBook");
while(rs.next()){
Book book=new Book(rs.getString(1), rs.getString(2), rs.getInt(3));
vec.add(book);
}
} catch (SQLException ex) { }
return vec;
}
89
JavaBeans implements JDBC3
1. package book;
2. public class Book {
3. private String title, author;
4. int year;
5. public Book(){ }
6. public Book(String title, String author, int year){
7. this.title=title; this.author=author;
8. this.year=year;
9. }
10. public void setTitle (String title){ this.title=title; }
11. public void setAuthor (String title){ this.title=title; }
12. public void setYear (int year) { this.year=year; }

13. public String getTitle() { return title; }
14. public String getAuthor() { return author; }
15. public int getYear() { return year; }
16. }
90
Calling JavaBeans from JSP
1. <%!Vector vec;%>
2. <%
3. if(bookJDBC.connect()){
4. vec=bookJDBC.select();
5. for(int i=0; i<vec.size();i++){
6. Book b=(Book)vec.get(i);%>
7. <tr>
8. <td align=center><%=b.getTitle()%></td>
9. <td align=center><%=b.getAuthor()%></td>
10. <td align=center><%=b.getYear()%></td>
11. </tr>
12. <% }
13. }
14. %>
91
Exercise: Using JavaBeans to implement JDBC
1. Modify the connect method to have a dsn (Data Source Name)
parameter.
2. Implement the delete method to delete a row
3. Implement the insert method to insert a row (fields are from a
form)
4. Modify the select method to select rows that fulfilled certain
criteria

92
Exercise: Using JavaBeans to implement JDBC
1. Modify the connect method to have a dsn (Data Source Name)
parameter.
2. Implement the delete method to delete a row
3. Implement the insert method to insert a row (fields are from a
form)
4. Modify the select method to select rows that fulfilled certain
criteria

93
How to implement form with multiple buttons
1. <head>
2. <script language = "javascript">
3. function invoke(btn){
4. if(btn == 0) document.myform.action="select.html";
5. if(btn == 1) document.myform.action="insert.html";
6. if(btn == 2) document.myform.action="update.html";
7. if(btn == 3) document.myform.action="delete.html";
8. document.myform.submit();
9. }
10. </script>

94
How to implement form with multiple buttons (2)
1. <body>
2. <form method="post" name="myform" action="">
3. <table><tr><td><input type="button" value="Select"
onclick="invoke(0)"></td></tr>
4. <tr><td><input type="button" value="Insert"
onclick="invoke(1)"></td></tr>
5. <tr><td><input type="button" value="Update"
onclick="invoke(2)"></td></tr>
6. <tr><td><input type="button" value="Delete"
onclick="invoke(3)"></td></tr>
7. </table> </form>
8. </body>
95
Tomcat Web Application Deployment
After installation, Tomcat has the following directory structure
bin- tomcat web server application

webapps- web applications. Each entry is
one web application hosted by Tomcat.

To host CDLibrary copy WAR file to cdLibrary
folder and unzip it using winzip or winrar

96
Thank you for your attention.
ung yean

Das könnte Ihnen auch gefallen