Unit 5 JSP (Java Server Pages)

Similar documents
Unit 4 Java Server Pages

Experiment No: Group B_2

UNIT -5. Java Server Page

Advantage of JSP over Servlet

JSP MOCK TEST JSP MOCK TEST III

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

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

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

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

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

JavaServer Pages. Juan Cruz Kevin Hessels Ian Moon

One application has servlet context(s).

Java Server Page (JSP)

01KPS BF Progettazione di applicazioni web

Introduction to JSP and Servlets Training 5-days

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

Ch04 JavaServer Pages (JSP)

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

Basic Principles of JSPs

Java Server Pages JSP

Servlet Fudamentals. Celsina Bignoli

Enterprise Computing with Java MCA-305 UNIT II. Learning Objectives. JSP Basics. 9/17/2013MCA-305, Enterprise Computing in Java

PES INSTITUTE OF TECHNOLOGY, SOUTH CAMPUS DEPARTMENT OF MCA INTERNAL TEST (SCHEME AND SOLUTION) II

Sun Sun Certified Web Component Developer for J2EE 5 Version 4.0

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

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

6- JSP pages. Juan M. Gimeno, Josep M. Ribó. January, 2008

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

CS506 Web Design & Development Final Term Solved MCQs with Reference

Module 4: SERVLET and JSP

JSP. Basic Elements. For a Tutorial, see:

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

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

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

SNS COLLEGE OF ENGINEERING, Coimbatore

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

JavaServer Pages. What is JavaServer Pages?

Chapter 10 Servlets and Java Server Pages

SERVLETS INTERVIEW QUESTIONS

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:

Java Server Pages. Copyright , Xiaoping Jia. 7-01/54

Data Source Name (Page 150) Ref: - After creating database, you have to setup a system Data Source Name (DSN).

Fast Track to Java EE

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

Introduction to Java Server Pages. Enabling Technologies - Plug-ins Scripted Pages

JSP Scripting Elements

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

Questions and Answers

COMP9321 Web Application Engineering

First Simple Interactive JSP example

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.

Table of Contents. Introduction... xxi

COMP9321 Web Application Engineering

Trabalhando com JavaServer Pages (JSP)

Java E-Commerce Martin Cooke,

Java Servlets. Preparing your System

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

Module 5 Developing with JavaServer Pages Technology

SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY- VIRUDHUNAGAR

Module 3 Web Component

Oracle 1z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Practice Test. Version:

Specialized - Mastering JEE 7 Web Application Development

Watch Core Java and Advanced Java Demo Video Here:

112. Introduction to JSP

ADVANCED JAVA TRAINING IN BANGALORE

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

JavaServer Pages (JSP)

112-WL. Introduction to JSP with WebLogic

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction

ddfffddd CS506 FINAL TERMS SOLVED BY MCQS GHAZAL FROM IEMS CAMPUS SMD CS506 Mcqs file solved by ghazal

A Gentle Introduction to Java Server Pages

Trabalhando com JavaServer Pages (JSP)

COMP9321 Web Application Engineering

SSC - Web development Model-View-Controller for Java Servlet

Web applications and JSP. Carl Nettelblad

JAVA SERVLET. Server-side Programming INTRODUCTION

Servlets and JSP (Java Server Pages)

For live Java EE training, please see training courses at

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

The Servlet Life Cycle

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

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer JSP

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

AN ISO 9001:2008 CERTIFIED COMPANY ADVANCED. Java TRAINING.

Advanced Java Programming

SECTION I: JAVA SERVLETS AND JAVA SERVER PAGES

(Objective-CS506 Web Design and Development)

Java Programming Course Overview. Duration: 35 hours. Price: $900

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

Servlet and JSP Review

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

The JSP page Directive: Structuring Generated Servlets

Java4340r: Review. R.G. (Dick) Baldwin. 1 Table of Contents. 2 Preface

The Struts MVC Design. Sample Content

