Download presentation
Presentation is loading. Please wait.
Published byMervyn Williamson Modified over 9 years ago
1
Servlet and JSP Programming: An Introduction Spiros Papadimitriou spapadim@cs.cmu.edu
2
Overview Introduction Static vs. Dynamic Servlets Java Server Pages (JSP)
3
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
4
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…
5
Static Pages GET /path/index.html Web Server Filesystem read /path/index.html STATUS …
6
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
7
CGI GET /cgi-bin/query?KEY=foo STATUS … CGI Program KEY=foo <response text foo> Web Server Filesystem Database, etc stdin stdout
8
CGI GET /cgi-bin/query?KEY=bar STATUS … CGI Program KEY=bar <response text bar> Web Server Filesystem Database, etc stdin stdout
9
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)
10
Servlets GET /srv/pkg.Servlet?KEY=foo STATUS … Web Server Filesystem Database, etc JVM Servlet doGet(req, res) res
11
Servlets GET /srv/pkg.Servlet?KEY=foo STATUS … Web Server Filesystem Database, etc JVM Servlet doGet(req, res) res
12
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(" Sample Servlet"); out.println(" "); out.println(" Hello World at " + req.getRequestURI() + " ! "); out.println(” Key is " + req.getParameter("KEY")); out.println(” "); }
13
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)
14
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)
15
First JSP Example (1/3) Sample JSP Hello World! Key is Core syntactic elements: –Directives –Declarations (outside service method) –Scriptlets –Expressions
16
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 (); […]
17
First JSP Example (3/3) try { // line:/jsp/hello.jsp:2 out.print(" \n[…]"); // line:/jsp/hello.jsp:4 String s = "GNUJSP"; // line:/jsp/hello.jsp:5 out.print("\n […]"); // 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(“ \n […]”); } catch (Throwable e) { […] } }
18
Second JSP Example (1/2) <%! 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); %>
19
Second JSP Example (2/2) Student Information Student Information for CourseID Student StudentID
20
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”
21
More Information Servlets and JSPs: –http://java.sun.com/products/servlet/ –http://java.sun.com/products/jsp/ JDBC: –http://java.sun.com/products/jdbc/
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.