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

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

SERVLETS INTERVIEW QUESTIONS

Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.

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

Web based Applications, Tomcat and Servlets - Lab 3 -

UNIT-V. Web Servers: Tomcat Server Installation:

Before you start with this tutorial, you need to know basic Java programming.

This tutorial will take you through simple and practical approaches while learning AOP framework provided by Spring.

Adobe Flex Tutorial i

This tutorial has been prepared for beginners to help them understand the basic functionalities of Gulp.

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

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

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

jmeter is an open source testing software. It is 100% pure Java application for load and performance testing.

JAVA SERVLET. Server-side Programming INTRODUCTION

Advanced Internet Technology Lab # 4 Servlets

Servlet Fudamentals. Celsina Bignoli

Servlet Basics. Agenda

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

Java Servlets. Preparing your System

Module 4: SERVLET and JSP

Session 8. Introduction to Servlets. Semester Project

This is a brief tutorial that explains how to make use of Sqoop in Hadoop ecosystem.

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

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

The Servlet Life Cycle

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

Java E-Commerce Martin Cooke,

This tutorial is designed for all Java enthusiasts who want to learn document type detection and content extraction using Apache Tika.

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

Servlets and JSP (Java Server Pages)

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

Parrot is a virtual machine designed to efficiently compile and execute bytecode for interpreted languages.

This tutorial is designed for software programmers who would like to learn the basics of ASP.NET Core from scratch.

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

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

This tutorial explains how you can use Gradle as a build automation tool for Java as well as Groovy projects.

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

Advanced Java Programming

This tutorial explains the key concepts of Web Dynpro with relevant screenshots for better understanding.

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

Table of Contents. Introduction... xxi

Scalable Vector Graphics commonly known as SVG is a XML based format to draw vector images. It is used to draw twodimentional vector images.

AJP. CHAPTER 5: SERVLET -20 marks

This tutorial provides a basic understanding of how to generate professional reports using Pentaho Report Designer.

This is an introductory tutorial designed for beginners to help them understand the basics of Radius.

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

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.

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets

Session 9. Introduction to Servlets. Lecture Objectives

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

Unit 4 - Servlet. Servlet. Advantage of Servlet

Before you start proceeding with this tutorial, we are assuming that you are already aware about the basics of Web development.

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

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

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

Memcached is an open source, high-performance, distributed memory object caching system.

This tutorial will help you in understanding IPv4 and its associated terminologies along with appropriate references and examples.

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

Questions and Answers

JdbcResultSet.java. import java.sql.*;

Java Training For Six Weeks

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

You must have a basic understanding of GNU/Linux operating system and shell scripting.

This tutorial also elaborates on other related methodologies like Agile, RAD and Prototyping.

About the Tutorial. Audience. Prerequisites. Copyright and Disclaimer. PySpark

Advanced Web Technology

1. Introduction. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

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

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

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction

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

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

COPYRIGHTED MATERIAL

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

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

Servlets. An extension of a web server runs inside a servlet container

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

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer ASP.NET WP

This tutorial has been prepared for beginners to help them understand the simple but effective SEO characteristics.

About the Tutorial. Audience. Prerequisites. Copyright and Disclaimer. Logstash

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

Chapter 2 FEATURES AND FACILITIES. SYS-ED/ Computer Education Techniques, Inc.

AIML - QUICK GUIDE AIML - INTRODUCTION

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

Oracle 10g: Build J2EE Applications

Servlets Basic Operations

Servlet Performance and Apache JServ

Introduction to Java. Lecture 1 COP 3252 Summer May 16, 2017

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

EUSurvey Installation Guide

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

SYLLABUS JAVA COURSE DETAILS. DURATION: 60 Hours. With Live Hands-on Sessions J P I N F O T E C H

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

Outline. Introduction to Java. What Is Java? History. Java 2 Platform. Java 2 Platform Standard Edition. Introduction Java 2 Platform

This is an introductory tutorial, which covers the basics of Jython and explains how to handle its various modules and sub-modules.

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java.

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

Transcription:

