Servlets Tutorial in PDF - Learning Java Servlets in simple and easy steps using this beginner's tutorial containing basic to advanced knowledge of Java Servlet. This tutorial will teach you how to use Java Servlets to develop your web based and graphics published in this e-book are the property of Tutorials Point. bernasungueta.ga Java Servlets are programs that run on a Web or Application server and act as a middle layer.

Tutorialspoint Servlet Pdf

Language:English, Dutch, Hindi
Published (Last):04.09.2016
ePub File Size:21.37 MB
PDF File Size:9.45 MB
Distribution:Free* [*Registration Required]
Uploaded by: BRIAN

Servlet and JSP. Programming with IBM WebSphere Studio and VisualAge for Java. Ueli Wahli. Mitch Fielding. Gareth Mackown. Deborah Shaddon. You can also download our FREE Java Servlet Ultimate Guide! Besides studying them online you may download the eBook in PDF format!. JSP tutorialspoint - Download as PDF File .pdf), Text File .txt) or read online. JSP.

This method returns an Enumeration that contains the parameter names in an unspecified order.

Following is the generic example which uses getParameterNames method of HttpServletRequest to read all the available form parameters. Now try calling JSP using above Hello. To intercept requests from a client before they access a resource at back end. To manipulate responses from server before they are sent back to the client.

There are various types of filters suggested by the specifications: Authentication Filters. Data compression Filters Encryption Filters. Filters that trigger resource access events. Image Conversion Filters. Logging and Auditing Filters.

Tokenizing Filters. Filters are deployed in the deployment descriptor file web. The deployment descriptor file web. When the JSP container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

Servlet Filter Methods: A filter is simply a Java class that implements the javax. Filter interface. The javax. Filter interface defines three methods: JSP Filter Example: This example would give you basic understanding of JSP Filter, but you can write more sophisticated filter applications using the same concept: Create the following entry for filter tag in the deployment descriptor file web.

Now try to call any servlet or JSP in usual way and you would see generated log in you web server log. You can use Log4J logger to log above log in a separate file. Using Multiple Filters: Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained above except you need to create a different mapping as mentioned below: The order of filter-mapping elements in web. To reverse the order of the filter.

This chapter will teach you how to set or reset cookies. A JSP that sets a cookie might send headers that look something like this: If the browser is configured to store cookies. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date. The Anatomy of a Cookie: The browser's headers might look something like this: If the user points the browser at any page that matches the path and domain of the cookie. There are three steps involved in identifying returning users: For example name.

Servlet Cookies Methods: Following is the list of useful methods associated with Cookie object which you can use while manipulating cookies in JSP: If you don't specify a path. The comment is useful if the browser presents the cookie to the user. The name cannot be changed after creation. SSL connections. Keep-Alive User-Agent: Linux 2. By default. If you don't set this. You use response.

You use setMaxAge to specify how long in seconds the cookie should be valid. Keep in mind. Let us modify our Form Example to set the cookies for first and last name. Following would set up a cookie for 24 hours. Setting Cookies with JSP: Setting cookies with JSP involves three steps: You call the Cookie constructor with a cookie name and a cookie value. Then cycle through the array.

Next section would explain you how you would access these cookies back in your web application. Reading Cookies with JSP: To read cookies. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button. Let us read cookies which we have set in previous example: Try to enter First Name and Last Name and then click submit button.

Cookie objects by calling thegetCookies method of HttpServletRequest. Found Cookies Name and Value Name: To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps: John Name: Set cookie age as zero using setMaxAge method to delete an existing cookie. Add this cookie back into response header. It would display the following result: Cookies Name and Value Deleted cookie: Player You can delete your cookies in Internet Explorer manually.

Start at the Tools menu and select Internet Options.

Tutorialspoint servlet pdf

Player Now try to run http: Still there are following three ways to maintain session between web client and web server: A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.

Each time when web browser sends request back. This may not be an effective way because many time browser does not support a cookie. URL Rewriting: You can append some extra data on the end of each URL that identifies the session. Hidden Form Fields: JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

