UNIT-5-Servlets

 

UNIT-5-Servlets

 

Servlet technology is used to create a web application (resides at server side and generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language. However, there were many disadvantages to this technology. We have discussed these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

What is a Servlet?

Servlet can be described in many ways, depending on the context.

  • Servlet is a technology which is used to create a web application.
  • Servlet is an API that provides many interfaces and classes including documentation.
  • Servlet is an interface that must be implemented for creating any Servlet.
  • Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests.
  • Servlet is a web component that is deployed on the server to create a dynamic web page.

Servlet

Do You Know?

  • What is the web application and what is the difference between Get and Post request?
  • What information is received by the web server if we request for a Servlet?
  • How to run servlet in Eclipse, MyEclipse and Netbeans IDE?
  • What are the ways for servlet collaboration and what is the difference between RequestDispatcher and sendRedirect() method?
  • What is the difference between ServletConfig and ServletContext interface?
  • How many ways can we maintain the state of a user? Which approach is mostly used in web development?
  • How to count the total number of visitors and whole response time for a request using Filter?
  • How to run servlet with annotation?
  • How to create registration form using Servlet and Oracle database?
  • How can we upload and download the file from the server?

What is a web application?

A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server and respond to the HTTP request.


CGI (Common Gateway Interface)

CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.

CGI vs., Servlet

Disadvantages of CGI

There are many problems in CGI technology:

  1. If the number of clients increases, it takes more time for sending the response.
  2. For each request, it starts a process, and the web server is limited to start processes.
  3. It uses platform dependent language e.g. CC++perl.

Advantages of Servlet

Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The advantages of Servlet are as follows:

  1. Better performance: because it creates a thread for each request, not process.
  2. Portability: because it uses Java language.
  3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc.
  4. Secure: because it uses java language.

What are Servlets?

Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

  • Performance is significantly better.
  • Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.
  • Servlets are platform-independent because they are written in Java.
  • Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.
  • The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.

Servlets Architecture

The following diagram shows the position of Servlets in a Web Application.

Servlets Architecture

 

Servlets Tasks

Servlets perform the following major tasks −

  • Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.
  • Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.
  • Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
  • Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
  • Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

 

Servlets Packages

Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current compiler.

Web Terminology

Servlet Terminology

Description

Website: static vs dynamic

It is a collection of related web pages that may contain text, images, audio and video.

HTTP

It is the data communication protocol used to establish communication between client and server.

HTTP Requests

It is the request send by the computer to a web server that contains all sorts of potentially interesting information.

Get vs Post

It gives the difference between GET and POST request.

Container

It is used in java for dynamically generating the web pages on the server side.

Server: Web vs Application

It is used to manage the network resources and for running the program or software that provides services.

Content Type

It is HTTP header that provides the description about what are you sending to the browser.

Servlet Interface

1. Servlet Interface

2. Methods of Servlet interface

Servlet interface provides common behavior to all the servlets.Servlet interface defines methods that all servlets must implement.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container.

Method

Description

public void init(ServletConfig config)

initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once.

public void service(ServletRequest request,ServletResponse response)

provides response for the incoming request. It is invoked at each request by the web container.

public void destroy()

is invoked only once and indicates that servlet is being destroyed.

public ServletConfig getServletConfig()

returns the object of ServletConfig.

public String getServletInfo()

returns information about servlet such as writer, copyright, version etc.

 


 

Life Cycle of a Servlet (Servlet Life Cycle)

1. Life Cycle of a Servlet

1. Servlet class is loaded

2. Servlet instance is created

3. init method is invoked

4. service method is invoked

5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

  1. Servlet class is loaded.
  2. Servlet instance is created.
  3. init method is invoked.
  4. service method is invoked.
  5. destroy method is invoked.

Life cycle of a servlet

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state.


1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container.


2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.


3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:

1.      public void init(ServletConfig config) throws ServletException  


4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:

1.      public void service(ServletRequest request, ServletResponse response)   

2.        throws ServletException, IOException  


5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below:

1.      public void destroy()  


 

HTTP Requests

The request sent by the computer to a web server, contains all sorts of potentially interesting information; it is known as HTTP requests.

The HTTP client sends the request to the server in the form of request message which includes following information:

  • The Request-line
  • The analysis of source IP address, proxy and port
  • The analysis of destination IP address, protocol, port and host
  • The Requested URI (Uniform Resource Identifier)
  • The Request method and Content
  • The User-Agent header
  • The Connection control header
  • The Cache control header

HTTP Requests

The HTTP request method indicates the method to be performed on the resource identified by the Requested URI (Uniform Resource Identifier). This method is case-sensitive and should be used in uppercase.

 

 

 

 

 

The HTTP request methods are:

HTTP Request

Description

GET

Asks to get the resource at the requested URL.

POST

Asks the server to accept the body info attached. It is like GET request with extra info sent with the request.

HEAD

Asks for only the header part of whatever a GET would return. Just like GET but with no body.

TRACE

Asks for the loopback of the request message, for testing or troubleshooting.

PUT

Says to put the enclosed info (the body) at the requested URL.

DELETE

Says to delete the resource at the requested URL.

OPTIONS

Asks for a list of the HTTP methods to which the thing at the request URL can respond

 


 

HTTP (Hypertext Transfer Protocol) specifies a collection of request methods to specify what action is to be performed on a particular resource. The most commonly used HTTP request methods are GET, POST, PUT, PATCH, and DELETE. These are equivalent to the CRUD operations (create, read, update, and delete).

Table of Content

·       HTTP Requests

·       Implementing GET Request

·       Making a POST Request

·       Making a PATCH Request

·       Making a DELETE Request

HTTP Requests

HTTP Requests are the message sent by the client to request the data from the server or to perform some actions. Different HTTP requests are:

·       GET: GET request is used to read/retrieve data from a web server. GET returns an HTTP status code of 200 (OK) if the data is successfully retrieved from the server.

·       POST: POST request is used to send data (file, form data, etc.) to the server. On successful creation, it returns an HTTP status code of 201.

·       PUT: A PUT request is used to modify the data on the server. It replaces the entire content at a particular location with data that is passed in the body payload. If there are no resources that match the request, it will generate one.

·       PATCH: PATCH is similar to PUT request, but the only difference is, it modifies a part of the data. It will only replace the content that you want to update.

·       DELETE: A DELETE request is used to delete the data on the server at a specified location.

 

 


 

Session Tracking in Servlets

  1. Session Tracking
  2. Session Tracking Techniques

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:

session tracking

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.


Session Tracking Techniques

There are four techniques used in Session tracking:

  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

Cookies in Servlet

cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.


How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

cookies in servlet


Types of Cookie

There are 2 types of cookies in servlets.

  1. Non-persistent cookie
  2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.


Advantage of Cookies

  1. Simplest technique of maintaining the state.
  2. Cookies are maintained at client side.

Disadvantage of Cookies

  1. It will not work if cookie is disabled from the browser.
  2. Only textual information can be set in Cookie object.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.


Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.

Constructor of Cookie class

Constructor

Description

Cookie()

constructs a cookie.

Cookie(String name, String value)

constructs a cookie with a specified name and value.

 

2) Hidden Form Field

  1. Hidden Form Field
  2. Example of Hidden Form Field

