Chapter 10 Servlets and Java Server Pages

Similar documents
11.1 Introduction to Servlets

Introduction to JSP and Servlets Training 5-days

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

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

Fast Track to Java EE

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

Servlet Fudamentals. Celsina Bignoli

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

SERVLETS INTERVIEW QUESTIONS

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

Unit 5 JSP (Java Server Pages)

Servlets and JSP (Java Server Pages)

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

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

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

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

JSP MOCK TEST JSP MOCK TEST IV

Module 4: SERVLET and JSP

Table of Contents. Introduction... xxi

Session 12. JSP Tag Library (JSTL) Reading & Reference

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

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

SNS COLLEGE OF ENGINEERING, Coimbatore

UNIT -5. Java Server Page

Servlet Basics. Agenda

Session 8. Introduction to Servlets. Semester Project

Module 3 Web Component

About the Authors. Who Should Read This Book. How This Book Is Organized

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

Session 20 Data Sharing Session 20 Data Sharing & Cookies

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

Java Servlets. Preparing your System

112. Introduction to JSP

JSTL. JSTL (Java Standard Tag Library) is a collection of custom tags that are developed and maintained by the Jakarta project.

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

Sun Sun Certified Web Component Developer for J2EE 5 Version 4.0

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

COMP9321 Web Application Engineering

112-WL. Introduction to JSP with WebLogic

ADVANCED JAVA TRAINING IN BANGALORE

Specialized - Mastering JEE 7 Web Application Development

Web Presentation Patterns (controller) SWEN-343 From Fowler, Patterns of Enterprise Application Architecture

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

directive attribute1= value1 attribute2= value2... attributen= valuen %>

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

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

Web based Applications, Tomcat and Servlets - Lab 3 -

COMP9321 Web Application Engineering

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

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

Anno Accademico Laboratorio di Tecnologie Web. Sviluppo di applicazioni web JSP

Advanced Java Programming

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

CS 112 Introduction to Programming

JSP - SYNTAX. Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:

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

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

Java Server Page (JSP)

Building Web Applications in WebLogic

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

Handout 31 Web Design & Development

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Experiment No: Group B_2

LearningPatterns, Inc. Courseware Student Guide

An excellent explanation of how web browsers work:

CSC309: Introduction to Web Programming. Lecture 10

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

COMP9321 Web Application Engineering

Component Based Software Engineering

INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad

UNIT -I PART-A Q.No Question Competence BTL

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

FINALTERM EXAMINATION Spring 2009 CS506- Web Design and Development Solved by Tahseen Anwar

Advanced Web Systems 3- Portlet and JSP-JSTL. A. Venturini

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

Chapter 10 Web-based Information Systems

Actual4Test. Actual4test - actual test exam dumps-pass for IT exams

Distributed Systems 1

ProgramvaruUtveckling för Stora System F2

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

JAVA 2 ENTERPRISE EDITION (J2EE)

Using Java servlets to generate dynamic WAP content

JavaServer Pages. What is JavaServer Pages?

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

TUTORIAL QUESTION BANK

What's New in the Servlet and JSP Specifications

ADVANCED JAVA COURSE CURRICULUM

JdbcResultSet.java. import java.sql.*;

Session 9. Introduction to Servlets. Lecture Objectives

JSP: Servlets Turned Inside Out

Java.. servlets and. murach's TRAINING & REFERENCE 2ND EDITION. Joel Murach Andrea Steelman. IlB MIKE MURACH & ASSOCIATES, INC.

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

Java4570: Session Tracking using Cookies *

Database. Request Class. jdbc. Servlet. Result Bean. Response JSP. JSP and Servlets. A Comprehensive Study. Mahesh P. Matha

Unit 4 - Servlet. Servlet. Advantage of Servlet

ive JAVA EE C u r r i c u l u m

Questions and Answers

JAVA SERVLET. Server-side Programming INTRODUCTION

Table of Contents Fast Track to Java EE 5 with Servlets/JSP and JDBC

Transcription:

