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

Similar documents
Jeff Offutt. SWE 432 Design and Implementation of Software for the Web. Web Applications

Servlet Fudamentals. Celsina Bignoli

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?

Java Servlets. Preparing your System

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

JAVA SERVLET. Server-side Programming INTRODUCTION

Session 8. Introduction to Servlets. Semester Project

Servlets and JSP (Java Server Pages)

Advanced Web Technology

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

Advanced Internet Technology Lab # 4 Servlets

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

UNIT-V. Web Servers: Tomcat Server Installation:

Servlet Basics. Agenda

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

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

Module 4: SERVLET and JSP

Servlets Basic Operations

Web based Applications, Tomcat and Servlets - Lab 3 -

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

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

Chapter 10 Servlets and Java Server Pages

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

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

ICOM 5016 Database Systems. Database Users. User Interfaces and Tools. Chapter 8: Application Design and Development.

Using Java servlets to generate dynamic WAP content

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

AJP. CHAPTER 5: SERVLET -20 marks

Servlets by Example. Joe Howse 7 June 2011

SERVLETS INTERVIEW QUESTIONS

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

CSC309: Introduction to Web Programming. Lecture 8

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

Questions and Answers

The Servlet Life Cycle

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

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

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

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

ServletConfig Interface

Unit 5 JSP (Java Server Pages)

Session 9. Introduction to Servlets. Lecture Objectives

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

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

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

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet.

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

COMP9321 Web Application Engineering

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

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

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Distributed Systems 1

3. The pool should be added now. You can start Weblogic server and see if there s any error message.

Software Elements of Electronic Business Sites

First Servlets. Chapter. Topics in This Chapter

Java Servlet Specification, v2.2

Unit 4 - Servlet. Servlet. Advantage of Servlet

Introdução a Servlets

Introduction to Servlets. After which you will doget it

INTERNET PROGRAMMING TEST-3 SCHEME OF EVALUATION 1.A 3 LIFE CYCLE METHODS - 3M 1.B HTML FORM CREATION - 2 M

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

COMP9321 Web Application Engineering

TUTORIAL QUESTION BANK

CSC309: Introduction to Web Programming. Lecture 10

HTTP and the Dynamic Web

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

Lecture 9a: Sessions and Cookies

3. WWW and HTTP. Fig.3.1 Architecture of WWW

Java E-Commerce Martin Cooke,

Ch04 JavaServer Pages (JSP)

Chapter 10 Web-based Information Systems

Handout 31 Web Design & Development

An excellent explanation of how web browsers work:

Servlets Pearson Education, Inc. All rights reserved.

Module 3 Web Component

CIS 455 / 555: Internet and Web Systems

Introduction to JSP and Servlets Training 5-days

3 The Servlet Life Cycle

Table of Contents. Introduction... xxi

AN OVERVIEW OF SERVLET AND JSP TECHNOLOGY

Component Based Software Engineering

LearningPatterns, Inc. Courseware Student Guide

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

INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad

Servlet. 1.1 Web. 1.2 Servlet. HTML CGI Common Gateway Interface Web CGI CGI. Java Applet JavaScript Web. Java CGI Servlet. Java. Apache Tomcat Jetty

CS506 Web Design & Development Final Term Solved MCQs with Reference

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

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

CHAPTER 2: A FAST INTRODUCTION TO BASIC SERVLET PROGRAMMING

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

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

J2EE Web Development 13/1/ Application Servers. Application Servers. Agenda. In the beginning, there was darkness and cold.

Java Server Page (JSP)

Chapter 29 Servlets: Bonus for Java Developers 1041

UNIT - III. Every element in a document tree refers to a Node object. Some nodes of the tree are

Fast Track to Java EE

5/11/2009. Better to light a candle than to curse the darkness. Case Study: Reconnaissance Leaks & Corporate Assets

13. Databases on the Web

Transcription:

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

Web Applications A web application uses enabling technologies to 1. make web site contents dynamic 2. allow users of the system to implement business logic on the server Web applications allow users to affect state on the server Search engines, though complicated, do not really affect the server s state An enabling technology is a mechanism that makes web pages interactive and responsive to user input 8/24/2008 Offutt 2

Traditional Computing Use A user is working with software on her computer 8/24/2008 Offutt 3

Client Server Computing A user is working with software or data on a separate computer called a server Client requests data Client PC Server returns data Compute or DB Server 8/24/2008 Offutt 4

Web Applications Many users work with servers and databases that can be reached through the Internet with the HyperText Transfer Protocol SQL Records HTML HTTP Request Internet Client Browser Client Browser Client Browser 8/24/2008 Offutt 5