Apart from the above mentioned three ways. Here is a summary of important methods available through session object: URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page. Since session object is already provided to the JSP programmer. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows: JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically.

Object value This method binds an object to this session. Session Tracking Example: This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist.

Delete the whole session: You can call public void invalidate method to discard an entire session. Log the user out: The servers that support servlets 2. You can call public void removeAttribute String name method to delete the value associated with a particular key.

Setting Session timeout: You can call public void setMaxInactiveInterval int interval method to set the timeout for a session individually. When you are done with a user's session data. It would display the following result when you would run for the first time: The getMaxInactiveInterval method in a servlet returns the timeout period for that session in seconds.

If you are using Tomcat. Creating a File Upload Form: The following HTM code below creates an uploader form. Following are the important points to be noted down: An uploaded file could be a text file or binary or image file or any document. The form action attribute should be set to a JSP file which would handle file uploading at backend server. The browser associates a Browse button with each of them.

Following example is using uploadFile. File Upload: To allow multiple files uploading. While testing following example. You can hard code this in your program or this directory name could also be added using an external configuration such as a context-param element in web. You can download it from http: FileUpload depends on Commons IO. First let us define a location where uploaded files would be stored..

Before proceeding you have make sure the followings: Make sure you have created directories c: Select a file to upload: Above form is just dummy form and would not work. You can download it fromhttp: When you would try http: The first constructor initializes the object with the current date and time. SN Methods with Description 1 boolean after Date date Returns true if the invoking Date object contains a date that is later than the one specified by date. Returns a negative value if the invoking object is earlier than date.

Servlets Tutorial in PDF

The Date class supports two constructors. Returns a positive value if the invoking object is later than date. The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight.

This tutorial would take you through Java provided Date class which is available in java. Returns 0 if the values are equal. Object clone Duplicates the invoking Date object.

January 1.

In case you need to compare two dates. Date Comparison: You can use the methods before. Because the 12th of the month comes before the 18th. You can use a simple Date object withtoString method to print current date and time as follows: To specify the time format use a time pattern string. Date Formatting using SimpleDateFormat: SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. In this pattern. Let us modify above example as follows: The simplest way of redirecting a request to another page is using method sendRedirect of response object.

Following is the signature of this method: You can also use setStatus and setHeader methods together to achieve the same redirection: This example shows how a JSP performs page redirection to an another location: Usually you attach.

To implement a hit counter you can make use of Application Implicit object and associated methods getAttribute and setAttribute. Following is the syntax to set a variable at application level: Following is the method to read the variable set by previous method: This example shows how you can use JSP to count total number of hits on a particular page.

If you want to count total number of hits of your website then you would have to include same code in all the JSP pages. Assign a zero value to it. With every hit. You can try to access the page using different browsers and you will find that hit counter will keep increasing with every hit and would display result something as follows: Welcome back to my website! Total number of visits: What about if you re-start your application ie.

To avoid this loss. Display new value of hitcount as total page hit counts. If you want to count hits for all the pages. This would display hit counter value which would increase every time when you refresh the page. Increase the value of hitcount by one and update the table with new value.

Auto Page Refresh Example: JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.

The simplest way of refreshing a web page is using method setIntHeader of response object.

For all such type of pages. Send a Simple Email: Here is an example to send a simple email from your machine. You need to add mail. Download and unzip these files.


You can download latest version of JavaMail Version 1. Here it is assumed that your localhostis connected to the internet and capable enough to send an email. This is the array of email ID. Example Message. CC or BCC. If you want to send an email to multiple recipients then following methods would be used to specify multiple email IDs: Sent message successfully.

Address[] addresses throws MessagingException Here is the description of the parameters: This would be set to TO. RecipientType type. This example is very similar to previous one. Here is an example to send an HTML email from your machine.

Using this example. Send Attachment in Email: Here is an example to send an email with attachment from your machine: User Authentication Part: If it is required to provide user ID and Password to the email server for authentication purpose then you can set these properties as follows: Rest of the email sending mechanism would remain as explained above. Once you have all the information. Using Forms to send email: You can use HTML form to accept email parameters and then you can use request object to get all the information as follows: Core Tags: The core group of tags are the most frequently used JSTL tags.

