Outline. Lecture 9: Java Servlet and JSP. Servlet API. HTTP Servlet Basics



Similar documents
Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

ACM Crossroads Student Magazine The ACM's First Electronic Publication

2.8. Session management

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, Java Servlets

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

11.1 Web Server Operation

Introduction to J2EE Web Technologies

Java 2 Web Developer Certification Study Guide Natalie Levi

Web Container Components Servlet JSP Tag Libraries

Outline. CS 112 Introduction to Programming. Recap: HTML/CSS/Javascript. Admin. Outline

Java Servlet Tutorial. Java Servlet Tutorial

Ch-03 Web Applications

2. Follow the installation directions and install the server on ccc

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Session Tracking Customized Java EE Training:

Agenda. Summary of Previous Session. Application Servers G Session 3 - Main Theme Page-Based Application Servers (Part II)

INTRODUCTION TO WEB TECHNOLOGY

Managing Data on the World Wide-Web

Web. Services. Web Technologies. Today. Web. Technologies. Internet WWW. Protocols TCP/IP HTTP. Apache. Next Time. Lecture # Apache.

chapter 3Chapter 3 Advanced Servlet Techniques Servlets and Web Sessions Store Information in a Session In This Chapter

Pure server-side Web Applications with Java, JSP. Application Servers: the Essential Tool of Server-Side Programming. Install and Check Tomcat

Application Security

CHAPTER 5. Java Servlets

BAPI. Business Application Programming Interface. Compiled by Y R Nagesh 1

Principles and Techniques of DBMS 5 Servlet

Controlling Web Application Behavior

Server-Side Web Development JSP. Today. Web Servers. Static HTML Directives. Actions Comments Tag Libraries Implicit Objects. Apache.

Creating Java EE Applications and Servlets with IntelliJ IDEA

In this chapter the concept of Servlets, not the entire Servlet specification, is

COMP9321 Web Applications Engineering: Java Servlets

INSIDE SERVLETS. Server-Side Programming for the Java Platform. An Imprint of Addison Wesley Longman, Inc.

CIS 455/555: Internet and Web Systems

Web Application Programmer's Guide

Servlet 3.0. Alexis Moussine-Pouchkine. mercredi 13 avril 2011

Web Applications. For live Java training, please see training courses at

An introduction to web programming with Java

Please send your comments to:

Web Programming II JSP (Java Server Pages) ASP request processing. The Problem. The Problem. Enterprise Application Development using J2EE

Class Focus: Web Applications that provide Dynamic Content

SSC - Web applications and development Introduction and Java Servlet (II)

PA165 - Lab session - Web Presentation Layer

Glassfish, JAVA EE, Servlets, JSP, EJB

The HTTP Plug-in. Table of contents

Java Servlet 3.0. Rajiv Mordani Spec Lead

Exam Prep. Sun Certified Web Component Developer (SCWCD) for J2EE Platform

Complete Java Web Development

Servlet and JSP Filters

Apache Jakarta Tomcat

CHAPTER 9: SERVLET AND JSP FILTERS

Web Programming with Java Servlets

Java Servlet Specification Version 2.3

Arjun V. Bala Page 20

Building Web Applications, Servlets, JSP and JDBC

Course Number: IAC-SOFT-WDAD Web Design and Application Development

Volume 1: Core Technologies Marty Hall Larry Brown. An Overview of Servlet & JSP Technology

An Overview of Servlet & JSP Technology

CSC 551: Web Programming. Spring 2004

CS506 Web Design and Development Solved Online Quiz No. 01

Java Server Pages and Java Beans

Course Name: Course in JSP Course Code: P5

APM for Java. AppDynamics Pro Documentation. Version 4.0.x. Page 1

JSP Java Server Pages

In this chapter, we lay the foundation for all our further discussions. We start

Java Server Pages (JSP)

JWIG Yet Another Framework for Maintainable and Secure Web Applications

How to use JavaMail to send

Java and Web. WebWork

WIRIS quizzes web services Getting started with PHP and Java

DTS Web Developers Guide

