servlet and jsp programming: an introduction spiros papadimitriou [email protected]

21
Servlet and JSP Programming: An Introduction Spiros Papadimitriou [email protected]

Upload: mervyn-williamson

Post on 23-Dec-2015

225 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

Servlet and JSP Programming:An Introduction

Spiros [email protected]

Page 2: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

Overview

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

Page 3: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

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

Page 4: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

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…

Page 5: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

Static Pages

GET /path/index.html

Web Server

Filesystem

read /path/index.html<file contents>

STATUS …<file contents>

Page 6: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

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

Page 7: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

CGI

GET /cgi-bin/query?KEY=foo

STATUS …<response text foo>

CGI ProgramKEY=foo

<response text foo>

Web Server

Filesystem Database, etc

stdin

stdout

Page 8: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

CGI

GET /cgi-bin/query?KEY=bar

STATUS …<response text bar>

CGI ProgramKEY=bar

<responsetext bar>

Web Server

Filesystem Database, etc

stdin

stdout

Page 9: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

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)

Page 10: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

Servlets

GET /srv/pkg.Servlet?KEY=foo

STATUS …<response foo>

Web Server

Filesystem Database, etc

JVM

Servlet

doGet(req, res)res <respose foo>

Page 11: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

Servlets

GET /srv/pkg.Servlet?KEY=foo

STATUS …<response bar>

Web Server

Filesystem Database, etc

JVM

Servlet

doGet(req, res

)

res <response ba

r>

Page 12: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

Servlet Examplepackage pkg;

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class Servlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><head><title>Sample Servlet"); out.println("</title></head><body>"); out.println("<h1>Hello World at " + req.getRequestURI() + " !</h1>"); out.println(”<p>Key is " + req.getParameter("KEY")); out.println(”</p></body></html>"); } }

Page 13: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

More Servlets A catalog of servlet methods:

– init(config)– service(req, res)

• doGet(req, res)• doPut(req, res)• doDelete(req, res)• etc…

A catalog of request methods:– getParameter(name)– getParameterNames(), getParameterValues(name)– getCookies()

A catalog of response methods:– sendRedirect(url), sendError(errCode, errStr)– setContentType(mimeType)– addCookie(cookieObj)

Page 14: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

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)

Page 15: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

First JSP Example (1/3)<%@ page import=“java.io.*” %><html><head><title>Sample JSP</title></head><% String s = “JSP”; %><body><h1>Hello <%= s %> World!</h1><p><% out.print(“Scriptlet Statement Hello!”); %></p><p>Key is <%= request.getParameter(“KEY”) %></p></body></html>

Core syntactic elements:– Directives <%@ page … %>– Declarations <%! … %> (outside service method)– Scriptlets <% … %>– Expressions <%= … %>

Page 16: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

First JSP Example (2/3)package jsp._jsp;

// line:/jsp/hello.jsp:1import java.io.*;

import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;

public class _hello_2ejsp extends org.gjt.jsp.HttpJspPageImpl implements org.gjt.jsp.GnuJspPage { […] public void _jspService (HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType ("text/html"); […] HttpSession session = pageContext.getSession (); JspWriter out = pageContext.getOut (); […]

Page 17: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

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.getParameter(“KEY”)); // line:/jsp/hello.jsp:8 out.print(“</p>\n</body>[…]”); } catch (Throwable e) { […] } }}

Page 18: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

Second JSP Example (1/2)<%@ page import=“java.io.*” %><%@ page import=“java.util.*” %><%@ page import=“java.sql.*” %><%! Static final String dbHost = “…”; %> Static final String oracleDriver = “…”;%><% String courseId = request.getParameter(“courseid”); Class.forName(oracleDriver); Connection conn = DriverManager.getConnection(…); Statement stmt = con.createStatement(); String qry = “SELECT STUDENT.SID, SNAME, COURSE.CID ” + “FROM STUDENT, COURSE, TAKE ” + “WHERE TAKE.CID = ‘” + courseId + “’ AND ” + “STUDENT.SID = TAKE.SID AND ” + “COURSE.CID = TAKE.CID;” ResultSet res = conn.executeQuery(qry);%>

Page 19: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

Second JSP Example (2/2)<html><head><title>Student Information</title></head>

<body><h1>Student Information for <%= courseId %></h1>

<p><table border=“1”><tr><th>CourseID</th><th>Student</th><th>StudentID</th></tr><% while (rs.next()) { %> <tr> <td><%= rs.getString(“cid”) %></td> <td><%= rs.getString(“sname”) %></td> <td><%= rs.getString(“sid”) %></td> </tr><% } // end while %></table></p>

</body></html>

Page 20: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

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) / FastCGI– Too little, too late

Modern web publishing systems– Essentially databases that “speak HTTP”

Page 21: Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu

More Information

Servlets and JSPs:– http://java.sun.com/products/servlet/– http://java.sun.com/products/jsp/

JDBC:– http://java.sun.com/products/jdbc/