Web 2.0 Programming 1 © Tongji University , Computer Science ...

indexadjustmentInternet and Web Development

Nov 13, 2013 (3 years and 8 months ago)

162 views

Web

2.0

Programming

1


©
Tongji

University ,
Computer

Science

and Technology
.

Web
编程技术

Web Programming Technology





同济大学计算机科学与技术系

2012


Web

2.0

Programming

2


©
Tongji

University ,
Computer

Science

and Technology
.

Outline



1


绪论



2


HTML

CSS
技术基础



3


Web
服务器端编程技术



4


动态编程技术



5


Web2.0
编程技术



6


Mashup
编程技术



7


云计算技术



8


云计算环境下的
Web
编程

Web

2.0

Programming

3


©
Tongji

University ,
Computer

Science

and Technology
.

Web
服务器端编程技术

Web

2.0

Programming

4


©
Tongji

University ,
Computer

Science

and Technology
.

Server
-
side programming


In many cases, client
-
side applications will be
insufficient


Heavy processing


Communication with other clients


Data available on server
-
side only


it may be useful to send the request to the
server and processing it


Many technologies : CGI, Servlets, JSP, ASP,
PHP and others


Next ,look at CGI, Servlets and JSP.

Web

2.0

Programming

5


©
Tongji

University ,
Computer

Science

and Technology
.

Static Pages

Retrieve file

Send file

Request file

Web

2.0

Programming

6


©
Tongji

University ,
Computer

Science

and Technology
.

Dynamic Pages

Do Computation


Generate HTML

page with results

of computation



Return dynamically generated HTML
file

Request service

Web

2.0

Programming

7


©
Tongji

University ,
Computer

Science

and Technology
.

Common Gateway Interface (CGI)


CGI is short of
Common Gateway Interface


CGI :
a standard programming interface to
Web servers that allows building dynamic and
interactive Web sites


CGI is not a programming language .


It is just a set of standards (protocols)


how Web
-
applications can be executed on the
server
-
side is specified by the standards

Web

2.0

Programming

8


©
Tongji

University ,
Computer

Science

and Technology
.

Common Gateway Interface (CGI)


CGI can be implemented in PERL or C


Any program can be converted to a CGI
program


It just has to follow the CGI rules


The rules define


How programs get and sends data (i.e.,
communication protocol)


How to make sure Web server know that a program is
a CGI program.

Web

2.0

Programming

9


©
Tongji

University ,
Computer

Science

and Technology
.

CGI


A CGI program is


Stored on the server,


Executed on the server,


Executed in response to request from client.


By running a CGI program,the server can
:


Display dynamic and updated information on web
page (e.g., weather forecast, stocks price, product
availability, etc…).


Respond to user’s input in time .


Keep user data on server
-
side in a file or DB.

Web

2.0

Programming

10


©
Tongji

University ,
Computer

Science

and Technology
.

Dynamic Pages

Run CGI program







print $result



Return dynamically generated HTML
file

Request service

<HEADER>

<BODY



</BODY>

Web

2.0

Programming

11


©
Tongji

University ,
Computer

Science

and Technology
.

Calling CGI Program


CGI program can be called in the same way like
that static HTML pages.


For example, a link that when clicked, will run CGI
program on the server
-
side

<a href=“http://www.mysite/cgi
-
bin/myprog”> Run my
CGI program </a>


Invoked by a form

<form action=“cgi
-
prog.cgi” method=“POST”>

. . .




</form>


Usually ,CGI programs are executed as processes

Web

2.0

Programming

12


©
Tongji

University ,
Computer

Science

and Technology
.

How does it know its CGI?


How does the Web server know whether the
request deals with static HTML page, or with a
CGI program?


The Web server is configured to provide clear
distinction between HTML and CGI files.


usually the CGI programs are put in a
cgi
-
bin

directory in Unix servers .


Access permissions are restricted


writing
to this directory is allowed to super
-
users, while

executing
is allowed to everybody
.

Web

2.0

Programming

13


©
Tongji

University ,
Computer