JAVA 2 ENTERPRISE EDITION (J2EE)

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

Page 1

Session 20 Data Sharing Session 20 Data Sharing & Cookies

JSP source code runs on the web server via JSP Servlet Engine. JSP files are HTML files with special Tags

web.xml Deployment Descriptor Elements

Transcription:

Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. It focuses more on presentation logic of the web apllication. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets. Servlet adds HTML code inside Java code while JSP adds Java code inside HTML. JSP files are HTML files with special tags containing Java source code that provide the dynamic content. It can be thought of as an extension to servlet because it provides more functionality than servlet such as expression language, jstl etc. How JSP works When browser sends an HTTP request to the web server. The web server recognizes that HTTP request for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with.jsp instead of.html. The JSP engine loads the JSP page from disk and converts it into servlet content. This conversion is very simple in which all text template is converted to println( )statements and all JSP elements are converted to Java code that implements the corresponding dynamic behaviour of the page. The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. Then, web server calls the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which servlet engine passes to the web server inside of HTTP response. The web server forwards the HTTP response to the browser in terms of static HTML content. 1 AJP(3360701) Prof. Vishal K. Makwana

Advantages Extension to Servlet o We can use all the features of servlet in JSP. We can also use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy. Easy to maintain o JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic. Fast Development, No need to recompile and redeploy o If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application. Less code than Servlet o In JSP, we can use a lot of tags such as action tags, JSTL (Java Standarad Tag Library), custom tags etc. that reduces the code. Also, we can use Expression Language (EL), implicit objects etc. Platform independent o It is built in java technology. JSP Life Cycle * A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to a Servlet is called Lifecycle of JSP. JSP Lifecycle consists of following steps: 1) Translation of JSP to Servlet code. 2) Compilation of Servlet to bytecode. 3) Loading Servlet class. 4) Creating servlet instance. 5) Initialization by calling jspinit() method 6) Request Processing by calling _jspservice() method 7) Destroying by calling jspdestroy() method 2 AJP(3360701) Prof. Vishal K. Makwana

1) Translation of JSP to Servlet code o JSP container checks the JSP page code and parse it to generate the servlet source code. o For example in Tomcat you will find generated servlet class files at <tomcat>/webapp/org/apache/jsp directory. o If the JSP page name is FirstJSP.jsp, usually the generate servlet class name as FirstJSP_jsp.class after compilation and java file name is FirstJSP_jsp.java after translation. 2) Compilation of Servlet to bytecode. o JSP container compiles the JSP class source code and produces the class file in this phase. 3) Loading Servlet class o Web Container loads the class in this phase. 4) Creating servlet instance o Web Container invokes the no-argument constructor of generated class to load and instantiate it. 5) Initialization (by calling jspinit() method) o Web Container invokes the init method of JSP class object and initializes the servlet config with init parms configured in development descriptor. o After this phase, JSP is ready to handle client requests. o Usually form translation to initialization of JSP happens when first request for JSP comes. 6) Request Processing (by calling _jspservice() method) o This is the longest lifecycle phase of JSP page and JSP page process the client requests. o The processing is multi-threaded and similar to servlets and for every request a new thread is created and ServletRequest and ServletResponse object is created and JSP service method _jspservice() is invoked. 7) Destroying (by calling jspdestroy() method) o When the Web Container removes the servlet instance from service, it calls the jspdestroy() method to perform any required clean up. JSP Life Cycle Methods A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows: 1) Compilation (Convert JSP to Servlet) 2) Initialization (jspinit()) 3) Execution (_jspservice()) 4) Cleanup (jspdestroy()) 3 AJP(3360701) Prof. Vishal K. Makwana

