Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Servlets: A QuickStart for CS Educators Dawn Wilkins and Kathy Gates The University of Mississippi.

Similar presentations

Presentation on theme: "Java Servlets: A QuickStart for CS Educators Dawn Wilkins and Kathy Gates The University of Mississippi."— Presentation transcript:

1 Java Servlets: A QuickStart for CS Educators Dawn Wilkins and Kathy Gates The University of Mississippi

2 Workshop Description l This workshop is designed to give CS educators, who have a working knowledge of Java, a good introduction to Java servlets. The servlet architecture and life cycle will be explained, and examples will be provided to demonstrate the use of the Java Servlet API. Advanced features including accessing databases through a servlet and session tracking will be covered. Setting up Java servlet development environment for students will also be addressed.

3 Contents l Background l Java Servlet Basics l A Comparison of Servlets & CGI l The Servlet Architecture l A Few Example Servlets l IDE’s & Server Options l Servlet Basics: A Closer Look l Servlets & JDBC l Session Tracking l Java Server Pages l Practical Applications l Resources

4 Software Demonstration Setup l Windows NT l Internet Explorer l Borland Jbuilder l Apache with Tomcat l Mysql Database – l PHP & phpMyAdmin

5 A Historical Perspective l First efforts at dynamic Web content –Common Gateway Interface (CGI) –Fast CGI l Proprietary Solutions –Microsoft’s Active Server Pages –Netscape’s Javascript

6 CGI: What is it? l A standard interface between a Web server and an application. l One of the first practical ways for generating dynamic content. l Runs as a separate process from the Web server. Common Gateway Interface (CGI) programs can be written in many languages, including Java. Perl is the most common language for CGI's, due to its advanced text processing capabilities.

7 Interaction with CGIs (From Developing Java Servlets: The Authoritative Solution by James Goodwill, p. 8)

8 An Example CGI Program l Hello World Hello World –See demonstration.

9 Common Gateway Interface l Advantages –Easy to get started –Simple programming interface –Popular scripting languages such as Perl offer powerful way to quickly develop new applications –Widely used l Disadvantages –New process is started for each CGI call –Separate process means limited interaction with Web server and possible loss of communication –May hit operating system limits on number of processes

10 Java Servlet Basics l First there was the applet -- high hopes, but probably did not reach expected potential. –Slow to load –Not operable on all browsers –Security issues l So, what is a servlet? –Java embedded in a Web server to extend the Web server's capabilities. –Whereas applets run in the Web browser, servlets run in the Web server. l Terms to Note: –Container vs. Engine –Filtering vs. Chaining –Contexts vs. Zones

11 Interaction with Servlets (From Developing Java Servlets: The Authoritative Solution by James Goodwill, p. 6)

12 Advantages of Servlets l Adds Persistence to a Stateless Web –The servlet's thread doesn't have to terminate once it sends back a response. l Platform Independent –Servlets port easily to other systems with JVM. l Efficient –Servlets are loaded once instead of each time they are executed. –The servlet is first loaded via the init() method and can perform potentially costly start-up functions once.

13 More Advantages l Function as Direct Extensions of the Web Server –Supports interaction with the server itself l Gaining Wide-Spread Acceptance l Built-in Support for Many Server Features –The developer can be free of certain server details. l Extensible –Object-oriented approach facilitates new development.

14 Disadvantages of Servlets l Servlets can be more complicated to set up. l Servlets must be recompiled whenever a change is made. l On their own, servlets do not provide a way to embed code into HTML documents such as with ColdFusion or PHP; however, this is addressed with JSP.

15 Guidelines for Choosing When should you use Servlets instead of CGI? l Nature of the Application –What is the hardware/software platform? –How long-term is it? –How much development time is available? –Who will maintain the application? –What other information systems does it interface with? –How many hits do you anticipate?