If you are using Apache Tomcat container then follow the following two simple steps: It also provides a framework for integrating existing custom tags with JSTL tags. To use any of the libraries. The JSTL tags can be classified. To use the Standard Taglib from its Jakarta Taglibs distribution. JSTL has support for common. Creates a URL with optional query parameters Formatting tags: The JSTL formatting tags are used to format and display text. Catches any Throwable that occurs in its body and optionally exposes it.

Simple conditional tag which evalutes its body if the supplied condition is true. Stores the given locale in the locale configuration variable. Simple conditional tag that establishes a context for mutually exclusive conditional operations.. Parses the string representation of a number. Retrieves an absolute or relative URL and exposes its contents to either the page. Sets the result of an expression evaluation in a 'scope' Removes a scoped variable from a particular scope. Iterates over tokens.

The basic iteration tag. Adds a parameter to a containing 'import' tag's URL. Loads a resource bundle and stores it in the named scoped variable or the bundle configuration variable. Redirects to a new URL. Following is the syntax to include Formatting library in your JSP: Stores the given time zone in the time zone configuration variable To display an internationalized message. Sets a parameter in an SQL statement to the specified java.

XML tags: Executes the SQL update defined in its body or through the sql attribute. Sets a parameter in an SQL statement to the specified value. Date value. Download it from http: This includes parsing XML. Provides nested database action elements with a shared Connection. Sets the request character encoding SQL tags: Returns a subset of a string. Returns the number of items in a collection. JSTL includes a number of standard functions. Tests if an input string starts with the specified prefix.

If the test condition is false. Tests if an input string contains the specified substring in a case insensitive way.

Tests if an input string ends with the specified suffix. Sets a variable to the value of an XPath expression. To loop over nodes in an XML document. Escapes characters that could be interpreted as XML markup. Returns a subset of a string following a specific substring. Splits a string into an array of substrings. Simple conditional tag that establishes a context for mutually exclusive conditional operations. Returns the index withing a string of the first occurrence of a specified substring.

Evaluates a test XPath expression and if it is true. Function fn: Use to parse XML data specified either via an attribute or in the tag body.. Returns a string resulting from replacing in an input string all occurrences with a given string.

Joins all elements of an array into a string.. Removes white spaces from both ends of a string. Converts all of the characters of a string to upper case. Converts all of the characters of a string to lower case. Open a Command Prompt and change to the installation directory as follows: Login to database as follows C: To start with basic concept.

Before starting with database access through a JSP. Query OK. Create Data Records Finally you create few records in Employee table as follows: As an XML document is merely a bunch of text. To set the content type. The title of the first book is: Padam History The price of the second book: Consider the following XSLT stylesheet style. Following are the unique characteristics that distinguish a JavaBean from other Java classes: It provides a default.

JavaBeans Properties: A JavaBean property is a named attribute that can be accessed by the user of the object. A read-only attribute will have only a getPropertyName method. JavaBeans Example: Consider a student class with few properties: JavaBean properties are accessed through two methods in the JavaBean's implementation class: This method is called mutator.

This method is called accessor. It may have a number of properties which can be read or written. The attribute can be of any Java data type. It should be serializable and implement the Serializable interface.

It may have a number of "getter" and "setter" methods for the properties. A JavaBean property may be read. Following example shows its simple usage: The full syntax for the useBean tag is as follows: Once declared. The value of the id attribute may be any value as a long as it is a unique name among other useBean declarations in the same JSP. The property attribute is the name of the get or set methods that should be invoked.

Student First Name: Zara Student Last Name: Ali Student Age: Here is the full syntax: Accessing JavaBeans Properties: Following is a simple example to access the data using above syntax: Create "Hello" Tag: So let us create HelloTag class as follows: To write a customer tab you can simply extend SimpleTagSupport class and override the doTag method.

When a JSP page containing a custom tag is translated into a servlet. The JSP 2. The Web container then invokes those operations when the JSP page's servlet is executed. JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page just as you would the built-in tags you learned about in earlier chapter.