In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.

In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.

Let's see the code to store value in hidden field.

1.      <input type="hidden" name="uname" value="Vimal Jaiswal">  

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.


Real application of hidden form field

It is widely used in comment form of a website. In such case, we store page id or page name in the hidden field so that each page can be uniquely identified.


Advantage of Hidden Form Field

  1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

  1. It is maintained at server side.
  2. Extra form submission is required on each pages.
  3. Only textual information can be used.

Example of using Hidden Form Field

In this example, we are storing the name of the user in a hidden textfield and getting that value from another servlet.

Hidden Form Field in Servlet

 

)URL Rewriting

  1. URL Rewriting
  2. Advantage of URL Rewriting
  3. Disadvantage of URL Rewriting
  4. Example of URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.

URL Rewriting

Advantage of URL Rewriting

  1. It will always work whether cookie is disabled or not (browser independent).
  2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

  1. It will work only with links.
  2. It can send Only textual information.

4) HttpSession interface

  1. HttpSession interface
  2. How to get the HttpSession object
  3. Commonly used methods of HttpSession interface
  4. Example of using HttpSession

In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks:

  1. bind objects
  2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.

HttpSession object

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

  1. public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.
  2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface

  1. public String getId():Returns a string containing the unique identifier value.
  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
  4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting that value from the session scope in another servlet. To set the attribute in the session scope, we have used the setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute method.

index.html

1.      <form action="servlet1">  

2.      Name:<input type="text" name="userName"/><br/>  

3.      <input type="submit" value="go"/>  

4.      </form>  

 

 

JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to Servlet because it provides more functionality than servlet such as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet

There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

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.

3) Fast Development: No need to recompile and redeploy

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.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover, we can use EL, implicit objects, etc.


The Lifecycle of a JSP Page

The JSP pages follow these phases:

  • Translation of JSP Page
  • Compilation of JSP Page
  • Classloading (the classloader loads class file)
  • Instantiation (Object of the Generated Servlet is created).
  • Initialization ( the container invokes jspInit() method).
  • Request processing ( the container invokes _jspService() method).
  • Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

How JSP is converted into Servlet

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator. The JSP translator is a part of the web server which is responsible for translating the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later like initialization, committing response to the browser and destroy.


Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and save it by .jsp extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP page. We will learn scriptlet tag later.