16 A Review of HTTP l Simple & Stateless l The client makes a request and the Web server responds. l The client request includes: –an HTTP command or “method” that tells what action to perform –a URL –the version of the HTTP protocol it is using. Hypertext Transfer Protocol (HTTP)

17 HTTP Responses l The server processes the request and sends back a response. l The first line of the response specifies: –the version of the HTTP protocol the server is using, –a status code, and –a description of the status code. For example, 200 means successful. The server also sends the client info telling what kind of software it is running and the content of the response.

18 HTTP Methods l GET is generally used by a client to request a resource from the server. l POST is normally used to pass user input to the server. The two most popular HTTP methods are GET & POST.

19 The GenericServlet Request (From Developing Java Servlets: The Authoritative Solution by James Goodwill, p. 13)

20 Generic Servlet API Methods l The interface javax.servlet.Servlet provides the framework for all servlets through five methods. l * init() –Servlet is constructed and initialized. l getServletConfig() –Returns startup configuration and initialization parameters. l * service() –Receives two objects: ServletRequest and ServletResponse l getServletInfo() –Provides the servlet user with information about the servlet itself. l * destroy() –Signifies the end of the servlet’s life. * Life cycle methods

21 Servlet Requests & Responses l ServletRequest allows access to names of parameters passed by the client, the protocol, etc. l ServletResponse allows the servlet to set the content length & MIME type of the reply and provides a means by which the servlet can send the reply data. The service() method accepts two parameters: ServletRequest ServletResponse.

22 Generic vs. HTTP Servlets l The HttpServlet Class is extended from GenericServlet. l Generic servlets should override the service() method; however, service() is already implemented in HttpServlet. l HttpServlets override doGet() to handle GET requests and doPost() to handle POST requests. l Other HttpServlet methods are also available.

23 The HttpServlet Request (From Developing Java Servlets: The Authoritative Solution by James Goodwill, p. 14)

24 An Example Servlet l Hello World Hello World –See demonstration.