About the Tutorial Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets 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 Servlets to develop your web based applications in simple and easy steps. Audience This tutorial is designed for Java programmers with a need to understand the Java Servlets framework and its APIs. After completing this tutorial you will find yourself at a moderate level of expertise in using Java Servlets from where you can take yourself to next levels. Prerequisites We assume you have good understanding of the Java programming language. It will be great if you have a basic understanding of web application and how internet works. Copyright & Disclaimer Copyright 2015 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of the contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness, or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com i

Table of Contents About the Tutorial... i Audience... i Prerequisites... i Table of Content... ii 1. SERVLETS OVERVIEW... 1 Servlets Tasks... 2 Servlets Packages... 2 What is Next?... 2 2. SERVLETS ENVIRONMENT SETUP... 3 Setting up Java Development Kit... 3 Setting up Web Server: Tomcat... 3 Setting Up the CLASSPATH... 5 3. SERVLETS LIFE CYCLE... 7 The init() Method... 7 The service() Method... 7 The doget() Method... 8 The dopost() Method... 8 The destroy() Method... 8 Architecture Diagram... 9 4. SERVLETS EXAMPLES... 10 Sample Code... 10 Compiling a Servlet... 11 Servlet Deployment... 11 ii

5. SERVLETS FORM DATA... 13 GET Method... 13 POST Method... 13 Reading Form Data using Servlet... 13 GET Method Example using URL... 14 GET Method Example Using Form... 16 POST Method Example Using Form... 16 Passing Checkbox Data to Servlet Program... 18 Reading All Form Parameters... 20 6. SERVLETS CLIENT HTTP REQUEST... 24 Methods to read HTTP Header... 25 HTTP Header Request Example... 27 7. SERVLETS SERVER HTTP RESPONSE... 30 Methods to Set HTTP Response Header... 32 HTTP Header Response Example... 33 8. SERVLETS HTTP STATUS CODES... 36 Methods to Set HTTP Status Code... 39 HTTP Status Code Example... 39 9. SERVLETS WRITING FILTERS... 41 Servlet Filter Methods... 41 Servlet Filter Example... 42 Servlet Filter Mapping in Web.xml... 43 Using Multiple Filters... 43 Filters Application Order... 44 iii

10. SERVLETS EXCEPTION HANDLING... 46 web.xml Configuration... 46 Request Attributes Errors/Exceptions... 47 Error Handler Servlet Example... 48 11. SERVLETS COOKIES HANDLING... 52 The Anatomy of a Cookie... 52 Servlet Cookies Methods... 53 Setting Cookies with Servlet... 54 Reading Cookies with Servlet... 56 Delete Cookies with Servlet... 58 12. SERVLETS SESSION TRACKING... 61 Cookies... 61 Hidden Form Fields... 61 URL Rewriting... 61 The HttpSession Object... 62 Session Tracking Example... 63 Deleting Session Data... 66 13. SERVLETS DATABASE ACCESS... 68 Create Table... 68 Create Data Records... 69 Accessing a Database... 69 14. SERVLETS FILE UPLOADING... 73 Creating a File Upload Form... 73 Writing Backend Servlet... 74 Compile and Running Servlet... 78 iv

15. SERVLET HANDLING DATE... 79 Getting Current Date & Time... 80 Date Comparison... 81 Date Formatting using SimpleDateFormat... 81 Simple DateFormat Format Codes... 82 16. SERVLETS PAGE REDIRECTION... 84 17. SERVLETS HITS COUNTER... 86 Hit Counter for a Web Page... 86 18. SERVLETS AUTO PAGE REFRESH... 91 Auto Page Refresh Example... 91 19. SERVLETS SENDING EMAIL... 94 Send a Simple Email... 94 Send an HTML Email... 97 Send Attachment in Email... 99 User Authentication Part... 102 20. SERVLETS PACKAGING... 103 Creating Servlets in Packages... 103 Compiling Servlets in Packages... 104 Packaged Servlet Deployment... 105 21. SERVLETS DEBUGGING... 106 System.out.println()... 106 Message Logging... 106 Using JDB Debugger... 107 Using Comments... 108 Client and Server Headers... 108 v