Chapter 10 Servlets and Java Server Pages

10.1 Overview of Servlets A servlet is a Java class designed to be run in the context of a special servlet container An instance of the servlet class is instantiated by the container and is used to handle requests directed to that servlet In the most common case, servlets are used to create responses to HTTP requests 10-2

10.1 Servlet Request Browser HTTP Request HTTP Response Servlet Container Request object Response object Response Servlet 10-3

10.1 Servlet Advantages Since servlets stay in existence while the server/container is running, they can remember state Java is a more robust development language Because the servlet stays running, it is potentially more efficient than CGI CGI programs are started for each request Improvements, such as mod_perl in the Apache web server, reduce much of the overhead of CGI by keeping programs in memory een between requests 10-4

10.2 Servlet Details Servlet class implement the Servlet interface Several convenience classes are provided that implement Servlet GenericServlet HttpServlet Since most servlets respond to HTTP requests, the most common way to implement a servlet is to extend the HttpServlet class 10-5

10.2 HttpServlet Details The class provides four methods to handle different types of HTTP requests doget dopost doput dodelete An extension class will implement one or more of these methods Each method is called with two parameters A request parameter containing data about the request A response parameter that is used by the servlet to create the response doget and doput are the only methods used in this text 10-6

10.2 Responding to HttpServlet Request The HTTP request is mapped to a servlet by the servlet container A configuration file provides a standard way of mapping paths to servlet classes The HttpServletResponse object passed as a parameter to doget and dopost provides a PrintWriter object Output sent to the PrintWriter object will become part of the response The HttpServletResponse object has a setcontenttype method that takes the MIME type of the response as a parameter 10-7

10.2 Generating a Request As with CGI, there are two main ways of invoking a servlet A hyperlink that specifies a path to the servlet A form action that specifies a path to the servlet The tstgreet.html and Greeting.java files give a simple example in which no data is sent with the request 10-8

10.3 A Survey Example This example presents a simple survey Site visitors fill out a simple survey Survey results are recorded and stored in a file A summary of survey results is presented The getparameter method of HttpServletRequest is used to get the data sent from the survey form 10-9

10.3 Survey Example: Race Condition Since multiple requests may be processed at roughly the same time, some mechanism is needed to prevent the requests from interfering with each other Such possible interference is known as a race condition The Java synchronized clause is used to prevent multiple threads executing file access code at the same time 10-10

10.4 Cookies HTTP is a stateless protocol, that is, the server treats each request as completely separate from any other This, however, makes some applications difficult A shopping cart is an object that must be maintained across numerous requests and responses The mechanism of cookies can be used to help maintain state by storing some information on the browser system A cookie is a key/value pair that is keyed to the domain of the server This key/value pair is sent along with any request made by the browser of the same server A cookie has a lifetime which specifies a time at which the cookie is deleted from the browser 10-11

10.4 Cookies and Security Cookies are only returned to the server that created them Cookies can be used to determine usage patterns that might not otherwise be ascertained by a server Browsers generally allow users to limit how cookies are used Browsers usually allow users to remove all cookies currently stored by the browser Systems that depend on cookies will fail if the browser refuses to store them 10-12

10.4 Servlet Support for Cookies The Java servlet support library defines a Cookie class Methods are provided to set the comment, set a maximum age, and set a value Other methods retrieve data from the object The HttpServletResponse object has an addcookie method Cookies must be added before setting content type in the response The HttpServletRequest object has a getcookies method that returns an array of Cookies from the request 10-13

10.4 An Example The ballot example has two components Ballot.html has a form used to cast a vote VoteCounter.java defines a servlet which counts the votes for each candidate The response page to a user casting a ballot carries a cookie. This is used to mark a user as having voted The vote tabulating servlet checks for the cookie and refuses to tabulate a vote if the cookie is provided with the request 10-14