Hello Custom Tag! Accessing the Tag Body: You can include a message in the body of the tag as you have seen with standard tags. Finally create following tag library file: This is message body Custom Tag Attributes: You can use various attributes along with your custom tags. To accept an attribute value.

Now accordingly we need to change TLD file as follows: It would be worth to note that you can include following properties for an attribute: Property name Purpose The name element defines the name of an attribute.

This is custom tag Hope above example makes sense for you. It would be false for optional Common Attributes: There are two attributes that are common to all Action elements: the id attribute and the scope attribute. Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id.

The scope attribute has four possible values: a page, b request, c session, and d application. Following is the list of attributes associated with include action: Attribute page flush Description The relative URL of the page to be included.

The boolean attribute determines whether the included resource has its buffer flushed before it is included.

Example: Let us define following two files a date. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object. Following is the list of attributes associated with useBean action: Attribute class type beanName Description Designates the full package name of the bean. Specifies the type of the variable that will refer to the object. Gives the name of the bean as specified by the instantiate method of the java.

Beans class. Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid example related to these actions. The Bean must have been previously defined before this action. The Bean must have been previously defined. Indicates the property you want to set.

The value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored. The param attribute is the name of the request parameter whose value the property is to receive.

Recommended Posts:

You can't use both value and param, but it is permissible to use neither. The property attribute is the name of the Bean property to be retrieved. Hello JSP Example: Let us reuse following two files a date. This would display result something like as below. Here it discarded content from main page and displayed content from forwarded page only. If the needed plugin is not present, it downloads the plugin and then executes the Java component.

The Java component can be either an Applet or a JavaBean. The plugin action has several attributes that correspond to common HTML tags used to format Java components.

The word dynamically is important, because it means that the XML elements can be generated at request time rather than statically at compile time. JSP Implicit Objects are also called predefined variables. HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.

We would see complete set of methods associated with request object in coming chapter: JSP - Client Request. HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client. The response object also defines the interfaces that deal with creating new HTTP headers.

We would see complete set of methods associated with response object in coming chapter: JSP - Server Response.

The out Object: The out implicit object is an instance of a javax. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression. Ignored by the JSP engine. An HTML comment. Ignored by the browser. A single quote in an attribute that uses single quotes. A double quote in an attribute that uses double quotes. Includes a file during the translation phase.

Defines dynamically defined XML element's body. Use to write template text in JSP pages and documents. These variables are: Objects request response out session application config pageContext page Exception Description This is the HttpServletRequest object associated with the request.

This is the HttpServletResponse object associated with the response to the client. This is the PrintWriter object used to send output to the client. This is the HttpSession object associated with the request. This is the ServletContext object associated with application context. This is the ServletConfig object associated with the page. This encapsulates use of server-specific features like higher performance JspWriters.

This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. The Exception object allows the exception data to be accessed by designated JSP. Decision-Making Statements: The if Loop Statements: You can also use three basic types of looping blocks in Java: for, while,and dowhile blocks in your JSP programming.

Following table give a list of all the operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Null: null I will consider XML formatted file hibernate. Most of the properties take their default values and it is not required to specify them in the property file unless it is really required.

This file is kept in the root directory of your application's classpath. A JSP directive affects the overall structure of the servlet class. Declares a tag library, containing custom actions, used in the page The page Directive: The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page.

By convention, page directives are coded at the top of the JSP page. Controls the behavior of the servlet output buffer. Defines the character encoding scheme. Specifies a superclass that the generated servlet must extend Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes.

Defines a string that can be accessed with the servlet's getServletInfo method. Defines the threading model for the generated servlet.

Defines the programming language used in the JSP page. Determines if scripting elements are allowed for use. Check more detail related to all the above attributes at Page Directive. The include Directive: The include directive is used to includes a file during the translation phase.The javax. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.

You can't use both value and param, but it is permissible to use neither. Syed Shah. HttpServletResponse object. HttpSession getSession Returns the current session associated with this request. The boolean attribute determines whether the included resource has its buffer flushed before it is included. Splits a string into an array of substrings.