1.      <html>  

2.      <body>  

3.      <% out.print(2*5); %>  

4.      </body>  

5.      </html>  

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

  • Start the server
  • Put the JSP file in a folder and deploy on the server
  • Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example, http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a simple JSP?

No, there is no need of directory structure if you don't have class files or TLD files. For example, put JSP files in a folder directly and deploy that folder. It will be running fine. However, if you are using Bean class, Servlet or TLD file, the directory structure is required.


The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-INF folder or in any directory.

The directory structure of JSP


 

JSP

Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Server Pages to develop your web applications in simple and easy steps.

Why to Learn JSP?

JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.

  • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having separate CGI files.
  • JSP are always compiled before they are processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
  • JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
  • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.

JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.

JSP needs. It knows how to understand the special elements that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web application.

JSP Architecture

JSP Processing

The following steps explain how the web server creates the Webpage using JSP −

  • As with a normal page, your browser sends an HTTP request to the web server.
  • The web server recognizes that the HTTP request is 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 a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code. This code implements the corresponding dynamic behavior of the page.
  • The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.
  • A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format. The output is furthur passed on to the web server by the servlet engine inside an HTTP response.
  • The web server forwards the HTTP response to your browser in terms of static HTML content.
  • Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response exactly as if it were a static page.

All the above mentioned steps can be seen in the following diagram −

JSP Processing

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's contents. This makes the process more efficient than with the other scripting languages (such as PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet.

Prinage

 


Life cycle of JSP

A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.

Paths Followed By JSP

The following are the paths followed by a JSP −

  • Compilation
  • Initialization
  • Execution
  • Cleanup

The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four phases have been described below −

JSP Life Cycle

Ezoic

JSP Compilation

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.

The compilation process involves three steps −

  • Parsing the JSP.
  • Turning the JSP into a servlet.
  • Compiling the servlet.

JSP Initialization

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...

}

Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.

Ezoic

JSP Execution

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows −

void _jspService(HttpServletRequest request, HttpServletResponse response) {

   // Service handling code...

}

The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.

JSP Cleanup

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.

The jspDestroy() method has the following form −

public void jspDestroy() {

   // Your cleanup code goes here.

}

 

Implicit objects

Implicit objects are a set of Java objects that the JSP Container makes available to developers on each page. These objects may be accessed as built-in variables via scripting elements and can also be accessed programmatically by JavaBeans and Servlets.JSP provide you Total 9 implicit objects which are as follows 
 

download.jpeg

1.      request: This is the object of HttpServletRequest class associated with the request.

2.      response: This is the object of  HttpServletResponse class associated with the response to the client.

3.      config: This is the object of ServletConfig class associated with the page.

4.      application: This is the object of ServletContext class associated with the application context.

5.      session: This is the object of HttpSession class associated with the request.

6.      page context: This is the object of PageContext class that encapsulates the use of server-specific features. This object can be used to find, get or remove an attribute.

7.      page object: The manner we use the keyword this for current object, page object is used to refer to the current translated servlet class.

8.      exception: The exception object represents all errors and exceptions which is accessed by the respective jsp. The exception implicit object is of type java.lang.Throwable.

9.      out: This is the PrintWriter object where methods like print and println help for displaying the content to the client.

 

 

 

JSP directives

The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.

There are three types of directives:

  • page directive
  • include directive
  • taglib directive

Following is the basic syntax of the page directive −

<%@ page attribute = "value" %>

You can write the XML equivalent of the above syntax as follows −

<jsp:directive.page attribute = "value" />

Attributes

Following table lists out the attributes associated with the page directive −

S.No.

Attribute & Purpose

1

buffer

Specifies a buffering model for the output stream.

2

autoFlush

Controls the behavior of the servlet output buffer.

3

contentType

Defines the character encoding scheme.

4

errorPage

Defines the URL of another JSP that reports on Java unchecked runtime exceptions.

5

isErrorPage

Indicates if this JSP page is a URL specified by another JSP page's errorPage attribute.

6

extends

Specifies a superclass that the generated servlet must extend.

7

import

Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes.

8

info

Defines a string that can be accessed with the servlet's getServletInfo() method.

9

isThreadSafe

Defines the threading model for the generated servlet.

10

language

Defines the programming language used in the JSP page.

11

session

Specifies whether or not the JSP page participates in HTTP sessions

12

isELIgnored

Specifies whether or not the EL expression within the JSP page will be ignored.

13

isScriptingEnabled

Determines if the scripting elements are allowed for use.

 

 

 

Comments

Popular posts from this blog

Compiler Design UNIT-1

COA- Unit -5 Peripheral DeviceS

COA-UNIT-3 Control Unit