Servlets and JSP (Java Server Pages)

Similar documents
Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Servlet Fudamentals. Celsina Bignoli

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

JAVA SERVLET. Server-side Programming INTRODUCTION

Module 4: SERVLET and JSP

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

SERVLETS INTERVIEW QUESTIONS

Session 8. Introduction to Servlets. Semester Project

Advanced Web Technology

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Session 9. Introduction to Servlets. Lecture Objectives

AJP. CHAPTER 5: SERVLET -20 marks

Unit 4 - Servlet. Servlet. Advantage of Servlet

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

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

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

Advanced Internet Technology Lab # 4 Servlets

Servlet Basics. Agenda

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Web based Applications, Tomcat and Servlets - Lab 3 -

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

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

Java Servlets. Preparing your System

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

UNIT-V. Web Servers: Tomcat Server Installation:

Chapter 10 Servlets and Java Server Pages

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

UNIT-VI. HttpServletResponse It extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

Using Java servlets to generate dynamic WAP content

JAVA SERVLET. Server-side Programming PROGRAMMING

Unit-4: Servlet Sessions:

********************************************************************

Servlets. An extension of a web server runs inside a servlet container

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

Unit 5 JSP (Java Server Pages)

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

Introduction to JSP and Servlets Training 5-days

Table of Contents. Introduction... xxi

HTTP and the Dynamic Web

CSC309: Introduction to Web Programming. Lecture 10

Questions and Answers

COMP9321 Web Application Engineering

CIS 455 / 555: Internet and Web Systems

Servlets Basic Operations

COMP9321 Web Application Engineering

How does the Web work? HTTP and the Dynamic Web. Naming and URLs. In Action. HTTP in a Nutshell. Protocols. The canonical example in your Web browser

Java E-Commerce Martin Cooke,

Module 3 Web Component

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

3 The Servlet Life Cycle

JavaServer Pages (JSP)

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets

Handout 31 Web Design & Development

The Structure and Components of

Session 9. Data Sharing & Cookies. Reading & Reference. Reading. Reference http state management. Session 9 Data Sharing

CS506 Web Design & Development Final Term Solved MCQs with Reference

The Servlet Life Cycle

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil

Generating the Server Response: HTTP Response Headers

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

Lab session Google Application Engine - GAE. Navid Nikaein

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

Introduction to Web applications with Java Technology 3- Servlets

Java4570: Session Tracking using Cookies *

Introdução a Servlets

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return:

CSC309: Introduction to Web Programming. Lecture 8

SNS COLLEGE OF ENGINEERING, Coimbatore

In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter.

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

Component Based Software Engineering

SERVLET AND JSP FILTERS

Introduction to Servlets. After which you will doget it

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction. This course Software Architecture with Java will discuss the following topics:

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

ADVANCED JAVA COURSE CURRICULUM

Fast Track to Java EE 5 with Servlets, JSP & JDBC

JAVA SERVLETS INTRODUCTION SERVLETS SHRI GURU RAM RAI INSTITUTE OF TECHNOLOGY & SCIENCE, DEHRADUN

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Chapter 17. Web-Application Development

1. Introduction. 2. Life Cycle Why JSP is preferred over Servlets? 2.1. Translation. Java Server Pages (JSP) THETOPPERSWAY.

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, JSPs 1

Oracle EXAM - 1Z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Buy Full Product

Session E118011: Best practices for developing WebSphere based applications

JSP. Common patterns

1.264 Lecture 15. Web development environments: JavaScript Java applets, servlets Java (J2EE) Active Server Pages

Fast Track to Java EE

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Transcription:

Servlets and JSP (Java Server Pages) XML HTTP CGI Web usability Last Week Nan Niu (nn@cs.toronto.edu) CSC309 -- Fall 2008 2 Servlets Generic Java2EE API for invoking and connecting to mini-servers (lightweight, short-lived, server-side interactions) Mostly HTTPServlets Generate HTTP responses (as for CGI) Embedded via <servlet> tag into HTML pages for server-side includes Servlet code snippets can be embedded directly into HTML pages: JSP = Java Server Pages Competitor: Microsoft ASP = Active Server Pages 3 Servlet Architecture Clients: browsers, e.g., IE, Netscape Web server: e.g., Apache, IIS CGI Protocol: Specifying what a request/response looks like Servlet container: Running JVM, hooked into the Web server, loads and maintains servlets, session info, object store Servlet: A Java class used to handle a specific request. 4 Servlet Interaction Client Makes a request by specifying a URL + additional info. Basically a method call, the method and arguments Web Server Receives the request Identifies the request as a servlet request Passes the request to the servlet container Servlet Container Locates the servlet (Java code, loaded and running in the container JVM) Feeds the request parameters to the servlet Servlet Executes in a separate thread The servlet can store/retrieve objects (possibly session scoped) from the servlet container Output is sent back to the requesting browser CGI1 CGI2 CGI1 CGI vs. Servlet CGI-Based Web Server Main Process Child Process for CGI1 Child Process for CGI2 Child Process for CGI1 Servlet continues to be available in the container 5 6 1

Setvlet2 CGI vs. Servlet Java Servlet-Based Web Server Main Process JVM Servlet2 7 Servlets vs. CGI Servlets Faster than CGI scripts because a different process model is used Also Java just-in-time compilation increases performance Process model allows resource sharing (e.g., database connection sharing) Container is always available Has all the advantages of Java programming language, including ease of development and platform independence Same language for both client- and server-side development Can access the large set of APIs for the Java platform Has access to CGI support through the servlet API Has session awareness, ability to store and retrieve scoped objects from servlet container 8 Servlet API (javax.servlet) Servlet Container Servlet Interface HttpServletRequest HttpServletResponse ServletContext Servlet Container Contains and manages servlets through their lifecycle Provides the network services over which requests and responses are sent Decodes requests Formats responses 9 10 Servlet Interface Central abstraction of the servlet API All servlets either implement this interface, or extend a class that implements this interface GenericServlet and HttpServlet are two classes in the servlet API that implement the Servlet interface User-defined Servlets Inherit from HttpServlet Override doget() and dopost() Have no main() method 11 12 2

