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



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

2.8. Session management

ACM Crossroads Student Magazine The ACM's First Electronic Publication

11.1 Web Server Operation

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

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

Introduction to J2EE Web Technologies

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

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

Principles and Techniques of DBMS 5 Servlet

Java Servlet Tutorial. Java Servlet Tutorial

Java 2 Web Developer Certification Study Guide Natalie Levi

An introduction to web programming with Java

Creating Java EE Applications and Servlets with IntelliJ IDEA

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

INTRODUCTION TO WEB TECHNOLOGY

Web Container Components Servlet JSP Tag Libraries

Session Tracking Customized Java EE Training:

How to program Java Card3.0 platforms?

CHAPTER 9: SERVLET AND JSP FILTERS

Manual. Programmer's Guide for Java API

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

Java Server Pages and Java Beans

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

SERVLETSTUTORIAL. Simply Easy Learning by tutorialspoint.com. tutorialspoint.com

Managing Data on the World Wide-Web

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

Ch-03 Web Applications

Web Application Programmer's Guide

CS506 Web Design and Development Solved Online Quiz No. 01

Essentials of the Java(TM) Programming Language, Part 1

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

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

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

How to use JavaMail to send

COMP9321 Web Applications Engineering: Java Servlets

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

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

Class Focus: Web Applications that provide Dynamic Content

Java Servlet Specification Version 2.3

CHAPTER 5. Java Servlets

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

Building Java Servlets with Oracle JDeveloper

CIS 455/555: Internet and Web Systems

Java Servlet and JSP Programming. Structure and Deployment China Jiliang University

An Overview of Java. overview-1

Building Web Applications with Servlets and JavaServer Pages

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

No no-argument constructor. No default constructor found

PA165 - Lab session - Web Presentation Layer

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

Web Programming with Java Servlets

Application Security

Automatic generation of distributed dynamic applications in a thin client environment

Creating a Simple, Multithreaded Chat System with Java

Web Application Development on a Linux System With a DB2 Database By Alan Andrea

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

An overview of Web development (for PDL)

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

Java Server Pages (JSP)

Database System Concepts

AN OVERVIEW OF SERVLET AND JSP TECHNOLOGY

Please send your comments to:

Penetration from application down to OS

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

Outline Introduction

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

CONTROLLING WEB APPLICATION BEHAVIOR WITH

Java Servlet 3.0. Rajiv Mordani Spec Lead

Virtual Open-Source Labs for Web Security Education

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Handling the Client Request: Form Data

Improving Web Security Education with Virtual Labs and Shared Course Modules

Supplement IV.E: Tutorial for Tomcat. For Introduction to Java Programming By Y. Daniel Liang

Java and Web. WebWork

Controlling Web Application Behavior

SESSION TRACKING. Topics in This Chapter

Model-View-Controller. and. Struts 2

Servlet and JSP Filters

Glassfish, JAVA EE, Servlets, JSP, EJB

CS 111 Classes I 1. Software Organization View to this point:

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

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

White Paper March 1, Integrating AR System with Single Sign-On (SSO) authentication systems

Java Server Pages combined with servlets in action. Generals. Java Servlets

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

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

Building a Multi-Threaded Web Server

Transcription:

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

What is a Servlet? A Servlet is a Java program that extends the capabilities of servers. Inherently multi-threaded. threaded. Each request launches a new thread. Input from client is automatically parsed into a Request variable. 2

Servlet Life Cycle Servlet Instantiation: Loading the servlet class and creating a new instance Servlet Initialization: Initialize the servlet using the init() method Servlet processing: Handling 0 or more client requests using the service() method Servlet Death: Destroying the servlet using the destroy() method 3

Client Form:Client Servlet-Enabled:Server Lookup Static Page or Launch Process/Thread to Create Output Http Request Lookup Launch Servlet On first access launch the servlet program. Launch Thread for Client Http Response Launch separate thread to service each request. Http Response 4

Writing Servlets Install a web server capable of launching and managing servlet programs. Install the javax.servlet package to enable programmers to write servlets. Ensure CLASSPATH is changed to correctly reference the javax.servlet package. Define a servlet by subclassing the HttpServlet class and adding any necessary code to the doget() and/or dopost() and if necessary the init() functions. 5