Science

and Technology
.

CGI invocation


HTTP GET request:

GET /webp/cgi
-
bin/printenv.pl HTTP/1.0


Looks like the standard of HTTP request, but
actually will not return
printenv.pl

file, but
rather the output of running it.


Different behaviors:


regular directory => returns the file


cgi
-
bin => returns output of the program


The behavior is determined by the server


E.g., i
f the path is
cgi
-
bin
, pass to CGI handler

Web

2.0

Programming

14


©
Tongji

University ,
Computer

Science

and Technology
.

CGI Input Data


Input parameters can be passed to a CGI program


For example, HTML forms wrap and encode the
form fields as a string :


var1=val1&var2=val2&var3=val3&…


This string is concatenated to the CGI URL, after
the
?

character


Example:
GET /webp/cgi
-
bin/printenv.pl?
var1=val1&var2=val2&var3=val3


CGI can extracte the parameters through
environment variables

Web

2.0

Programming

15


©
Tongji

University ,
Computer

Science

and Technology
.

GET vs. POST


In the
POST

method the data is sent to the CGI
separately, in the request body.


GET

method is not secure, the data is visible in
URL.


GET

is suitable for small amounts of data (limited
to 1K)


What about refreshing in
GET

and
POST
?

Web

2.0

Programming

16


©
Tongji

University ,
Computer

Science

and Technology
.

Security issues with CGI


Publicly accessible to CGI program allows
anyone to run a program on the server.


Malicious users may exploit security breaches,
and harm to the server.


For this ,many Web hosts do not let ordinary
users create CGI programs.


the use of CGI is permitted


special
wrapper

programs may be required so that
enhance security checks


limit the CGI program permissions.

Web

2.0

Programming

17


©
Tongji

University ,
Computer

Science

and Technology
.

CGI Summary


CGI :
a standard for interfacing Web client to the
programs running on server
-
side.


Specifies location of files so server knows to execute
them!.


The output is displayed differently according to it.


Simple examples using shell script, but complex ones
need more serious language.


Security breaches of CGI should be handled

Web

2.0

Programming

18


©
Tongji

University ,
Computer

Science

and Technology
.

Servlets vs. CGI


Servlet


Java
-
based CGI


Executed by servlets container


Faster and thinner


No fork
-
process execution like Perl


No need to initialize for each request


Only lightweight thread context switching


Built
-
in multithreading

Web

2.0

Programming

19


©
Tongji

University ,
Computer

Science

and Technology
.

Servlets vs. CGI


Multi
-
thread execution allows to:


share data across successive requests


share data between concurrent requests


use hidden fields, cookies, or sessions


Java supports “write once, run anywhere”


Java provides enhanced security


Supports all HTTP request methods


GET, POST, PUT, DELETE, and others

Web

2.0

Programming

20


©
Tongji

University ,
Computer

Science

and Technology
.

Servlet Architecture: 3
-
Tier system


Tier 1: Client


HTML browser


Java client


Tier 2: Servlets


embody business logic


secure, robust


Tier 3: Data Sources


Java can talk to SQL, JDBC, OODB, files, etc…

Web

2.0

Programming

21


©
Tongji

University ,
Computer

Science

and Technology
.

Web Application model

Client Tier

Middle Tier

Enterprise Information

System (EIS) Tier

application

browser

Web Container


Servlet

Servlet

JSP



Database

SQL

File
system

Web

2.0

Programming

22


©
Tongji

University ,
Computer

Science

and Technology
.

Servlet Name


Invoke Servlet by using its name


Servlet should be located in appropriate directory


A servlet’s name is its class name


Name is usually a single word


Possibly with a package name and dots