doget() and dopost() protected void doget( HttpServletRequest req, HttpServletResponse resp) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; Hello World public class HelloWorld extends HttpServlet { public void doget(httpservletrequest req, HttpServletResposse resp) throws ServletException, IOException { resp.setcontenttype( text/html ); PrintWriter out = resp.getwriter(); out.println( <html> ); out.println( <head><title>hello world</title></head> ); protected void dopost( HttpServletRequest req, HttpServletResponse resp) 13 out.println( <body><h2>hello World</h2></body> ); out.println( </html> ); public void dopost(httpservletrequest req, HttpServletResposse resp) throws ServletException, IOException { doget(req, resp); 14 Handling GET and POST Request Servlet API (javax.servlet) Servlet Container Servlet Interface HttpServletRequest HttpServletResponse ServletContext Servlet Lifecycle 15 16 Servlet Lifecycle Inherited from GenericServlet init() destroy() Defined by HttpServlet doget() dopost() 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 17 18 3

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 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 19 20 Servlet Instance Persistence Servlets persist between requests as object instances When the servlet is 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 Setvlet2 Servlet Model Java Servlet-Based Web Server Main Process JVM Servlet2 21 22 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; A Simple Counter Multi-threading public class SimpleCounter extends HttpServlet { int count = 0; public void doget(httpservletrequest req, HttpServletResposse resp) throws ServletException, IOException { resp.setcontenttype( text/plain ); PrintWriter out = resp.getwriter(); count++; out.println( Since loading, this servlet has been accessed + count + times. ); 23 Each client request is another thread that calls the servlet via service(), doget(), and dopost() methods 24 4

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 25 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 Reduce parallelism Increased overhead to obtain the monitor 26 SimpleCounter Has Four Options Option 1 Don t care; can live with inconsistency Option 2 public synchronized void doget( ) Option 3 PrintWriter out = resp.getwriter(); synchronized(this) { count++; out.println( Since loading, this servlet has been accessed + count + times. ); Option 4 (the best) PrintWriter out = resp.getwriter(); int local_count; synchronized(this) { local_count = ++count; out.println( Since loading, this servlet has been accessed + local_count + times. ); 27 Servlet API (javax.servlet) Servlet Container Servlet Interface HttpServletRequest HttpServletResponse ServletContext Servlet Lifecycle 28 HttpServletRequest 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() HttpServletResponse Encapsulate all data to be returned to client HTTP response header and response body 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() 29 30 5

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.getServletContext() 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 31 Session Management HTTP is stateless: No memory of browser s state Preserving state between browser and Web server interaction Probably determined by previous forms filled in and pages viewed Kept at the browser or/and at the Web server Example: User authentication: post questions only after the user is logged in Session recognition: don t want to require a user to log in at every page 32 Session Management (Cont d) At client Cookies Hidden variables URL rewriting At server Servlet s built-in session tracking Database, file system, etc. 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 33 34 Cookie Cookie(String name, String value) setmaxage(int expiry) Adding a Cookie setdomain(string pattern) setpath(string uri) setsecure(boolean flag) HttpServletResponse addcookie(cookie cookie) Path MaxAge Given in seconds If negative, cookie persists until browser exists Domain Return cookie to servers matching the specified domain pattern By default, only return to the server that sent it Where the client should return the cookie Visible to all the pages in the specified (sub-)directory Secure flag Send cookies only on secure Retrieving Cookie Values HttpServletRequest public Cookies[] getcookies() Cookie getname() getvalue() getdomain() getpath() getsecure() channels 35 36 6

Hidden Variables Supported by all browsers Requires all hidden variables to appear in all forms <input type= hidden name= userid value= 309 /> State is sent inside each Web page For form-based applications only Following hyperlinks may cause a loss of state Current submitted page represents current state independent of what was done previously URL Rewriting Rewrite URLs so that they include state variables Each URL is now a CGI-get request Supported by all browsers Requires all URLs contain all state information (long URLs) Current submitted page represents current state independent of what was done previously 37 38 Servlet s Built-in Session Tracking Session tracking API Devoted to servlet session tracking Most servers support session tracking Through the use of cookies Able to revert to URL rewriting when cookies fail Servlet uses the token to fresh 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 39 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 HtttpServletRequest.getSession() Create one if no valid session found 40 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) 41 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 42 7

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 Jan 1, 1970 GMT long getlastaccessedtime() Returns the last time the client sent a request associated with this session, and marked by the time the container received the request Setting Session Timeout Setting default session timeout Deploy 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 from server Removes cookie from client 43 44 JSP (Java Server Pages) Servlets disadvantage A little Java in a whole lot of HTML Java Server Pages Embed Java servlet code in HTML pages Deployed in textual form (as opposed to byte code) Translated into a servlet on the fly Server automatically creates, compiles, loads, and runs a special servlet for the page Behind the Scene 45 46 Simple JSP Example JSP Lifecycle <html> <head> <title>jsp Example</title> </head> <body> <h1>jsp Example</h1> <hr> <% out.println("hello " + request.getparameter("name")); %> <p> <%= "Hello again " + request.getparameter("name") + "!"%> </body> </html> 47 48 8

ASP (Active Server Pages) Microsoft-specific technology Similar to JSP Use VisualBasic instead of Java Can access a vast variety of COM and DCOM objects 49 9