Post on 28-Mar-2015
CGI programming
Common Gateway Interface
• interface between web server and other programs (cgi scripts)
• information passed as environment variables
• passed to standard input (STDIN)
• script outputs to standard output (STDOUT)
• output is http response message
CGI Environment
• Web Server defines– working directory– preset variables– filehandles (links to resources on the server)
• CGI script must produce– minimal set of response headers
• e.g. Content-Type: text/html
– content of http response
Environment Variables
• provide info about the web server and the client
• information drawn from http request headersSERVER_NAME
REMOTE_ADDR
CONTENT_LENGTH
CONTENT_TYPE
Server-Script interface
• STDIN– Web server launches CGI program and
provides standard input
• STDOUT– CGI program outputs response to web server
• STDERR– Web server handles CGI program error output– Apache appends it to error log
CGI Output
• headers:– Content-Type
•print “Content-Type:text/html\n\n”;
– Location•print “Location:someFile.html\n\n”;
– Status•print “503 Service unavailable”;
CGI Example
CGI Example
Ice Cream Stand Design
BrowserWeb
ServerCGI
Script
Present order form and response
Handle request and response
Produce order form
Process order form
CGI script design
• Input– Form data
• Output– Order form– Order response
• Self-referencing form
ice cream stand CGI script
#!/usr/local/bin/perl #ice cream stand cgi script use CGI qw(:standard); print (header(),start_html("Ice Cream Stand"),h1("Ice Cream Stand")); if (param()) { #the form has been filled out $who = param("name"); $flavour = param("flavour"); $scoops = param("scoops"); $vat = 1.175; $cost = sprintf("%.2f", $vat*(1.00 + $scoops*0.25)); print p("OK $who, have $scoops scoops of $flavour for £$cost.");
ice cream stand CGI script
} else {# present the form print (hr, start_form()); print p("What is your name",textfield("name")); print p("What flavour: ", popup_menu("flavour", ['mint','cherry','mocha'] )); print p("How many scoops? ", popup_menu("scoops",[1..3] )); print p(submit("order"), reset("clear")); print (end_form, hr); } print end_html;
CGI is programmer-oriented
• HTML embedded in the program
• HTML generated as a series of function calls
• requires– knowledge of HTML tags– programming skills
Does CGI implement M-V-C?
• No!
• Data processing (model) is inseparable from response page generation (view)
• Also contains elements of controller– Handles request headers and creates response
headers
CGI security problems
• scripts can be corrupted by user data– hidden fields– arbitrary commands embedded in text fields
• file permissions
• file locations
• trust relationships between web server and other machines
speed of CGI
• each request creates a new process
• overhead of communication through CGI
• overhead of interpretation and compilation
• Possible solutions (only partly effective)– code optimisation– Fast CGI– mod_perl with Apache
Alternatives to CGI
• Java servlets
• JSP - Java Server Pages
• PHP
• ASP - Active Server Pages
• Coldfusion
Java Servlets
Servlets
• add functionality to a web server
• comparable to CGI– More tightly defined– Separate http handling from middleware– Deployed in a web container (see later)
• vendor and platform independent (Java)
• integrate with other Java technologies– J2EE framework
Servlets
• efficient– permanently available, no compile overhead
• robust– encapsulation, type-checking, error handling
• secure– specialised interfaces to other server resources
that are not vulnerable to attack
Servlets• implement javax.servlet.Servlet interface
public void init(ServletConfig c)run on initialisation
public void service (ServletRequest req, ServletResponse res)runs for each request and response
public void destroy ()end of servlet life
WebServer
ServletClass
init(ServletConfig c)
service(ServletRequest r, ServletResponse s)
destroy()
once at first request or at server start
every request
once when server shuts down
webcontainer
HTTP servlets
• Most commonly used servlet subclass– javax.servlet.http.HttpServlet
• implements additional methods to handle http functionality
• service() method passes handling to more specific sub-class methods– doGet, doPost …
The “Hello World” servlet
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWorld extends HttpServlet{
The “Hello World” servlet
public void doGet (HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {res.setContentType(“text/html”);
Printwriter out = res.getWriter();
The Hello World servlet
out.println (“<html>”);out.println (“<head><title>”);out.println (“Hello World”);out.println (“</title></head>”);out.println (“<body>”);out.println (“<h1>Hello World</h1>”);out.println (“</body></html>”); }}
Servlets vs CGI
• similar idea– web container “like” CGI environment – request and response objects vs std I/O
• servlet compilation once only– much faster, even though run in JVM
• security problems greatly reduced– web container is much more secure
• but still HTML embedded in code
Java Server Pages
Java Server Pages (JSP)
• Template for page generation
• Separates code from HTML
• HTML with additional jsp tags processed on server side
• links to other Java entities for more complex processing/ database access
• platform independent
JSP elements
• A JSP is a template for generating a web page– Response to an http request
• JSP elements are tags embedded in HTML• JSP scripting elements
– Specify Java code to be run when template is requested
– Separate the coding from HTML content• Fits with M-V-C philosophy
<HTML><HEAD><TITLE>JSP Digital Clock</TITLE>
</HEAD><BODY><H1>Date and Time</H1>
<!--table in here--><%= new java.util.Date.toString() %><!-- end table--></BODY></HTML>
Simple JSP Example
JSP scripting elements• Three different kinds of scripting,
determining when each is executed:• Insert snippets of Java code
<% … %>• embed a code expression, which
evaluates in the response (no ;)<%= … %>
• declare variables and methods<%! … %>
Examples
<!--Declare a variable--><%! String name = “Gandalf”; %>
<!-- Do some processing--><% name = name + “ the Grey”;%>
<!-- Output a result--><h1><%= name %></h1>
result
JSP and Servelets
How does JSP work?
• NOT a Java scripting language
• NOT like php– JSP are NOT parsed on request
• Java code must involve classes, creation of objects, etc…
• JSP is a designer-friendly way of writing servlets
Clock example
Server withTomcat
WebContainer
client
translationrequest processing
GET clock.jsp
1clock.jsp
read2
Serveletclock.java
generate
3
clock.class
compile and deploy
4
execute
5
http response
6
public class clock implements Servlet { public void service (ServletRequest r, ServletResponse s) throws ServletException, IOException { s.setContentType (“text/html”); PrintWriter out = s.getWriter (); out.println (“<HTML>”); out.println (“<HEAD>”); out.println (“<TITLE>JSP… </TITLE>”); out.println (“</HEAD>”); out.println (“<BODY>”);
out.println(“<H1>Date and Time</H1>”);
out.println(new
java.util.Date.toString()); out.println (“</BODY>”); out.println (“</HTML>”); }}
JSP directive elements
• applied when the JSP is compiled into a servelet– Only executed once (on compilation)– Do not affect the response
• Used to set up resources such as– Java classes– inclusions
JSP directive elements
• specify page information (static)
<%@ page … >scripting language, error page
<%@ include … >includes a file, e.g. an applet
<%@ taglib … >declare a tag library (custom actions)
JSP and http
JSP and http
• A JSP is a servelet
• Permanently resident in server memory
• Multi-threaded
• Request and response objects
• Sessions and cookies
Accessing request information
• Methods of the request object provide all request information
• object is called “request”
public String getParameter (String name)
public String getMethod ()
public String getHeader (String name)
public Cookie [] getCookies ()
javax.servelet.http.Cookie class• getName ()
– the name of the cookie
• getValue(), setValue (String value)– gets/sets the value of a cookie
• getDomain(), setDomain(String dName)– get/set the cookie domain name
• getPath(), String setPath(String path)– get/set the request path the cookie is associated with
• getMaxAge(), setMaxAge (int expiry)– get/set maximum age for the cookie
javax.servelet.http.HttpSession
• provides standard functionality for handling sessions
• handles cookies as standard but must be extended to handle URL rewriting
• holds client state info resident in memory– automatically times out abandoned sessions
• created/returned by HttpServeletRequest class getSession method
JSP and Java Beans
Java Beans
• ordinary Java classes with the following properties:– introspection– customization– events– properties– persistence
Java Beans
• introspection– an analyser can inspect how the Bean works
• properties– naming conventions for getter and setter methods
• persistence– implement the Serializable interface– Bean state can be stored
Example Java beanpublic class ExampleBean implements
java.io.Serializable {private String name = null;private int score = 0;
public ExampleBean() {} // Empty constructor
/* Getter and Setter Methods */public String getName() {
return name;}
public void setName(String s) {name = s;
}
Example Java bean
public int getScore() {return score;
}
public void setScore(int i) {score = i;
}
/* No method required to implement
Serializable*/
}
JSP action elements
• action elements– perform an action when page is requested
<jsp:useBean>uses a JavaBean component
<jsp:getProperty>property from JavaBean used in the page
<jsp:setProperty>sets a JavaBean property (possibly
using request information)
<jsp:useBeanid="userInfo"
class="com.ora.jsp.beans.userInfo.UserInfoBean“>
<jsp:setPropertyname = “userInfo”property = “userName”value = “Gandalf”/>
</jsp:useBean>
The following information was saved:
<ul><li>User Name:<jsp:getProperty
name="userInfo"property="userName"/></li>
<li>Email Address:<jsp:getProperty
name="userInfo"property="emailAddr"/></li>
</ul></body></html>
Other JSP action elements
<jsp:include>responses from other jsp pages or servelets
<jsp:forward>forwards processing to other jsp or servelet
<jsp:param>passes a parameter with include or forward
<jsp:plugin>generates the HTML to embed an applet
Timetable change
• From 10 November:
• Two lectures moved into one slot:– Wednesday 11-1– B39– (lab with GE being moved)
• Labs will still be Thursday, 9-11