10.4 Session Tracking In the Java servlet framework, sessions are sets of key/value pairs The HttpSession object implements a session Several methods are provided to manipulate values putvalue defines a key/value pair Invalidate destroys the session removevalue removes a key/value pair getvalue retrieves a value given the key A session object, if defined, is attached to the request object The programmer can access the object The programmer can specify on access that the session be created if it does not yet exist An alternate vote counting servlet uses sessions to check for duplicate voting 10-15

10.5 Java Server Pages Java Server Pages (JSP) provide a way of embedding active content in a web page Servlet containers manage JSP s also A Java Server Page is first converted to a servlet which is then operates as previously described 10-16

10.5 Motivations for JSP Creating HTML documents using println is tedious and error prone Separation of coding and web page development can be more efficient for a team of developers On the other hand, if there is too much code embedded in the web page, the reverse problem arises 10-17

10.5 JSP Documents JSP documents can be created in two different ways The classic syntax uses specially formatted tags, generally starting with <% The newer XML syntax uses valid XML JSP documents contain four kinds of elements XHTML code, called template text Action elements Directives Scriptlets Template text is passed through to the response unchanged 10-18

10.5 Action Elements Action elements create content There are three categories of action elements Standard action elements Custom action elements JSP Standard Tag LIbrar (JSTL) elements Standard action elements are defined by the JSP standard and include basic services such as element generation and file inclusion Custom action elements are defined by creating Java code The JSTL is a collection of custom tags that provide important utilities 10-19

10.5 JSTL The JSTL contains five sub-libraries Core tags XML Processing Internationalization and formatting Database access Functions JSTL also supports an expression language 10-20

10.5 Directives Directives are tags that begin with <%@ Directives define the environment in which the JSP is interpreted A page directive provides information such as content type The taglib directive is used to make libraries of custom tags available to the JSP JSTL tags must be imported with a taglib directive <%@ taglib prefix= c uri= http://java.sun.com/jsp/jstl/core %> Is used to allow the current JSP refer to the JSTL core library Tags from that library will use the c: qualifier 10-21

10.5 Scriptlets Scriptlets allow embedding programming language code into a JSP Although extensions can be used to support other languages, Java is the one that must be supported The expression scriptlet <%= expression %> Causes the value of the expression be put into the response General Java code can be enclosed within <% %> JSP comments <%-- --%> are not put into the response Regular HTML comments <!-- --> are put into the response 10-22

10.5 Temperature Conversion Example tempconvert0.html and temconvert0.jsp provide a temperature conversion example Tempconvert1.jsp is similar but both pages are integrated into the same JSP A Java if is used to conditionally include content in the response If the request comes with a data value with key ctemp, it is assumed that this is a request from the form Otherwise, it is assumed that this is the first request and only the form is sent 10-23

10.5 Expression Language The JSTL expression language (EL) uses ${.. } to indicate an expression The expression language includes standard operators In some cases alternate names are provided to avoid problems with the HTML special characters So, ge is provided as a synonym for >= The param object is predefined in EL to provide data submitted with an HTTP request ${param.name} gets the value associated with name ${param[ fancy name ]} gets the value if the name is not a proper identifier It is usually best to use the JSTL core tag c:out to put the value of an expression into the response Tempconvert2.html and tempconvert2.jsp implement temperature conversion using EL 10-24

10.5 JSTL Control Action Elements The JSTL core library defines a number of control structures The c:if tag defines a one way branch, no else is allowed Tempconvert3.jsp uses the c:if tag to determine if the request being sent uses the POST method or not If the POST method is used, it must be a form submission, so data is accessed and the conversion is carried out If the GET method is used, this must be a first request for the page, so the form itself is returned 10-25

10.5 JST foreach The c:foreach tag provides iteration Iteration through a list of values is supported Iterations through a sequence of numeric values is supported If, for example, several checkboxes have the same name attribute, the value of parmvalues.name will be a list of the values <c:foreach items= ${paramvalues.name} var= x > Will step the variable x through each value in the list 10-26

10.5 JSTL choose The c:choose tag provides a multi-way choice The testradio.jsp example uses c:if to determine the method of the request If the method is POST, the JSP uses the c:choose construct to determine which text to put into the response 10-27