25 Skeleton Servlet public class skeletonServlet extends HttpServlet { // declaration of instance variables public void init (ServletConfig config) throws ServletException { super.init (config); // initialize resources here }

26 Skeleton Servlet, part 2 public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {... } public void doPost (HttpServletRequest request, HttpServletResponse response) { … }

27 Skeleton Servlet, part 3 public String getServletInfo () { return “The purpose of this servlet is …” } public void destroy () { { // free resources here } } // skeletonServlet

28 Servlets & HTML l Creating HTML Documents –setContentType() –getWriter() l Retrieving Form Data –getParameterNames() –getParameter() –getParameterValues() l Invoking the Servlet

29 More Servlet Examples l Vacation Example Vacation Example –See demonstration. l Quiz #1 Quiz #1 –See demonstration.

30 Java IDE’s & Servlets l IDE –Integrated Development Environment l Examples –Borland Jbuilder –IBM Visualage l Servlet Aids –Automatic Code Generation –Test Environment

31 Servlet-Enabled Web Servers l Apache with Tomcat l iPlanet l IBM Websphere l Other See for a more comprehensive list.

32 The Servlet Specification Created from a Sun- sponsored open process to develop and revise Java TM technology specifications l Newest servlet specification includes: –Concept of a Web Application (Servlets, JSP, HTML, Classes, other resources) with conventions for the directory structure –Web Application Archive (WAR) files –Filtering l Allows on-the-fly transformations of HTTP content (request or response); for example, to transform XML content –Other

33 Servlet Basics: A Closer Look l The ServletRequest Interface –Defines an object used to encapsulate information about the client’s request. –Includes information about parameter name/value pairs. l The ServletResponse Interface –Defines an object for sending MIME data back to the client from the servlet’s service() method.

34 HttpServletRequest Interface l A Few Methods –getAuthType() –getCookies() –getDateHeader() –getHeader() –getHeaderNames() –getIntHeader() –getMethod() –getPathInfo() –getPathTranslated() –getQueryString() –getRemoteUser() –getRequestedSessionId() –getRequestedURI() –getServletPath() –getSession()

35 l Static Final Variables –For example, SC_OK represents a status code of 200, and SC_NOT_FOUND represents a status code of 404. HttpServletResponse Interface l A Few Methods –addCookie() –encodeURL() –sendError() –sendRedirect() –setDateHeader() –setHeader() –setStatus()

36 Servlet Tips l Place costly functions in init(). Let doGet() call doPost() or vice versa: public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } l Be careful with multiple threads; SingleThreadModel may be necessary.

37 JDBC l Java Database Connectivity l Relational Databases l SQL Refresher –CREATE –INSERT –UPDATE –DELETE –SELECT

38 JDBC Features l Easy Object to Relational Mapping l Database Independence l Distributed Computing l A Java API for: –Opening a connection to a database –Executing a SQL statement –Processing the results –Closing the connection to the database

39 Basic JDBC Methods l Establishing a connection with getConnection() l Creating SQL Statements –CreateStatement() l executeQuery() l executeUpdate() l execute() l Getting the results with ResultSet l SQLExceptions

40 A Simple Servlet with JDBC l HowFar –See demonstration.

41 Session Tracking l HTTP is stateless, so no inherent way to determine that a series of requests all come from the same client. l Think about a shopping cart application example.

42 Possible Solutions l Traditional CGI Techniques –User-authorization –Hidden form fields –URL rewriting –Persistent cookies l Servlet API Built-in Support

43 Session-tracking API support l Uses persistent cookies where possible and reverts to URL rewriting when cookies do not work. l Each user is associated with a javax.servlet.http.HttpSession object. Information about the user can be stored in the session object, e.g. shopping cart contents or database connection.

44 Session Tracking Example l Quiz #2 Quiz #2 –See demonstration.

45 Java Server Pages l Supports embedded scripting and tags. These co-exist with HTML. l Provide a means for separating content and presentation. l Reuse and code sharing are enhanced when JSP is used with JavaBeans. l Steps of a JSP Request –Client requests a JSP page. –The JSP engine compiles the JSP into a servlet. –The generated servlet is compiled and loaded. –The compiled services the request and sends a response back to the client. from Pure JSP by Goodwill

46 JSP Directives l Page –A global definition that is sent to the JSP engine Ex: l Include –Allows the substitution of text or code Ex: l Declarations –Contains Java variables and methods called from an expression block. Syntax: l Scriptlets –Used to embed small code blocks. l Comments –Two forms: l Expressions –Scriptlet fragments whose results can be converted to String objects.

47 HowFar as a JSP file l HowFar.jsp HowFar.jsp –See demonstration.

48 JSP and JavaBeans l Supports the creation of dynamic content l JavaBeans –Reusable software components that can be manipulated visually in a builder tool –Minimum Requirements: l Supports JDK 1.1 and later Serialization Model l Uses Get/Set accessors to expose its properties l Tags –jsp:useBean l Declares the JavaBean object that you want to use within the JSP –jsp:getProperty l Inserts the String type of the object into the output stream –jsp:setProperty l Sets properties of the Bean

49 HowFar2 as a JSP file with a JavaBean l HowFar2.jsp HowFar2.jsp –See demonstration.

50 Practical Applications l Useful for serving as the “glue” to connect heterogeneous information systems that require a web interface. l XML makes this scenario even more attractive. l University of Mississippi IT Applications –E-forms l Requires data from Cold Fusion/SQL Server and SAP via Java Connector –Web-to-SAP l Business Connector l Java Connector

51 Servlet Resources l See accompanying handouts.

52 For More Information Dawn Wilkins Department of Computer Science University of Mississippi (662) 915-7309 Kathy Gates Office of Information Technology University of Mississippi (662) 915-7206

Download ppt "Java Servlets: A QuickStart for CS Educators Dawn Wilkins and Kathy Gates The University of Mississippi."

Similar presentations

Ads by Google