Servlet and JSP Programming An Introduction Spiros Papadimitriou

  • Slides: 21
Download presentation
Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs. cmu. edu

Servlet and JSP Programming: An Introduction Spiros Papadimitriou [email protected] cmu. edu

Overview § § Introduction Static vs. Dynamic Servlets Java Server Pages (JSP)

Overview § § Introduction Static vs. Dynamic Servlets Java Server Pages (JSP)

Introduction § What you know: – Java – JDBC § What we’ll tell you:

Introduction § What you know: – Java – JDBC § What we’ll tell you: – How to use Java inside a webserver! § Why you might care: – Building non-trivial web interfaces and applications – In particular: database-backed web applications

Plain Old Static Pages § Static webpages – Plain files stored in the filesystem

Plain Old Static Pages § Static webpages – Plain files stored in the filesystem – Webserver accepts pathnames – Returns contents of corresponding file § Boring! – Can’t generate customized content—always serve the same static pages…

Static Pages Web Server GET /path/index. html STATUS … <file contents> read /path/index. html

Static Pages Web Server GET /path/index. html STATUS … <file contents> read /path/index. html Filesystem

Dynamic Content § CGI: Easy “fix” – – – Common Gateway Interface Oldest standard

Dynamic Content § CGI: Easy “fix” – – – Common Gateway Interface Oldest standard But at least a standard! Inefficient No persistent state § Forward requests to external programs – Spawn one process for each new request (ouch!) – Communicate via • Standard input/output • Environment variables – Process terminates after request is handled

CGI GET /cgi-bin/query? KEY=foo STATUS … <response text foo> Web Server KEY=foo CGI Program

CGI GET /cgi-bin/query? KEY=foo STATUS … <response text foo> Web Server KEY=foo CGI Program <response text foo> stdin stdout Filesystem Database, etc

CGI Web Server GET /cgi-bin/query? KEY=bar CGI Program <response text bar> STATUS … <response

CGI Web Server GET /cgi-bin/query? KEY=bar CGI Program <response text bar> STATUS … <response text bar> stdin stdout Filesystem Database, etc

Servlets to the rescue… § Little Java programs… – Contain application-specific code – Web

Servlets to the rescue… § Little Java programs… – Contain application-specific code – Web server does generic part of request handling – Servlets run “in” the web server and do some of the handling § Highlights – – Standard! Efficiency (much better than CGI) Security (Java!) Persistence (handle multiple requests)

Servlets GET /srv/pkg. Servlet? KEY=foo Web Server JVM do. G STATUS … <response foo>

Servlets GET /srv/pkg. Servlet? KEY=foo Web Server JVM do. G STATUS … <response foo> res et( <re req Filesystem spo , r es) se foo Servlet > Database, etc

Servlets Web Server JVM Servlet GET /srv/pkg. Servlet? KEY=foo STATUS … <response bar> req,

Servlets Web Server JVM Servlet GET /srv/pkg. Servlet? KEY=foo STATUS … <response bar> req, do. Get( res) r> onse ba p s e r < res Filesystem Database, etc

Servlet Example package pkg; import java. io. *; import javax. servlet. http. *; public

Servlet Example package pkg; import java. io. *; import javax. servlet. http. *; public class Servlet extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws IOException, Servlet. Exception { res. set. Content. Type("text/html"); Print. Writer out = res. get. Writer(); out. println("<html><head><title>Sample Servlet"); out. println("</title></head><body>"); out. println("<h 1>Hello World at " + req. get. Request. URI() + " !</h 1>"); out. println(”<p>Key is " + req. get. Parameter("KEY")); out. println(”</p></body></html>"); } }

More Servlets § A catalog of servlet methods: – init(config) – service(req, res) •

More Servlets § A catalog of servlet methods: – init(config) – service(req, res) • do. Get(req, res) • do. Put(req, res) • do. Delete(req, res) • etc… § A catalog of request methods: – get. Parameter(name) – get. Parameter. Names(), get. Parameter. Values(name) – get. Cookies() § A catalog of response methods: – send. Redirect(url), send. Error(err. Code, err. Str) – set. Content. Type(mime. Type) – add. Cookie(cookie. Obj)

JSP… Sugar § Printing to output not really a special case when writing heaps

JSP… Sugar § Printing to output not really a special case when writing heaps of HTML! § Well… why not make that the common case in the syntax and program statements the “special case? ” § And while we’re at it, why not hide the compilation steps (let the server do it)? § Now things look more like “plain old HTML” (only they aren’t… they can produce dynamic content and really are Java programs)