Mastering Tomcat Development

Oracle WebLogic Server

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Core Java+ J2EE+Struts+Hibernate+Spring

Developing XML Solutions with JavaServer Pages Technology

Manual. Programmer's Guide for Java API

Università degli Studi di Napoli Federico II. Corsi di Laurea Specialistica in Ingegneria Informatica ed Ingegneria delle Telecomunicazioni

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

The Server.xml File. Containers APPENDIX A. The Server Container

Accessing Data with ADOBE FLEX 4.6

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Piotr Nowicki's Homepage. Java EE 6 SCWCD Mock Exam. "Simplicity is the ultimate sophistication." Important!

Web Applications. Originals of Slides and Source Code for Examples:

Szervletek. ANTAL Margit. Sapientia - EMTE, Pannon Forrás,,Egységes erdélyi felnőttképzés a

CONTROLLING WEB APPLICATION BEHAVIOR WITH

Japan Communication India Skill Development Center

Building Java Servlets with Oracle JDeveloper

Anders Møller & Michael I. Schwartzbach 2006 Addison-Wesley

Tomcat 5 New Features

Japan Communication India Skill Development Center

Hello World RESTful web service tutorial

Transcription:

Lecture 9: Java Servlet and JSP Wendy Liu CSC309F Fall 2007 Outline HTTP Servlet Basics Servlet Lifecycle Request and Response Session Management JavaServer Pages (JSP) 1 2 HTTP Servlet Basics Current API 2.5: https://glassfish.dev.java.net/nonav/javaee5/api/index.html Servlet API javax.servlet Support generic, protocol-independent servlets Servlet (interface) GenericServlet (class) service() ServletRequest and ServletResponse Provide access to generic server requests and responses javax.servlet.http Extended to add HTTP-specific functionality HttpServlet (extends GenericServlet ) doget() dopost() HttpServletRequest and HttpServletResponse Provide access to HTTP requests and responses 3 4 1