N-Tier Web Architecture Large web applications run on many computers that have to coordinate with each other. Amazon and Netflix have thousands of servers. network middleware middleware Client Web Servers Application Servers DB Servers Browser Javascripts HTML PHP ASP JSP, etc Java C# 8/24/2008 Offutt 6

How the Software Works Name : George Age : 23 Email : Browser <html> <body> <form method=post action=idprogram idprogram Name=idForm idform> Name: : <input type=text name=username username> Age: : <input type=text name=age age> Email: : <input type=text name=email Email> </form> </body> </html> to server HTML out.println ( <html>\n ); out.println ( <body>\n ); out.println ( <p>your name is ); out.println (req.getparameter (username username)); out.println ( \n<p>your age is ); out.println (req.getparameter (age age)); out.println ( \n<p>your email is ); out.println (req.getparameter (Email Email)); out.println ( </body> ); out.println ( </html> ); Java Servlet to client Your name is George Your age is 23 Your email is Browser 8/24/2008 Offutt 7

Server Side Processing HTTP Request data browser web server servlet container Client HTML HTTP Response Server 8/24/2008 Offutt 8

Session Management HTTP client server communication is connectionless as soon as the request is made and fulfilled, the connection is terminated communication is more simple and resistant to network problems But how can a server keep track of state of different clients? 1. Session: A single coherent use of the system by the same user Example: shopping carts 2. Cookies: A string of characters that a web server places on a browser s client to keep track of a session usually used as an index into a table (dictionary) on the server most dictionaries expire after a reasonable time (15 to 30 minutes) We ll come back to this later 8/24/2008 Offutt 9

Enabling Technologies - CGI CGI: Common Gateway Interface allows clients to execute applications on the server CGI applications usually reside in a special safe directory Can be written in any language; PERL is most common CGI apps typically: 1. process data 2. modify server state 3. return information (usually an HTML page) 8/24/2008 Offutt 10

Enabling Technologies Problems with CGI CGI does not automatically provide session management services Each and every execution of a CGI module requires a new process on the web server Solution: Plug-ins on the Web server 8/24/2008 Offutt 11

Enabling Technologies Web Server Plug-ins A plug-in is an extension to a web server that allows a different program to handle certain types of requests images, sound, video compiled module applications scripted page applications Plug-ins typically keep an active process as long as the web server is active 8/24/2008 Offutt 12

Enabling Technologies - Plug-ins Compiled Modules Compiled modules are executable programs that the server uses Common compiled module application plug-ins: Microsoft s Internet Server API (ISAPI) ASP Netscape Server API (NSAPI) Java servlets Compiled modules are efficient and very effective They provide clear separation of the front-end from the back-end, which aids design but complicates implementation 8/24/2008 Offutt 13

Enabling Technologies - Plug-ins Scripted Pages Scripted pages look like HTML pages that happen to process business logic Execution is server-side, not client (unlike JavaScripts) They are HTML pages that access software on the server to get and process data JSPs are compiled and run as servlets (very clean and efficient) PHP scripts are interpreted within the server 8/24/2008 Offutt 14

Enabling Technologies - Plug-ins Common scripted pages: Allaire s Cold Fusion Scripted Pages (2) Microsoft s Active Server Pages (ASP) PHP Java Server Pages (JSP) Scripted pages are generally easy to develop, and deploy They mix logic with HTML, so can be difficult to read and maintain Not effective for heavy-duty engineering 8/24/2008 Offutt 15

Servlets Servlets are small Java classes that perform a service Servlet container or engine connects to network catches requests produces responses requests are handled by objects Programmers use a servlet API 8/24/2008 Offutt 16

Servlet Container (or Engine) Servlet container is a plug-in for handling Java servlets A servlet container has five jobs: 1. Creates servlet instance 2. Calls init() 3. Calls service() whenever a request is made 4. Calls destroy() before killing servlet 5. Destroys instance Really a mini operating system 8/24/2008 Offutt 17

Servlet Container (2) When a request comes to a servlet, the servlet container does one of two things: 1. If there is no active object for the servlet, the container instantiates a new object of that class, and the object handles the request 2. If there is an active object, the container creates a Java thread to handle the request 8/24/2008 Offutt 18

Servlet Container (3) A servlet instance runs until the container decides to destroy it: When it gets destroyed is not specified by the servlet rules Most servlet containers destroy the object N minutes after the last request N is usually 15 or 30, and can be set by the system administrator 8/24/2008 Offutt 19