1) Compilation o JSP engine compiles the page. o The compilation process involves three steps: 1. Parsing the JSP. 2. Turning the JSP into a servlet. 3. Compiling the servlet. 2) jspinit() (Initialization) o When a container loads a JSP it invokes the jspinit () method before servicing any requests. If you need to perform JSP-specific initialization, override the jspinit () method: public void jspinit () { // Initialization code... } o This method is called only once in the JSP lifecycle to initialize it. o JSP declaration scripting element is used to initialize. 3) _jspservice() (Execution) o Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP container invokes the _jspservice() in the JSP. o The _jspservice() method takes an HttpServletRequest and HttpServletResponse as its parameters as below: void _jspservice (HttpServletRequest request,httpservletresponse response) { // Service handling code... } o The _jspservice() of a JSP is invoked once per request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTPmethods i.e. GET, POST, DELETE etc. 4) jspdestroy() (Cleanup) o This method is called only once in JSP lifecycle. o When the Container removes the servlet instance, it calls the jspdestroy() method to perform any required clean up. o The jspdestroy () method has the following form: public void jspdestroy() { // cleanup code goes here. } 4 AJP(3360701) Prof. Vishal K. Makwana

Difference between Servlet and JSP Servlet Servlets are java classes. Servlets run faster compared to JSP. In MVC, servlet act as a controller. servlets are best for use when there is more processing and manipulation involved. We cannot build custom tags using Servlet. To make servlet, java code knowledge must be there. In servlet implicit objects are not present. We cannot achieve functionality of servlets at client side. Consists of an html file for static content & java file for dynamic content. JSP JSP is webpage scripting language. JSP run slower compared to Servlet as it takes compilation time to convert into Java Servlets. In MVC, jsp act as a view. JSP are generally preferred when there is not much processing of data required. We can build custom tags using JSP. JSP are compiled to servlet effectively allowing you to produce a servlet by just writing the HTML page, without knowing Java. In JSP implicit objects are present. We can achieve functionality of JSP at client side by running JavaScript at client side. Contains java code embedded directly to in an html page by using special tags. JSP Scripting Elements The scripting elements provide the ability to insert java code inside JSP. JSP Scripting element is written inside <% tags. These code inside <% tags are processed by the JSP engine during translation of the JSP page. Any other text in the JSP page is considered as HTML code or plain text. Scripting Element Syntax Comment <%-- comment -- Scriptlet <% scriplets Declaration <%! declarations Expression <%= expression Directive <%@ directive 1) JSP Comment : o JSP Comment is used when you are creating a JSP page and want to put in comments about what you are doing. 5 AJP(3360701) Prof. Vishal K. Makwana

o JSP comments are only seen in the JSP page. These comments are neither included in servlet source code during translation phase, nor they appear in the HTTP response. Syntax: <%-- JSP comment -- 2) JSP Scriptlet : o JSP Scriptlet Tag allows you to write java code inside JSP page. Syntax: <% java source code 3) JSP Declaration : o The JSP declaration tag is used to declare fields and methods. o The code written inside the jsp declaration tag, the declaration is made inside the Servlet class but outside the service (or any other) method. o You can declare static member, instance variable and methods inside Declaration Tag. o Code placed in this tag must end in a semicolon(;). o Declarations do not generate output so are used with JSP expressions or scriptlets. Syntax: <%! Declaration Example: <%! int count=0; 4) JSP Expression : * o The code placed within JSP expression tag is written to the output stream of the response. o So, you need not write out.print() to display data. It is mainly used to print the values of variable or method. Syntax : <%= Java Expression Example : <%= (10*2) it turns into out.println((10*2)); o Between <%= we can put anything and that will converted to the String and that will be displayed. 5) JSP Directive: o It gives special instruction to Web Container at the time of page translation (JSP to Servlet). Syntax : <%@ directive_name attribute_name="value" o There are three types of directive tag: 1) page directive 2) include directive 3) taglib directive 1) JSP page directive : The page directive defines attributes that apply to an entire JSP page. Syntax: <%@ page attribute_name="value" 6 AJP(3360701) Prof. Vishal K. Makwana