User-defined Servlets Inherit from HttpServlet Override doget() and dopost() To handle GET and POST requests Have no main() method doget() and dopost() protected void doget( HttpServletRequest req, HttpServletResponse resp) protected void dopost( HttpServletRequest req, HttpServletResponse resp) 5 6 Hello World Handling GET and POST Request import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); out.println("<html>"); out.println("<head><title>hello world</title></head>"); out.println("<body>"); out.println("<big>hello world</big>"); out.println("</body></html>"); public void dopost(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { doget(req, res); 7 Adopted from Java Servlet Programming, Jason Hunter, 2001 8 2

Client End-to-end Process Makes a request to a servlet Web Server Receives the request Identifies the request as a servlet request Passes the request to the servlet container Servlet Container Locates the servlet Passes the request to the servlet Servlet Executes in the current thread The servlet can store/retrieve objects from the container Output is sent back to the requesting browser via the web server Servlet continues to be available in the servlet container Servlet Lifecycle 9 10 Servlet Container Provide web server with servlet support Execute and manage servlets E.g., Tomcat Must conform to the following lifecycle contract Create and initialize the servlet Handle zero or more service calls from clients Destroy the servlet and then garbage collect it Three types Standalone container Add-on container Embeddable container Usually execute all servlets in a single JVM Loading Servlet Server calls servlet s init() method After the server constructs the servlet instance and before the servlet handles any requests init() Servlet initialization is defined May be called When the server starts When the servlet is first requested, just before the service() method is invoked At the request of the server administrator 11 12 3

Removing Servlet Server calls the destroy() method After the servlet has been taken out of service and all pending requests to the servlet have completed or timed out destroy() Resources acquired should be freed up A chance to write out its unsaved cached info Last step before being garbage collected Servlet Instance Persistence Servlets persist between requests as object instances When servle it loaded, the server creates a single instance The single instance handles every request made of the servlet Improves performance in three ways Keeps memory footprint small Eliminates the object creation overhead Enables persistence May have already loaded required resources 13 14 Request for Servlet1 Request for Setvlet2 Request for Servlet1 Servlet Thread Model Servlet-Based Web Server Main Process JVM Thread Servlet1 Thread Servlet2 Thread import java.io.*; import javax.servlet.*; import javax.servlet.http.*; A Simple Counter public class SimpleCounter extends HttpServlet { int count = 0; public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/plain"); PrintWriter out = res.getwriter(); count++; out.println("since loading, this servlet has been accessed " + count + " times."); 15 16 4

Multi-threading Each client request is another thread that calls the servlet via the service(), doget(), and dopost() methods Thread Safety Non-local variables are not thread-safe Variables declared within a class but outside any specific method May cause data corruption and inconsistencies In the example count ++ // thread 1 count ++ // thread 2 out.println // thread 1 out.println // thread 2 Local variables are thread-safe Variables declared within a method 17 18 Synchronization Place code within a synchronization block Guaranteed not to be executed concurrently by another thread Before any thread begins to execute synchronized code A monitor (lock) must be obtained on a specified object instance If one thread already has the monitor, all other threads must wait Use only when necessary Reduced parallelism Increased overhead to obtain the monitor 19 Simple Counter Has Four Options Option 1 public synchronized void doget(httpservletrequest req, HttpServletResponse res) Option 2 PrintWriter out = res.getwriter(); synchronized(this) { count++; out.println("since loading, this servlet has been accessed " + count + " times."); Option 3 (the best) PrintWriter out = res.getwriter(); int local_count; synchronized(this) { local_count = ++count; out.println("since loading, this servlet has been accessed " + count + " times."); Option 4 Don t care; I can live with the inconsistency 20 5

HttpServletRequest Request and Response https://glassfish.dev.java.net/nonav/javaee5/api/index.html 21 Encapsulate all information from the client request HTTP request header and request body Methods to retrieve data Inherited from ServletRequest getparameter() getparameternames() getparametervalues() getinputstream() getreader() 22 HttpServletResponse Encapsulate all data to be returned to client HTTP response header and response body (optional) Set HTTP response header Primitive manipulation setstatus(), setheader(), addheader() Convenience methods setcontenttype(), sendredirect(), senderror() Set HTTP response Body Obtain a PrintWriter or ServletOutputStream to return data to the client getwriter(), getoutputstream() GET GET vs. POST All form parameters are embedded in the URL If you reload, or bookmark and return, the query will get executed a second time with the same parameters Bad if page is a credit card order confirmation 2 charges! Use GET to obtain info POST Form parameters are included in the request body On reload Browser will ask if it should re-post On bookmark and return Query will proceed with no parameters Use POST to change state 23 24 6

Session Management Session Management Provide state between HTTP requests Client-side Cookies Hidden variables URL rewriting User authentication getremoteuser() Provided by HttpServletRequest Server-side Servlet s built-in session tracking 25 26 Persistent Cookies Stored at the browser As name=value pairs Browsers limit the size of cookies Users can refuse to accept them Attached to subsequent requests to the same server Servlets can create cookies Included in the HTTP response header Adding a Cookie Cookie MaxAge Cookie(String name, Given in seconds String value) If negative, cookie persists until browser exists setmaxage(int expiry) Domain setdomain(string pattern) Return cookie to servers matching setpath(string uri) the specified domain pattern setsecure(boolean flag) By default, only return to the server that sent it HttpServletResponse Path addcoockie(cookie cookie) Where the client should return the cookie Visible to all the pages in the specified directory and subdirectory Secure flag Send cookie only on secure channels 27 28 7

HttpServletRequest Retrieving Cookies public Cookie[] getcookies() Cookie getname() getvalue() getdomain() getpath() getsecure() Servlet s Built-in Session Tracking Session tracking API Devoted to servlet session tracking Most servers support session tracking Through the use of persistent cookies Able to revert to URL rewriting when cookies fail Servlet uses the token to fetch session state Session objects are maintained in memory Some servers allow them to be written to file system or database as memory fills up or when server shuts down Items in the session need to be serializable 29 30 Session Tracking Basics Every user of a site is associated with a javax.servlet.http.httpsession object To store and retrieve information about the user Retrieve the current HttpSession object public HttpSession HttpServletRequest.getSession() Creates one if no valid session found Session Attributes To add data to a session object public void HttpSession.setAttribute(String name, Object value) To retrieve an object from a session public Object HttpSession.getAttribute(String name) To get the names of all objects in a session public Enumeration HttpSession.getAttributeNames() To remove an object from a session public void HttpSession.removeAttribute(String name) Deprecated methods since API 2.2 (do not use) putvalue(), getvalue(); getvaluenames(); removevalue() 31 32 8

Session Lifecycle Sessions do not last forever Expire automatically due to inactivity Default 30 min Explicitly invalidated by servlet When session expires (or is invalidated) The HttpSession object and its data values are removed HttpSession Lifecycle Methods boolean isnew() Returns true if the client does not yet know about the session or if the client chooses not to join the session void invalidate() Invalidates this session then unbinds any objects bound to it long getcreationtime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT long getlastaccessedtime() Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request 33 34 Setting Session Timeout Setting default session timeout Deployment descriptor, web.xml Applies to all sessions created in the given web application <session-config> <session-timeout> 30 <! minutes --> </session-timeout> </session-config> Configured individually public void HttpSession.setMaxInactiveInterval(int secs) public int HttpSession.getMaxInactiveInterval() Terminating a session session.invalidate() Deletes session related attributes form server Removes cookie from client 35 ServletContext Reference to the web application in which servlets execute One ServletContext for each app on the server Allow servlets to access server information ServletContext GenericServlet.getServletContex() Using ServletContext, servlets can Log events Obtain URL references to resources Access to initialization parameters (in web.xml) Share attributes with other servlets in the context Not thread safe 36 9

Simple JSP Example JavaServer Pages (JSP) Currently JSP 2.1 http://java.sun.com/products/jsp/syntax/2.0/syntaxref20.html 37 <html> <head> <title>jsp Example</title> </head> <body> <h1>jsp Example</h1> <hr/> <p> <% out.println("hello " + request.getparameter("name")); %> <%= "Hello again, " + request.getparameter("name") + "!"%> </p> </body> </html> 38 JavaServer Pages Behind the Scene Embed Java servlet code in HTML pages Purposes Enable the separation of dynamic and static content Enable the authoring of Web pages that create dynamic content easily but with maximum power and flexibility Server automatically creates, compiles, loads, and runs a special servlet for the page request response Web Server.jsp file <html> <head> </head> <body> <% %> </body> </html> Java Compiler Servlet 39 40 10

Elements in JSP (1) XHTML Scriptlet <% servlet code for service() %> <%-- comment --%> Expressions and declarations <%= expression %> Eliminates the clutter of out.println() <%! code for outside of service() %> Declare static or instance variables, and define new methods Directives Control different aspects of the workhorse servlet <%@ directivename attribname= attribvalue %> <%@ page contenttype= text/plain %> 41 Elements in JSP (2) Include directive (or raw include ) Included directly as if it were typed; occurs at translation time <%@ include file = /header.html %> Action tags <jsp:include> Occurs at request time; includes the output of the dynamic resource <jsp:include page= pathtodynamicresource flush= true /> Add parameters to request object passed to <jsp:include> <jsp:param name= User value= John /> Must be enclosed by a pair of <jsp:include> tags Forward a request Occurs at request time <jsp:forward page= pathtodynamicresource /> 42 Elements in JSP (3) Support for custom tag libraries Let a JSP page contain XML tags that cause specific Java code to be executed <%@ taglib prefix= c uri= http://java.sun.com/jsp/jstl/core %> JSP Standard Tag Library (JSTL) <c:out value= ${param.address /> <%@ taglib prefix= struts uri= /WEB-INF/struts.tld %> Apache Struts Library Installation is required for custom library use <struts:property name= cookie property= name /> Active Server Pages (ASP) Microsoft-specific technology Similar to JSP Use VisualBasic instead of Java Can access a vast array of COM and DCOM objects 43 44 11