First JSP Example (1/3) <%@ page import=“java. io. *” %> <html> <head><title>Sample JSP</title></head> <%

First JSP Example (1/3) <%@ page import=“java. io. *” %> <html> <head><title>Sample JSP</title></head> <% String s = “JSP”; %> <body> <h 1>Hello <%= s %> World!</h 1> <p><% out. print(“Scriptlet Statement Hello!”); %></p> <p>Key is <%= request. get. Parameter(“KEY”) %></p> </body> </html> § Core syntactic elements: – – Directives <%@ page … %> Declarations <%! … %> (outside service method) Scriptlets <% … %> Expressions <%= … %>

First JSP Example (2/3) package jsp. _jsp; // line: /jsp/hello. jsp: 1 import java.

First JSP Example (2/3) package jsp. _jsp; // line: /jsp/hello. jsp: 1 import java. io. *; import javax. servlet. http. *; import javax. servlet. jsp. *; public class _hello_2 ejsp extends org. gjt. jsp. Http. Jsp. Page. Impl implements org. gjt. jsp. Gnu. Jsp. Page { […] public void _jsp. Service (Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, java. io. IOException { response. set. Content. Type ("text/html"); […] Http. Session session = page. Context. get. Session (); Jsp. Writer out = page. Context. get. Out (); […]

First JSP Example (3/3) try { // line: /jsp/hello. jsp: 2 out. print("<html>n[…]"); //

First JSP Example (3/3) try { // line: /jsp/hello. jsp: 2 out. print("<html>n[…]"); // line: /jsp/hello. jsp: 4 String s = "GNUJSP"; // line: /jsp/hello. jsp: 5 out. print("n<body>[…]"); // line: /jsp/hello. jsp: 6 out. print(s); […] // line: /jsp/hello. jsp: 7 out. print(“Scriptlet Statement Hello!”); […] // line: /jsp/hello. jsp: 8 out. print(request. get. Parameter(“KEY”)); // line: /jsp/hello. jsp: 8 out. print(“</p>n</body>[…]”); } catch (Throwable e) { […] } } }

Second JSP Example (1/2) <%@ page import=“java. io. *” %> <%@ page import=“java. util.

Second JSP Example (1/2) <%@ page import=“java. io. *” %> <%@ page import=“java. util. *” %> <%@ page import=“java. sql. *” %> <%! Static final String db. Host = “…”; %> Static final String oracle. Driver = “…”; %> <% String course. Id = request. get. Parameter(“courseid”); Class. for. Name(oracle. Driver); Connection conn = Driver. Manager. get. Connection(…); Statement stmt = con. create. Statement(); String qry = “SELECT STUDENT. SID, SNAME, COURSE. CID ” + “FROM STUDENT, COURSE, TAKE ” + “WHERE TAKE. CID = ‘” + course. Id + “’ AND ” + “STUDENT. SID = TAKE. SID AND ” + “COURSE. CID = TAKE. CID; ” Result. Set res = conn. execute. Query(qry); %>

Second JSP Example (2/2) <html> <head><title>Student Information</title></head> <body> <h 1>Student Information for <%= course.

Second JSP Example (2/2) <html> <head><title>Student Information</title></head> <body> <h 1>Student Information for <%= course. Id %></h 1> <p><table border=“ 1”> <tr><th>Course. ID</th><th>Student. ID</th></tr> <% while (rs. next()) { %> <tr> <td><%= rs. get. String(“cid”) %></td> <td><%= rs. get. String(“sname”) %></td> <td><%= rs. get. String(“sid”) %></td> </tr> <% } // end while %> </table></p> </body> </html>

Alternatives § Dynamically loadable server modules – – – Web server offers standard API

Alternatives § Dynamically loadable server modules – – – Web server offers standard API for request handlers Request handlers are dynamic libraries Loaded into server address space (security? !) Very efficient! Better suited for generic server extensions than application-specific logic § CGI flavors – Persistent CGI (PCGI) / Fast. CGI – Too little, too late § Modern web publishing systems – Essentially databases that “speak HTTP”

More Information § Servlets and JSPs: – http: //java. sun. com/products/servlet/ – http: //java.

More Information § Servlets and JSPs: – http: //java. sun. com/products/servlet/ – http: //java. sun. com/products/jsp/ § JDBC: – http: //java. sun. com/products/jdbc/