Servlet Container (4) What if the same servlet gets multiple requests? More than one execution thread may be running at the same time, using the same memory Client 1 Client 2 Server container servlet thread 1 servlet thread 2 Shared memory space Risky 8/24/2008 Offutt 20

Servlet Container (5) By default, there is only one instance of a servlet class per servlet definition in the servlet container Distributable : If the application is distributable, there is one instance of a servlet class per virtual machine (typically, each VM is on a different computer in the cluster) 8/24/2008 Offutt 21

Allowing Concurrency (SingleThreadModel) Container may send multiple service requests to a single instance, using Java threads Simply put, threads are Java s concurrency mechanism Thus, your service methods (doget, dopost, etc.) should be thread-safe Loosely speaking, thread-safe means that if two or more requests are operating at the same time, they will not interfere with each other. If the service methods are not thread-safe, use the SingleThreadModel 8/24/2008 Offutt 22

SingleThreadModel (2) The SingleThreadModel ensures that only one thread may execute the service() method at a time Containers may implement this in two ways: 1. Instance Pooling : A pool of several servlet instances are available that do not share memory 2. Request Serialization : Only one request is handled at a time 3. Combination : A pool is used, and if there more requests than servlets in the pool, they are serialized This is resource intensive and can be slow Better to synchronize only the statements that might interfere with each other 8/24/2008 Offutt 23

Servlet Lifecycle UML State Diagram Does not exist instantiation based on a request or at container startup Instantiated initialization release reference Unavailable initiation failed back to service in case of temporary unavailability (optional) Initialized and/or ready for requests temporary or permanent failure HTTP requests from clients end of service thread Destroyed timeout or a container shutdown Service 8/24/2008 Offutt 24

Common Servlet Containers Tomcat (installed on Hermes apps cluster) BEA s WebLogic Jrun IBM Websphere (uses Apache / Tomcat) 8/24/2008 Offutt 25

Servlet API javax.servlet primarily containers javax.servlet.http methods to service requests GenericServlet Abstract class (not all methods are implemented) HttpServlet All methods are implemented MyServlet Servlet written by a programmer 8/24/2008 Offutt 26

Generic Servlet & HTTP Servlet Servlets have five principal methods: 1. init() called when servlet starts 2. service() called to process requests 3. destroy() called before servlet process ends 4. getservletconfig() servlet can access information about servlet container 5. getservletinfo() servlet container can access info about servlet 8/24/2008 Offutt 27

Generic Servlet & HTTP Servlet (2) These methods are defined by the library classes GenericServlet and HttpServlet We write servlets by extending (inheriting from) them GenericServlet does not implement service() (it is abstract) HttpServlet extends GenericServlet with: service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 8/24/2008 Offutt 28

1. init ( ) Read configuration data Read initialization parameters (javax.servlet.servletconfig) Initialize services: Database driver Connection pool Logging service Seldom used in simple applications 8/24/2008 Offutt 29

2. service ( ) The entry point for the servlet this is the method that is called from the servlet container Called after the initialization (init ()) Primary purpose is to decide what type of request is coming in and then call the appropriate method doget () dopost () 8/24/2008 Offutt 30

Types of HTTP Requests GET POST HEAD OPTIONS DELETE PUT TRACE doget () dopost () dohead () dooptions () dodelete () doput () dotrace() same signatures as service() 8/24/2008 Offutt 31

Types of HTTP Requests (2) HttpServlet implements these methods as stubs that print error messages doget () { print ("Error, doget() not implemented"); } Programmers implement services by overriding these methods (most commonly doget() and dopost()) 8/24/2008 Offutt 32

3) destroy ( ) Called by container when the servlet instance is killed The threads from the service() method are given time to terminate before destroy() is called Can be used for clean up tasks: Un-registering a database driver Closing a connection pool Informing another application the servlet is stopping Saving state from the servlet 8/24/2008 Offutt 33

4) getservletconfig ( ) Returns a ServletConfig object, which stores information about the servlet s configuration The ServletConfig object was passed into init() 8/24/2008 Offutt 34

5) getservletinfo ( ) Returns a String object that stores information about the servlet: Author Creation date Description Usage This string should be formatted for human readability 8/24/2008 Offutt 35