Handler Functions Each HTTP Request type has a separate handler function. GET -> doget(httpservletrequest HttpServletRequest, HttpServletResponse) POST -> dopost(httpservletrequest HttpServletRequest, HttpServletResponse) PUT -> doput (HttpServletRequest, HttpServletResponse) DELETE -> dodelete (HttpServletRequest, HttpServletResponse) TRACE -> dotrace (HttpServletRequest, HttpServletResponse) OPTIONS -> dooptions (HttpServletRequest, HttpServletResponse) 6

A Servlet Template import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { // Use "request" to read incoming HTTP headers // (e.g. cookies) and HTML form data (e.g. data the user // entered and submitted). // Use "response" to specify the HTTP response status // code and headers (e.g. the content type, cookies). } } PrintWriter out = response.getwriter(); // Use "out" to send content to browser 7

Important Steps Import the Servlet API: import javax.servlet.*; import javax.servlet.http.*; Extend the HTTPServlet class Full servlet API available at: http://www.java.sun.com/products/servlet/2.2/j avadoc/index.html You need to overrride at least one of the request handlers! Get an output stream to send the response back to the client All output is channeled to the browser. 8

doget and dopost The handler methods each take two parameters: HTTPServletRequest: : encapsulates all information regarding the browser request. Form data, client host name, HTTP request headers. HTTPServletResponse: : encapsulate all information regarding the servlet response. HTTP Return status, outgoing cookies, HTML response. If you want the same servlet to handle both GET and POST, you can have doget call dopost or vice versa. Public void doget(httpservletrequest req, HttpServletResponse res) throws IOException {dopost(req,res);} 9

Hello World Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>\n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n" + "</BODY></HTML>"); } } 10

getparameter() Use getparameter() to retrieve parameters from a form by name. Named Field values HTML FORM <INPUT TYPE="TEXT" NAME="diameter"> In a Servlet String sdiam = request.getparameter("diameter"); 11

getparameter() cont d getparameter() can return three things: String: corresponds to the parameter. Empty String: parameter exists, but no value provided. null: Parameter does not exist. 12

getparametervalues() Used to retrieve multiple form parameters with the same name. For example, a series of checkboxes all have the same name, and you want to determine which ones have been selected. Returns an array of Strings. 13

getparameternames() Returns an Enumeration object. By cycling through the enumeration object, you can obtain the names of all parameters submitted to the servlet. Note that the Servlet API does not specify the order in which parameter names appear. 14

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class circle extends HttpServlet { public void doget(httpservletrequest request, } HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println( "<BODY><H1 ALIGN=CENTER> Circle Info </H1>\n"); try{ } String sdiam = request.getparameter("diameter"); double diam = Double.parseDouble(sdiam); out.println("<br><h3>diam:</h3>" + diam + "<BR><H3>Area:</H3>" + diam/2.0 * diam/2.0 * 3.14159 + "<BR><H3>Perimeter:</H3>" + 2.0 * diam/2.0 * 3.14159); } catch ( NumberFormatException e ){ out.println("please enter a valid number"); out.println("</body></html>"); Subclass HttpServlet. Circle Servlet Specify HTML output. Attach a PrintWriter to Response Object 15

Cookies and Servlets The HttpServletRequest class includes the getcookies() function. This returns an array of cookies, or null if there aren t any. Cookies can then be accessed using three methods. String getname() String getvalue() String getversion() 16

Cookies & Servlets cont d Cookies can be created using HttpServletResponse.addCookie addcookie() and the constructor new Cookie(String name, String value); Expiration can be set using setmaxage(int seconds) 17

Sessions & Servlets Servlets also support simple transparent sessions Interface HttpSession Get one by using HttpServletRequest.getSession getsession() You can store & retrieve values in the session putvalue(string name, String value) String getvalue(string name) String[] getnames() 18

Sessions & Servlets cont d Various other information is stored long getcreationtime() String getid() long getlastaccessedtime() Also can set timeout before session destruction int getmaxinactiveinterval() setmaxinactiveinterval(int seconds) 19