There are many attributes as given in below table: Attribute Description Example import extends session errorpage iserrorpage iselignored language contenttype The import attribute is used to import class, interface or all the members of a package. It is similar to import keyword in java class or interface. It defines the parent class that will be inherited by the generated servlet. It is rarely used. It defines whether the JSP page is participating in an HTTP session. The value is either true or false. It is used to define the error page. if exception occurs in the current page, it will be redirected to the error page. It is used to declare that the current page is the error page. Default value is false. We can ignore the Expression Language (EL) in jsp by the iselignored attribute. By default its value is false. Means Expression Language is enabled by default. It specifies the scripting language used in the JSP page. The default value is "java". It defines the MIME type for the JSP response. The default value is text/html. autoflush It defines whether the buffered output is flushed automatically. <%@ page import="java.util.date" <%@ page language="java session="true" <%@ page language="java" errorpage="error.jsp" <%@ page iserrorpage="true" <%@ page iselignored="true" <%@ page language="java" <%@ page contenttype="text/html <%@ page 7 AJP(3360701) Prof. Vishal K. Makwana - autoflush="true"

buffer isthreadsafe info The default value is "true". It sets the buffer size in KB to handle output generated by the JSP page. The default size of the buffer is 8Kb. Servlet and JSP both are multithreaded. If you want to control this behaviour of JSP page, you can use isthreadsafe attribute of page directive. The value of isthreadsafe value is true. If you make it false, the web container will serialize the multiple requests. Means it will wait until the JSP finishes responding to a request before passing another request to it. It simply sets the information of the JSP page which is retrieved later by using getservletinfo() method of Servlet interface. <%@ page <%@ page buffer="16kb" isthreadsafe="false" <%@ page info="hello Welcome to info attribute" 2) JSP include directive : The include directive is used to include the contents of any resource it may be jsp file, html file or text file. It includes the original content of the included resource at page translation time. Syntax: <%@ include file="resourcename" 3) JSP taglib directive: The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags. Syntax : <%@ taglib uri=" tagliburi " prefix="prefixoftag" The prefix is used to distinguish the custom tag from other libary custom tag. Every custom tag must have a prefix. The URI is the unique name for Tag Library. 8 AJP(3360701) Prof. Vishal K. Makwana

JSP implicit Objects/Predefined variables Implicit objects are created by the web container and are available to all the jsp pages. There are 9 JSP implicit objects. Object out request response config application Session pagecontext Description The JspWriter object associated with the output stream of the response. Example : <% out.println( Welcome ) The HttpServletRequest object associated with the request. So, we can get request information parameter (getparameter()), header information (cookie), server port, content type etc. It can also be used to set, get and remove attributes. Example: <% String name=request.getparameter("uname"); The HttpServletReponse object associated with the response that is sent back to the browser. It can be used to add or manipulate response such as redirect response to another resource. Example: <% response.sendredirect("http://www.google.com"); It is an implicit object of type ServletConfig. This object can be used to get initialization parameter for a particular JSP page from web.xml. Example : <% String name=config.getinitparameter("name"); It is an object of type ServletContext. The instance of ServletContext is created only once by the web container when application or project is deployed on the server. It can be used to get initialization parameter from configuration file (web.xml). It can also be used to get, set or remove attribute from the application scope. Example: <% String name=application.getinitparameter("name"); It is an object of type HttpSession. The Java developer can use this object to set, get or remove attribute or to get session information. Example: <% session.setattribute("user",name); It is an object of type PageContext class. It can be used to set, get or remove attribute from page, request, session or application scope. page scope is the default scope. Example: <% pagecontext.setattribute("user",name,pagecontext.session_scope); 9 AJP(3360701) Prof. Vishal K. Makwana

page exception It is an object of type Object class. This object is assigned to the reference of auto generated servlet class. It is an object of type java.lang.throwable class. This object can be used to print the exception. This object is only available to pages that have iserrorpage set to true with the directive. 10 AJP(3360701) Prof. Vishal K. Makwana