Simple Servlet Example import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class JOHello extends HttpServlet { public void doget (HttpServletRequest req, HttpServletResponse res) throws servletexception, IOException { res.setcontenttype ( text/html ); PrintWriter out = res.getwriter (); out.println ( <HTML> ); 8/24/2008 Offutt 36

Simple Servlet (2) out.println ( <HEAD> ); out.println ( <TITLE>Servlet example</title> ); out.println ( </HEAD> ); out.println ( <BODY> ); out.println ( <P>My first servlet. ); out.println ( </BODY> ); out.println ( </HTML> ); out.close (); } // end doget() } // end JOHello http://apps-swe432.ite.gmu.edu:8080/swe432/servlet/offutt.hello 8/24/2008 Offutt 37

Servlet Parameters requests Parameters are conveniently stored in objects String req.getparameter (String KEY) Returns value of field with the name = KEY String[ ] req.getparametervalues (String KEY) Returns all values of KEY (eg, checkboxes) Enumeration req.getparameternames () Returns an Enumeration object with a list of all parameter names 8/24/2008 Offutt 38

Servlet Output responses Standard output is sent directly back to the client browser res.setcontenttype (String type) text/html is an HTML page PrintWriter res.getwriter() Use print() and println() to write HTML to browser 8/24/2008 Offutt 39

Servlet Performance Some servlets will run a lot Servlets run as lightweight threads, so are fast The network speeds usually dominate, but: avoid concatenation ( + ) out.flush() Sends current output to user s screen while servlet continues processing 8/24/2008 Offutt 40

GET and POST Requests A GET request is generated when the URL is entered directly doget () is called An HTML form can generate either a GET or a POST request Method=POST or Method=GET GET requests put form data on the URL as parameters http://www /RunForm?NAME=Jeff&TITLE=prof GET parameters are limited to 1024 bytes POST requests put form data in body of request 8/24/2008 Offutt 41

GET and POST Requests (2) Textbooks say: Use GET to retrieve data Use POST to change state on server (update file or DB) Use POST when there are a lot of data items My usual strategy: Use POST when sending data to server Use GET when no data is sent 8/24/2008 Offutt 42

GET and POST Requests (3) If my servlet is primarily based on processing data and I use POST, implement a simple doget() method as a filler:... <BODY> <CENTER>A Title </CENTER> <HR> <P> You should run this from <A Href="http://.html"> http://.html</a> </BODY> 8/24/2008 Offutt 43

Sending Mail Messages from Servlets Common job is to gather data from form and send through email Import mail utilities: import sun.net.smtp.smtpclient; Setup mail header: send = new SmtpClient ( gmu.edu ); send.from ( offutt@gmu.edu ); send.to ( offutt@gmu.edu ); Send message: out = send.startmessage (); out.println ( message header and body ); out.flush (); out.close (); out.closeserver (); 8/24/2008 Offutt 44

Sending Mail Messages (2) This is the simplest mechanism for sending email, but is not very powerful JavaMail is a collection of abstract library classes for handling mail with a number of different protocols 8/24/2008 Offutt 45

Redirecting to Another URL from Servlets Servlets usually generate an HTML file as a response, but sometimes you may want to send the client to a different URL. res.sendredirect ( http://www.ise.gmu.edu/ ); Do not need to set content type (setcontenttype()) The client will be sent to the specified URL Precisely: Server tells the client to generate another request to the new URL Handled by browser, but invisible to the user 8/24/2008 Offutt 46

Writing to files from Servlets Common job is to save data into a file File must be in a publically writeable directory: cd // File under your home directory mkdir Data // Subdirectory named "Data/" chmod 777 Data // Write permission for everyone Open a file, write to it, and close it: FileWriter outfile = new FileWriter ( /home/offutt/data/info-file ); outfile.write (... the data to save...); outfile.close (); Open a file in append mode: FileWriter outfile = new FileWriter ( /home/offutt/data/info-file, true); Remember Unix / Windows path differences!! info-file does NOT equal INFO-FILE!!! 8/24/2008 Offutt 47

Deployment Testing Development and deployment computers often differ Web apps must be tested on final deployment platform Must test just as real users use it Issues to check for: Different platforms (DOS / Unix / Linux / Mac ) File names and path names (local/nonlocal, DOS/Unix) Upper case dependencies Incomplete deployment Compiler and runtime system version Permissions (data and DB) 8/24/2008 Offutt 48

Examples http://www.ise.gmu.edu/~offutt/classes/432/examples/servlets/ 1. Hello: Prints lots of hellos 2. Name: Accepts and prints a name from a form 3. FormHandler: Processes data from any form 4. ChoosAbs: Processes form data and sends through email 5. LoanCalculater: Compute time to pay off a loan 6. Convert: Convert values 7. Convert2: Better value conversion 8. FileLoad: Uploading files from client 9. StudInfoSys432: Processes data from students 10. Coupling Demo: Demos a tool 11. SessionLifeCycle: Demonstrates session data 12. Attribute Servlet: Prints values in session data 13. Shop: Simple shopping cart 8/24/2008 Offutt 49