Standard names: such as DateServlet (echoes
current date/time), EchoServlet (bounces back
CGI parameters


Refer the server documentation

Web

2.0

Programming

23


©
Tongji

University ,
Computer

Science

and Technology
.

Servlet Invocation


Can be invoked directly using the
<servlet>

tag


pass servlet parameters in param tags


codebase of the servlet can be specified


<servlet code=DateServlet.class
codebase=http://servlets.foo.com/>

<param name=serviceParam1 value=val3>

<param name=serviceParam2 value=val4>

</servlet>


Typically invoked by form’s
action

attribute

Web

2.0

Programming

24


©
Tongji

University ,
Computer

Science

and Technology
.

The Servlet API


Defined in javax.servlet package


Independent of


Web protocol


server brand or platform


whether it is local or remote servlet


Provides core servlet functionality


just extend it


CGI
-
like functionality


generic interface


accepts query, returns response

Web

2.0

Programming

25


©
Tongji

University ,
Computer

Science

and Technology
.

The Servlet API


javax.servlet


Basic servlet API definitions.


How the inputs and outputs are to/from Servlet


Not tied to any specific protocol (e.g., HTTP)


These low
-
level classes/interfaces usually are not
used


javax.servlet.http


HTTP
-
related definitions


Extension of the basic interfaces to handle the HTTP
protocol functionality


This package is ofen used

Web

2.0

Programming

26


©
Tongji

University ,
Computer

Science

and Technology
.

Servlet Architecture Overview


Servlet Interface


methods to manage servlet


GenericServlet


implements Servlet


HttpServlet


extends GenericServlet


exposes HTTP
-
specific

functionality

Servlet

extends


doGet()


doPost()


service()


...

Override one or more of:


doGet()


doPost()


service()


...

Class

Interface

Class

Class

Class

extends

HttpServlet

implement
s

GenericServlet

UserServlet

Web

2.0

Programming

27


©
Tongji

University ,
Computer

Science

and Technology
.

Servlet Architecture Overview


ServletRequest


the client sends the request to the server


ServletResponse


the server sends the response to the client


being sent only after processing the request


HttpServletRequest, HttpServletResponse


HTTP
-
specific request and response


In addition to the regular request and response,
tracking client information and managing the session

Web

2.0

Programming

28


©
Tongji

University ,
Computer

Science

and Technology
.

The HelloWorld Servlet

import javax.servlet.*;

import java.io.*;

public class HelloServlet extends GenericServlet

{


public void service(ServletRequest req,



ServletResponse res) throws IOException,



ServletException{




res.setContentType("text/plain");




ServletOutputStream out = res.getOutputStream();




out.println("Hello, World!");


}

}

Web

2.0

Programming

29


©
Tongji

University ,
Computer

Science

and Technology
.

Servlet Lifecycle Overview


Server calls init() method


Loop


Server receives request from client


Server calls service() method


service() calls doGet() or doPost() methods


Server calls destroy() method


More detail in the next...

Web

2.0

Programming

30


©
Tongji

University ,
Computer

Science

and Technology
.

Servlet interface


Central abstraction in the Servlet API


All servlets implement this interface


Either directly, or


By extending another class that implements it


Defines abstract methods for managing the
servlet and its communications with clients


Servlet writers provide these methods


While developing servlets


Implementing the interface

Web

2.0

Programming

31


©
Tongji

University ,
Computer

Science

and Technology
.

Servlet classes


GenericServlet class


implements Servlet


also implements Serializable, ServletConfig


implements all Servlet methods


HttpServlet class


extends the GenericServlet class


provides a framework for handling the HTTP protocol


has its own subclasses of ServletRequest and
ServletResponse that do HTTP things

Web

2.0

Programming

32


©
Tongji

University ,
Computer

Science

and Technology
.

HttpServlet methods


HTTPServlet class provides helper methods for
handling HTTP requests


doGet (GET and HEAD)


doPost (POST)


doPut, doDelete (rare)


doTrace, doOptions (not overridden)


the requests to the appropriate do* method is
dispatched through the service() method

Web

2.0

Programming

33


©
Tongji

University ,
Computer

Science

and Technology
.

Generic Servlet vs. HTTP Servlet

GenericServlet

service ( )

Server

Client

HTTPServlet

service ( )

HTTP
Server

Browser

request

response

doGet


( )

doPost

( )

request

response

Web

2.0

Programming

34


©
Tongji

University ,
Computer

Science

and Technology
.

ServletRequest class


Encapsulates the client

server
communication


Allows the Servlet access to


Names of the parameters passed in by the client


The protocol being used by the client


The names of the remote host that made the request
and the server that received it


The input stream, ServletInputStream, through which
the servlet gets data from clients


Subclasses of ServletRequest allow the servlet
to retrieve more protocol
-
specific data


HttpServletRequest for accessing HTTP
-
specific
header information

Web

2.0

Programming

35


©
Tongji

University ,
Computer

Science

and Technology
.

ServletRequest
-

Client Info


getRemoteAddr()


Returns the IP address of the client that sent the
request


getRemoteHost()


Returns the fully qualified host name of the client that
sent the request


getProtocol()


Returns the protocol and version of the request as a
string
<protocol>/<major version>.<minor version>
.

Web

2.0

Programming

36


©
Tongji

University ,
Computer

Science

and Technology
.

ServletRequest
-

URL Info


getScheme()


Returns the scheme of the URL used in this request, for
example "http", "https", or "ftp".


getServerName()


Returns the host name of the server receiving the
request


getServerPort()


Returns the port number on which this request was
received


getServletPath()


Returns the URL path that got to this script, e.g.
“/servlet/com.foo.MyServlet”


Useful for putting in a <FORM> tag

Web

2.0

Programming

37


©
Tongji

University ,
Computer

Science

and Technology
.

ServletRequest
-

Contents


getContentLength()


Returns the size of the request data


getContentType()


Returns the MIME type of the request data


getInputStream()


Returns an input stream for reading binary data in the
request body.


getReader()


Returns a buffered reader for reading the request body.

Web

2.0

Programming

38


©
Tongji

University ,
Computer

Science

and Technology
.

ServletRequest
-

Parameters


String getParameter(String)


Returns a string containing one value of the specified
parameter, or null if the parameter does not exist.


String[] getParameterValues(String)


Returns the values of the specified parameter as an
array of strings, or null if the named parameter does not
exist.


Enumeration getParameterNames()


Returns the parameter names as an enumeration of
strings, or an empty enumeration if there are no
parameters or the input stream is empty.


Web

2.0

Programming

39


©
Tongji

University ,
Computer

Science

and Technology
.

ServletResponse class


Encapsulates the server

client
communication


Gives the servlet methods for replying to the client


Allows the servlet to set the content length and MIME
type of the reply


Provides an output stream, ServletOutputStream
through which the servlet can send the reply data


Subclasses of ServletResponse give the servlet
more protocol
-
specific capabilities.


HttpServletResponse for manipulating HTTP
-
specific
header information

Web

2.0

Programming

40


©
Tongji

University ,
Computer

Science

and Technology
.

ServletResponse


Embodies the response


Basic use:



response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println(

"<HTML><BODY>Hello</BODY></HTML>");


setContentType() is usually called before calling
getWriter() or getOutputStream()

Web

2.0

Programming

41


©
Tongji

University ,
Computer

Science

and Technology
.

ServletResponse
-

Output


getWriter()


for writing text data


getOutputStream()


for writing binary data


or for writing multipart MIME


And many other methods, similarly to the
methods of ServletRequest


Refer the documentation

Web

2.0

Programming

42


©
Tongji

University ,
Computer

Science

and Technology
.

Scalability of servlets


The
servlet

is only recompiled if it was changed
otherwise the already compiled class is loaded


Faster response times because the
servlet

does not
need to be recompiled


The
servlet

can be kept in memory for a long time
to service many sequential requests


Faster response times because the
servlet

does not
need to be reloaded


Only one copy of the
servlet

is held in memory
even if there are multiple concurrent requests


Less memory usage for concurrent requests and no
need to load another copy of the
servlet

and create a
new process to run it.

Web

2.0

Programming

43


©
Tongji

University ,
Computer

Science

and Technology
.

Java Server Pages


JSP


Java Servlets can be awkward to use.


Servlets often consist most statements to write out
HTML (with just a few dynamic calculations, database
access etc…).


writing servlets to produce attractive well “styled”
pages may be difficult


JSP allows to mix standard static HTML pages
with dynamically generated HTML.


Hybrid of HTML and servlets

Web

2.0

Programming

44


©
Tongji

University ,
Computer

Science

and Technology
.

Java Server Pages


JSP


JSP technically can not do anything that
servlets can not do


Following example displays how we get JSP
code embedded in the HTML


<html>

<head> … </head>

<body>

<h1> Todays date is:</h1>

<%= new java.util.Date() %>

</body>

</html>

Web

2.0

Programming

45


©
Tongji

University ,
Computer

Science

and Technology
.

Java Server Pages


JSP


by special JSP container ,JSPs execute as
part of a Web server


Basically, on first access to JSP code


it is automatically converted into servlet code


stored as servlets on the server


will be invoked on future requests


Notice the “first invocation delay”


JSP errors


Translation
-
time errors occur when JSP is
translated into servlets


Request
-
time errors occur during request
processing

Web

2.0

Programming

46


©
Tongji

University ,
Computer

Science

and Technology
.

JSP example

<body>


<% // begin JSP


String name = request.getParameter("firstName");


if ( name != null ) {


%> <%
--

end of JSP
--
%>



<h1> Hello <%= name %>, <br />


Welcome to JavaServer Pages! </h1>


<% // continue JSP


}


else {


%> <%
--

end of JSP
--
%>


<form action = "welcome.jsp" method = "get">


<p>Type your name and press Submit</p>


<p><input type = "text" name = "firstName" />


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


</p>


</form>


<% // continue JSP


} // end else


%> <%
--

end scriptlet
--
%>

</body>

Web

2.0

Programming

47


©
Tongji

University ,
Computer

Science

and Technology
.

JSP vs. Servlets


JSP


Look like standard HTML


Normally include HTML markup tags


HTML codes can be written easily


Used when content is mostly fixed
-
template data


Servlets


HTML codes must be written to the PrintWriter or
OutputStream


Used when small amount of content is fixed
-
template
data


Most content generated dynamically

Web

2.0

Programming

48


©
Tongji

University ,
Computer

Science

and Technology
.

Tomcat


Tomcat

is a Servlet Engine that processes servlet
requests for Apache application server


In another word,Tomcat is a “servlet container”


Tomcat can process Web pages, Servlets, and JSPs


Apache can process many types of Web services


It is easier to install Tomcat alone than as part of
Apache


Apache and Tomcat are open source (free)


In the next, we will focus on Tomcat

Web

2.0

Programming

49


©
Tongji

University ,
Computer

Science

and Technology
.

Which Should I Use? Client
-

or Server
-
Side?


If you want to have dynamic client forms with
client
-
side validation, you must use client
-
side
programming.


If you want your site to have highly interactive
pages, you should use client
-
side programming.


If you need to provide your client with advanced
functionality that can be created only using
ActiveX controls (or Flash, or …), you must use
client
-
side programming.

Web

2.0

Programming

50


©
Tongji

University ,
Computer

Science

and Technology
.

Which Should I Use? Client
-

or Server
-
Side?


If you want to control the user's browser (i.e., to
turn off the menus or place the browser in kiosk
mode), you must use client
-
side programming.


If your Web site must work with every browser
on the market, and you do not want to create
several different versions for different browsers,
you should avoid client
-
side programming.


If you want to protect your source code, you
must use only server
-
side programming. Client
-
side source code is transferred to the browser.

Web

2.0

Programming

51


©
Tongji

University ,
Computer

Science

and Technology
.

Which Should I Use? Client
-

or Server
-
Side?


If you need to track user information across
several Web pages to create a "Web
application“, you must use server
-
side
programming.


If you need to interact with server
-
side
databases, you must use server
-
side
programming.


If you need to use server variables or check the
capabilities of the user's browser, you must use
server
-
side programming.

Web

2.0

Programming

52


©
Tongji

University ,
Computer

Science

and Technology
.

Q

&

A