Important Debugging Tips... 108 22. SERVLETS INTERNATIONALIZATION... 110 Detecting Locale... 110 Languages Setting... 112 Locale Specific Dates... 113 Locale Specific Currency... 114 Locale Specific Percentage... 115 23. SERVLET ANNOTATIONS... 117 @WebServlet... 118 @WebInitParam... 119 @Webfilter... 121 vi

Servlets Overview Java Servlets 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. 1

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. What is Next? I would take you step by step to set up your environment to start with Servlets. So fasten your belt for a nice drive with Servlets. I'm sure you are going to enjoy this tutorial very much. 2

Servlets Environment Setup Java Servlets A development environment is where you would develop your Servlet, test them and finally run them. Like any other Java program, you need to compile a servlet by using the Java compiler javac and after compilation the servlet application, it would be deployed in a configured environment to test and run. This development environment setup involves the following steps: Setting up Java Development Kit This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately. You can download SDK from Oracle's Java site: Java SE Downloads. Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in C:\jdk1.8.0_65, you would put the following line in your C:\autoexec.bat file. set PATH=C:\jdk1.8.0_65\bin;%PATH% set JAVA_HOME=C:\jdk1.8.0_65 Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.8.0_65 and you use the C shell, you would put the following into your.cshrc file. setenv PATH /usr/local/jdk1.8.0_65/bin:$path setenv JAVA_HOME /usr/local/jdk1.8.0_65 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. Setting up Web Server: Tomcat A number of Web Servers that support servlets are available in the market. Some web servers are freely downloadable and Tomcat is one of them. 3

Apache Tomcat is an open source software implementation of the Java Servlet and Java Server Pages technologies and can act as a standalone server for testing servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine: Download latest version of Tomcat from http://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-8.0.28 on windows, or /usr/local/apache-tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on windows machine: %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-8.0.28\bin\startup.bat Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine: $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-8.0.28/bin/startup.sh After startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result: 4

Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org Tomcat can be stopped by executing the following commands on windows machine: C:\apache-tomcat-8.0.28\bin\shutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine: /usr/local/apache-tomcat-8.0.28/bin/shutdown.sh Setting Up the CLASSPATH Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler. If you are running Windows, you need to put the following lines in your C:\autoexec.bat file. set CATALINA=C:\apache-tomcat-8.0.28 set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH% Alternatively, on Windows NT/2000/XP, you could go to My Computer -> Properties -> Advanced -> Environment Variables. Then, you would update the CLASSPATH value and press the OK button. On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your.cshrc file. setenv CATALINA=/usr/local/apache-tomcat-8.0.28 5

setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH NOTE: Assuming that your development directory is C:\ServletDevel (Windows) or /usr/servletdevel (Unix) then you would need to add these directories as well in CLASSPATH in similar way as you have added above. 6

Servlets Life Cycle Java Servlets A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet The servlet is initialized by calling the init () method. The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM. Now let us discuss the life cycle methods in detail. The init() Method The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets. The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started. When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doget or dopost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet. The init method definition looks like this: public void init() throws ServletException { } // Initialization code... The service() Method The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doget, dopost, doput, dodelete, etc. methods as appropriate. 7

Here is the signature of this method: public void service(servletrequest request, } ServletResponse response) throws ServletException, IOException{ The service () method is called by the container and service method invokes doge, dopost, doput, dodelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doget() or dopost() depending on what type of request you receive from the client. The doget() and dopost() are most frequently used methods with in each service request. Here is the signature of these two methods. The doget() Method A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doget() method. public void doget(httpservletrequest request, } HttpServletResponse response) throws ServletException, IOException { // Servlet code The dopost() Method A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by dopost() method. public void dopost(httpservletrequest request, } HttpServletResponse response) throws ServletException, IOException { // Servlet code The destroy() Method The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. 8

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this: public void destroy() { } // Finalization code... Architecture Diagram The following figure depicts a typical servlet life-cycle scenario. First the HTTP requests coming to the server are delegated to the servlet container. The servlet container loads the servlet before invoking the service() method. Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet. 9

End of ebook preview If you liked what you saw Buy it from our store @ https://store.tutorialspoint.com 10