CGI programming. Common Gateway Interface interface between web server and other programs (cgi...

58
CGI programming

Transcript of CGI programming. Common Gateway Interface interface between web server and other programs (cgi...

Page 1: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

CGI programming

Page 2: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 3: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 4: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Environment Variables

• provide info about the web server and the client

• information drawn from http request headersSERVER_NAME

REMOTE_ADDR

CONTENT_LENGTH

CONTENT_TYPE

Page 5: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 6: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

CGI Output

• headers:– Content-Type

•print “Content-Type:text/html\n\n”;

– Location•print “Location:someFile.html\n\n”;

– Status•print “503 Service unavailable”;

Page 7: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

CGI Example

Page 8: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

CGI Example

Page 9: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Ice Cream Stand Design

BrowserWeb

ServerCGI

Script

Present order form and response

Handle request and response

Produce order form

Process order form

Page 10: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

CGI script design

• Input– Form data

• Output– Order form– Order response

• Self-referencing form

Page 11: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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.");

Page 12: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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;

Page 13: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

CGI is programmer-oriented

• HTML embedded in the program

• HTML generated as a series of function calls

• requires– knowledge of HTML tags– programming skills

Page 14: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 15: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 16: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 17: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Alternatives to CGI

• Java servlets

• JSP - Java Server Pages

• PHP

• ASP - Active Server Pages

• Coldfusion

Page 18: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Java Servlets

Page 19: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 20: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 21: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 22: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 23: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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 …

Page 24: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

The “Hello World” servlet

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWorld extends HttpServlet{

Page 25: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

The “Hello World” servlet

public void doGet (HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {res.setContentType(“text/html”);

Printwriter out = res.getWriter();

Page 26: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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>”); }}

Page 27: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 28: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Java Server Pages

Page 29: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 30: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 31: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

<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

Page 32: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Page 33: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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<%! … %>

Page 34: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Examples

<!--Declare a variable--><%! String name = “Gandalf”; %>

<!-- Do some processing--><% name = name + “ the Grey”;%>

<!-- Output a result--><h1><%= name %></h1>

Page 35: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

result

Page 36: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

JSP and Servelets

Page 37: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 38: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Clock example

Page 39: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 40: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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>”);

Page 41: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

out.println(“<H1>Date and Time</H1>”);

out.println(new

java.util.Date.toString()); out.println (“</BODY>”); out.println (“</HTML>”); }}

Page 42: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 43: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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)

Page 44: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

JSP and http

Page 45: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

JSP and http

• A JSP is a servelet

• Permanently resident in server memory

• Multi-threaded

• Request and response objects

• Sessions and cookies

Page 46: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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 ()

Page 47: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 48: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 49: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

JSP and Java Beans

Page 50: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Java Beans

• ordinary Java classes with the following properties:– introspection– customization– events– properties– persistence

Page 51: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 52: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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;

}

Page 53: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

Example Java bean

public int getScore() {return score;

}

public void setScore(int i) {score = i;

}

/* No method required to implement

Serializable*/

}

Page 54: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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)

Page 55: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

<jsp:useBeanid="userInfo"

class="com.ora.jsp.beans.userInfo.UserInfoBean“>

<jsp:setPropertyname = “userInfo”property = “userName”value = “Gandalf”/>

</jsp:useBean>

Page 56: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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>

Page 57: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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

Page 58: CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.

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