210 likes | 221 Views
Learn the basics of Servlet and Java Server Pages (JSP) programming, including static vs dynamic web content, building database-backed web applications, and utilizing Java inside a web server.
E N D
Servlet and JSP Programming:An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu
Overview • Introduction • Static vs. Dynamic • Servlets • Java Server Pages (JSP)
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 • Webserver accepts pathnames • Returns contents of corresponding file • Boring! • Can’t generate customized content—always serve the same static pages…
Web Server GET /path/index.html STATUS … <file contents> read /path/index.html <file contents> Filesystem Static Pages
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
Web Server GET /cgi-bin/query?KEY=foo KEY=foo CGI Program <response text foo> STATUS … <response text foo> stdin Filesystem Database, etc stdout CGI
Web Server CGI Program STATUS … <response text bar> GET /cgi-bin/query?KEY=bar KEY=bar <response text bar> stdin Filesystem Database, etc stdout CGI
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)
Web Server GET /srv/pkg.Servlet?KEY=foo JVM doGet(req, res) Servlet Filesystem Database, etc Servlets STATUS … <response foo> res <respose foo>
Web Server JVM Servlet GET /srv/pkg.Servlet?KEY=foo doGet(req, res) Filesystem Database, etc Servlets res <response bar> STATUS … <response bar>
Servlet Example package 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>"); } }
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)
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> <% 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 <%= … %>
First JSP Example (2/3) package jsp._jsp; // line:/jsp/hello.jsp:1 import 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 (); […]
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) { […] } } }
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); %>
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>
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”
More Information • Servlets and JSPs: • http://java.sun.com/products/servlet/ • http://java.sun.com/products/jsp/ • JDBC: • http://java.sun.com/products/jdbc/