SlideShare a Scribd company logo
Programming Simple Servlet
under Ubuntu GNU/Linux
Tushar B Kute
Nashik Linux Users Group
tushar@tusharkute.com
What can you build with Servlets?
• Search Engines
• E-Commerce Applications
• Shopping Carts
• Product Catalogs
• Intranet Applications
• Groupware Applications:
– bulletin boards
– file sharing
Servlets vs. CGI
• A Servlet does not run
in a separate process.
• A Servlet stays in
memory between
requests.
• A CGI program needs to
be loaded and started
for each CGI request.
• There is only a single
instance of a servlet
which answers all
requests concurrently.
Browser 1
Web
Server
Browser 2
Browser N
Perl 1
Perl 2
Perl N
Browser 1
Web
Server
Browser 2
Browser N
Servlet
• Performance
– The performance of servlets is superior to CGI because there is
no process creation for each client request.
– Each request is handled by the servlet container process.
– After a servlet has completed processing a request, it stays
resident in memory, waiting for another request.
• Portability
– Like other Java technologies, servlet applications are portable.
• Rapid development cycle
– As a Java technology, servlets have access to the rich Java
library that will help speed up the development process.
• Robustness
– Servlets are managed by the Java Virtual Machine.
– Don't need to worry about memory leak or garbage collection,
which helps you write robust applications.
• Widespread acceptance
– Java is a widely accepted technology.
Benefits of Java Servlets
• A servlet is a Java class that can be
loaded dynamically into and run by a special
web server.
• This servlet-aware web server, is known as
servlet container.
• Servlets interact with clients via a
request-response model based on HTTP.
• Therefore, a servlet container must support
HTTP as the protocol for client requests and
server responses.
• A servlet container also can support similar
protocols such as HTTPS (HTTP over SSL) for
secure transactions.
Definitions
Browser HTTP
Server
Static
Content
Servlet
Container
HTTP Request
HTTP Response
Servlet
Servlet Container Architecture
Receive
Request
is servlet
loaded?
is servlet
current?
Send
Response
Process Request
Load Servlet
Yes
Yes
No
No
How Servlets Work
Servlet APIs
• Every servlet must implement javax.servlet.Servlet
interface
• Most servlets implement the interface by extending
one of these classes
–javax.servlet.GenericServlet
–javax.servlet.http.HttpServlet
Generic Servlet & HTTP Servlet
GenericServletGenericServlet
service ( )Server
ClientClient
HTTPServletHTTPServlet
service ( )HTTP
Server
BrowserBrowser
request
response
doGet( )
doPost( )
request
response
Interface javax.servlet.Servlet
• The Servlet interface defines methods
– to initialize a servlet
– to receive and respond to client requests
– to destroy a servlet and its resources
– to get any startup information
– to return basic information about itself, such as its
author, version and copyright.
• Developers need to directly implement
this interface only if their servlets
cannot (or choose not to) inherit
from GenericServlet or HttpServlet.
Life
Cycle
Methods
• void init(ServletConfig config)
– Initializes the servlet.
• void service(ServletRequest req,
ServletResponse res)
– Carries out a single request from the client.
• void destroy()
– Cleans up whatever resources are being held (e.g., memory, file
handles, threads) and makes sure that any persistent state is
synchronized with the servlet's current in-memory state.
• ServletConfig getServletConfig()
– Returns a servlet config object, which contains any initialization
parameters and startup configuration for this servlet.
• String getServletInfo()
– Returns a string containing information about the servlet, such as its
author, version, and copyright.
GenericServlet - Methods
Initialization
init()
Service
service()
doGet()
doPost()
doDelete()
doHead()
doTrace()
doOptions()
Destruction
destroy()
Concurrent
Threads
of Execution
Servlet Life Cycle
HttpServlet - Methods
• void doGet (HttpServletRequest request,
HttpServletResponse response)
–handles GET requests
• void doPost (HttpServletRequest request,
HttpServletResponse response)
–handles POST requests
• void doPut (HttpServletRequest request,
HttpServletResponse response)
–handles PUT requests
• void doDelete (HttpServletRequest request,
HttpServletResponse response)
– handles DELETE requests
Servlet Request Objects
• provides client request information to a servlet.
• the servlet container creates a servlet request object and
passes it as an argument to the servlet's service method.
• the ServletRequest interface define methods to retrieve
data sent as client request:
–parameter name and values
– attributes
– input stream
• HTTPServletRequest extends the ServletRequest
interface to provide request information for HTTP
servlets
HttpServletRequest - Methods
Enumeration getParameterNames()
an Enumeration of String objects, each String
containing the name of a request parameter; or an
empty Enumeration if the request has no
parameters
java.lang.String[] getParameterValues (java.lang.String name)
Returns an array of String objects containing all of
the values the given request parameter has, or
null if the parameter does not exist.
java.lang.String getParameter (java.lang.String name)
Returns the value of a request parameter as a
String, or null if the parameter does not exist.
HttpServletRequest - Methods
Cookie[] getCookies()
Returns an array containing all of the Cookie objects
the client sent with this request.
java.lang.String getMethod()
Returns the name of the HTTP method with whichthi
request was made, for example, GET, POST, or PUT.
java.lang.String getQueryString()
Returns the query string that is contained in the
request URL after the path.
HttpSession getSession()
Returns the current session associated with this
request, or if the request does not have a session,
creates one.
Servlet Response Objects
• Defines an object to assist a servlet in
sending a response to the client.
• The servlet container creates a
ServletResponse object and passes it as
an argument to the servlet's service
method.
HttpServletResponse - Methods
java.io.PrintWriter getWriter()
Returns a PrintWriter object that can send
character text to the client
void setContentType (java.lang.String type)
Sets the content type of the response being sent
to the client. The content type may include the
type of character encoding used, for example,
text/html; charset=ISO-8859-4
int getBufferSize()
Returns the actual buffer size used for the
response
• Create a directory structure under Tomcat for your
application.
• Write the servlet source code.
• Compile your source code.
• deploy the servlet
• Run Tomcat
• Call your servlet from a web browser
Steps to Running a Servlet
Installation of Apache Tomcat7
• Servlets implement the
javax.servlet.Servlet interface.
• Because most servlets extend web servers
that use the HTTP protocol to interact
with clients, the most common way to
develop servlets is by specializing the
javax.servlet.http.HttpServlet class.
• The HttpServlet class implements the
Servlet interface by extending the
GenericServlet base class, and provides a
framework for handling the HTTP protocol.
• Its service() method supports standard
HTTP requests by dispatching each request
to a method designed to handle it.
Write the Servlet Code
Servlet Example
1: import java.io.*;
2: import javax.servlet.*;
3: import javax.servlet.http.*;
4:
5: public class MyServlet extends HttpServlet
6: {
7: protected void doGet(HttpServletRequest req,
8: HttpServletResponse res)
9: {
10: res.setContentType("text/html");
11: PrintWriter out = res.getWriter();
12: out.println( "<HTML><HEAD><TITLE> Hello You!” +
13: “</Title></HEAD>” +
14: “<Body> HelloWorld!!!</BODY></HTML>“ );
14: out.close();
16: }
17: }
An Example of Servlet (I)
Lines 1 to 3 import some packages which
contain many classes which are used by
the Servlet (almost every Servlet needs
classes from these packages).
The Servlet class is declared in line 5. Our
Servlet extends javax.servlet.http.HttpServlet,
the standard base class for HTTP Servlets.
In lines 7 through 16 HttpServlet's doGet
method is getting overridden
An Example of Servlet (II)
In line 12 we request a PrintWriter object to
write text to the response message.
In line 11 we use a method of the
HttpServletResponse object to set the content
type of the response that we are going to
send. All response headers must be set
before a PrintWriter or ServletOutputStream is
requested to write body data to the
response.
In lines 13 and 14 we use the PrintWriter to
write the text of type text/html (as specified
through the content type).
An Example of Servlet (III)
The PrintWriter gets closed in line 15 when
we are finished writing to it.
In lines 18 through 21 we override the
getServletInfo() method which is supposed to
return information about the Servlet, e.g.
the Servlet name, version, author and
copyright notice. This is not required for
the function of the HelloClientServlet but can
provide valuable information to the user of
a Servlet who sees the returned text in the
administration tool of the Web Server.
• Compile the Servlet class
•
•
• The resulting MyServlet.class file should go under
/var/lib/tomcat7/webapps/ROOT/WEB-INF/classes
Compile the Servlet
• In the Servlet container each
application is represented by a servlet
context
• each servlet context is identified by a
unique path prefix called context path
• The remaining path is used in the
selected context to find the specific
Servlet to run, following the rules
specified in the deployment descriptor.
Deploy the Servlet
• The deployment descriptor is a XML file
called web.xml that resides in the WEB-INF
directory within an application.
<web-app xmlns=http://java.sun.com/xml/ns/j2ee……>
<display-name>test</display-name>
<description>test example</description>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testing</servlet-name>
<url-pattern>/servlet/TestingServlet</url-pattern>
</servlet-mapping>
</web-app>
Deployment Descriptor
web.xml
web.xml
Start / Restart the Servlet Web Engine, Tomcat7
• To execute your Servlet, type the following URL in
the Browser’s address field:
• http://localhost/MyServlet
Run the Servlet
• By default, servlets written by
specializing the HttpServlet class can
have multiple threads concurrently
running its service() method.
• If you would like to have only a single
thread running a service method at a
time, then your servlet should also
implement the SingleThreadModel
interface.
– This does not involve writing any extra methods, merely
declaring that the servlet implements the interface.
Running service() on a single thread
public class SurveyServlet extends HttpServlet
implements SingleThreadModel
{
/* typical servlet code, with no threading concerns
* in the service method. No extra code for the
* SingleThreadModel interface. */
...
}
Example
Thank You
http://snashlug.wordpress.com

More Related Content

PDF
Tp n 4 linux
Amir Souissi
 
PPTX
Linux Device Driver’s
Rashmi Warghade
 
PPT
Linux - Introductions to Linux Operating System
Vibrant Technologies & Computers
 
PPTX
『例えば、PHPを避ける』以降PHPはどれだけ安全になったか
Hiroshi Tokumaru
 
PDF
XPDDS19: [ARM] OP-TEE Mediator in Xen - Volodymyr Babchuk, EPAM Systems
The Linux Foundation
 
PPSX
Install ubuntu
pramoddps
 
PDF
LinuxCon 2015 Linux Kernel Networking Walkthrough
Thomas Graf
 
PDF
5-CFT Composant Vital Infrastructure d\’échange
Jean-Claude Bellando
 
Tp n 4 linux
Amir Souissi
 
Linux Device Driver’s
Rashmi Warghade
 
Linux - Introductions to Linux Operating System
Vibrant Technologies & Computers
 
『例えば、PHPを避ける』以降PHPはどれだけ安全になったか
Hiroshi Tokumaru
 
XPDDS19: [ARM] OP-TEE Mediator in Xen - Volodymyr Babchuk, EPAM Systems
The Linux Foundation
 
Install ubuntu
pramoddps
 
LinuxCon 2015 Linux Kernel Networking Walkthrough
Thomas Graf
 
5-CFT Composant Vital Infrastructure d\’échange
Jean-Claude Bellando
 

What's hot (20)

PDF
6.5.1.2 packet tracer layer 2 security instructor
Salem Trabelsi
 
DOCX
Rapport tp openssl
Yacoubou Salifou Bouraima
 
PPTX
ARM LinuxのMMUはわかりにくい
wata2ki
 
PDF
Mininet introduction
Vipin Gupta
 
PDF
Travaux pratiques configuration du routage entre réseaux locaux virtuels
Mohamed Keita
 
PDF
室内空調シミュレーション手順書
murai1972
 
PPT
Système répartis avec RMI
Korteby Farouk
 
PDF
クラウドコラボレーションサーバ「Collabora Online」を構築してみた
Shinji Enoki
 
PDF
Fun with PRB, VRFs and NetNS on Linux - What is it, how does it work, what ca...
Maximilan Wilhelm
 
PDF
DevConf 2014 Kernel Networking Walkthrough
Thomas Graf
 
PDF
Cours eigrp i pv4 et ipv6
EL AMRI El Hassan
 
PDF
Linux Internals - Interview essentials - 1.0
Emertxe Information Technologies Pvt Ltd
 
PDF
ARM Trusted FirmwareのBL31を単体で使う!
Mr. Vengineer
 
PDF
第二回CTF勉強会資料
Asuka Nakajima
 
PDF
2014年10月江戸前セキュリティ勉強会資料 -セキュリティ技術者になるには-
Asuka Nakajima
 
PDF
#ljstudy KVM勉強会
Etsuji Nakai
 
PPTX
Hibernate
Ghazouani Mahdi
 
PPTX
545人のインフラを支えたNOCチーム!
Masayuki Kobayashi
 
DOCX
blackberry os 10
Aashu Singh
 
PPTX
Cortex-M0プロセッサから自作して Lチカをやってみた
Junichi Akita
 
6.5.1.2 packet tracer layer 2 security instructor
Salem Trabelsi
 
Rapport tp openssl
Yacoubou Salifou Bouraima
 
ARM LinuxのMMUはわかりにくい
wata2ki
 
Mininet introduction
Vipin Gupta
 
Travaux pratiques configuration du routage entre réseaux locaux virtuels
Mohamed Keita
 
室内空調シミュレーション手順書
murai1972
 
Système répartis avec RMI
Korteby Farouk
 
クラウドコラボレーションサーバ「Collabora Online」を構築してみた
Shinji Enoki
 
Fun with PRB, VRFs and NetNS on Linux - What is it, how does it work, what ca...
Maximilan Wilhelm
 
DevConf 2014 Kernel Networking Walkthrough
Thomas Graf
 
Cours eigrp i pv4 et ipv6
EL AMRI El Hassan
 
Linux Internals - Interview essentials - 1.0
Emertxe Information Technologies Pvt Ltd
 
ARM Trusted FirmwareのBL31を単体で使う!
Mr. Vengineer
 
第二回CTF勉強会資料
Asuka Nakajima
 
2014年10月江戸前セキュリティ勉強会資料 -セキュリティ技術者になるには-
Asuka Nakajima
 
#ljstudy KVM勉強会
Etsuji Nakai
 
Hibernate
Ghazouani Mahdi
 
545人のインフラを支えたNOCチーム!
Masayuki Kobayashi
 
blackberry os 10
Aashu Singh
 
Cortex-M0プロセッサから自作して Lチカをやってみた
Junichi Akita
 
Ad

Viewers also liked (14)

PPT
Servlet ppt by vikas jagtap
Vikas Jagtap
 
PPTX
Hibernate Training Session1
Asad Khan
 
PPT
Hibernate
husnara mohammad
 
PPTX
JSON-(JavaScript Object Notation)
Skillwise Group
 
PPTX
Introduction to AJAX and DWR
SweNz FixEd
 
PPTX
Spring boot for buidling microservices
Nilanjan Roy
 
PPT
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
PPT
Java & J2EE Struts with Hibernate Framework
Mohit Belwal
 
PDF
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Fahad Golra
 
PPSX
JDBC: java DataBase connectivity
Tanmoy Barman
 
PDF
Spring Framework - Core
Dzmitry Naskou
 
PPT
Java servlet life cycle - methods ppt
kamal kotecha
 
PPT
Java Servlets
Nitin Pai
 
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Hibernate Training Session1
Asad Khan
 
Hibernate
husnara mohammad
 
JSON-(JavaScript Object Notation)
Skillwise Group
 
Introduction to AJAX and DWR
SweNz FixEd
 
Spring boot for buidling microservices
Nilanjan Roy
 
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
Java & J2EE Struts with Hibernate Framework
Mohit Belwal
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Fahad Golra
 
JDBC: java DataBase connectivity
Tanmoy Barman
 
Spring Framework - Core
Dzmitry Naskou
 
Java servlet life cycle - methods ppt
kamal kotecha
 
Java Servlets
Nitin Pai
 
Ad

Similar to Java Servlet Programming under Ubuntu Linux by Tushar B Kute (20)

PPT
Servlets
Sasidhar Kothuru
 
PPT
JAVA Servlets
deepak kumar
 
PDF
Java Servlets.pdf
Arumugam90
 
PPT
1 java servlets and jsp
Ankit Minocha
 
PPTX
Chapter 3 servlet & jsp
Jafar Nesargi
 
PPTX
Http Server Programming in JAVA - Handling http requests and responses
bharathiv53
 
PPT
Java servlets
lopjuan
 
PPT
Servlet (1) also contains code to create it.ppt
juhishrivastava25
 
ODP
Servlets
ramesh kumar
 
PPTX
Wt unit 3
team11vgnt
 
PPT
Servlets
Manav Prasad
 
PPTX
UNIT-3 Servlet
ssbd6985
 
PPT
Servlet.ppt
MouDhara1
 
PPT
Servlet.ppt
kstalin2
 
PPT
Servlet1.ppt
KhushalChoudhary14
 
PPT
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
shubhangimalas1
 
PPT
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
tahirnaquash2
 
PPT
Java Servlets
BG Java EE Course
 
DOC
Java Servlets & JSP
Manjunatha RK
 
DOC
Unit5 servlets
Praveen Yadav
 
JAVA Servlets
deepak kumar
 
Java Servlets.pdf
Arumugam90
 
1 java servlets and jsp
Ankit Minocha
 
Chapter 3 servlet & jsp
Jafar Nesargi
 
Http Server Programming in JAVA - Handling http requests and responses
bharathiv53
 
Java servlets
lopjuan
 
Servlet (1) also contains code to create it.ppt
juhishrivastava25
 
Servlets
ramesh kumar
 
Wt unit 3
team11vgnt
 
Servlets
Manav Prasad
 
UNIT-3 Servlet
ssbd6985
 
Servlet.ppt
MouDhara1
 
Servlet.ppt
kstalin2
 
Servlet1.ppt
KhushalChoudhary14
 
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
shubhangimalas1
 
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
tahirnaquash2
 
Java Servlets
BG Java EE Course
 
Java Servlets & JSP
Manjunatha RK
 
Unit5 servlets
Praveen Yadav
 

More from Tushar B Kute (20)

PDF
ॲलन ट्युरिंग: कृत्रिम बुद्धिमत्तेचा अग्रदूत - लेखक: तुषार भ. कुटे.pdf
Tushar B Kute
 
PDF
Apache Pig: A big data processor
Tushar B Kute
 
PDF
01 Introduction to Android
Tushar B Kute
 
PDF
Ubuntu OS and it's Flavours
Tushar B Kute
 
PDF
Install Drupal in Ubuntu by Tushar B. Kute
Tushar B Kute
 
PDF
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Tushar B Kute
 
PDF
Share File easily between computers using sftp
Tushar B Kute
 
PDF
Signal Handling in Linux
Tushar B Kute
 
PDF
Implementation of FIFO in Linux
Tushar B Kute
 
PDF
Implementation of Pipe in Linux
Tushar B Kute
 
PDF
Basic Multithreading using Posix Threads
Tushar B Kute
 
PDF
Part 04 Creating a System Call in Linux
Tushar B Kute
 
PDF
Part 03 File System Implementation in Linux
Tushar B Kute
 
PDF
Part 02 Linux Kernel Module Programming
Tushar B Kute
 
PDF
Part 01 Linux Kernel Compilation (Ubuntu)
Tushar B Kute
 
PDF
Open source applications softwares
Tushar B Kute
 
PDF
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Tushar B Kute
 
PDF
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Tushar B Kute
 
PDF
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Tushar B Kute
 
PDF
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 
ॲलन ट्युरिंग: कृत्रिम बुद्धिमत्तेचा अग्रदूत - लेखक: तुषार भ. कुटे.pdf
Tushar B Kute
 
Apache Pig: A big data processor
Tushar B Kute
 
01 Introduction to Android
Tushar B Kute
 
Ubuntu OS and it's Flavours
Tushar B Kute
 
Install Drupal in Ubuntu by Tushar B. Kute
Tushar B Kute
 
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Tushar B Kute
 
Share File easily between computers using sftp
Tushar B Kute
 
Signal Handling in Linux
Tushar B Kute
 
Implementation of FIFO in Linux
Tushar B Kute
 
Implementation of Pipe in Linux
Tushar B Kute
 
Basic Multithreading using Posix Threads
Tushar B Kute
 
Part 04 Creating a System Call in Linux
Tushar B Kute
 
Part 03 File System Implementation in Linux
Tushar B Kute
 
Part 02 Linux Kernel Module Programming
Tushar B Kute
 
Part 01 Linux Kernel Compilation (Ubuntu)
Tushar B Kute
 
Open source applications softwares
Tushar B Kute
 
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Tushar B Kute
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Tushar B Kute
 
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Tushar B Kute
 
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 

Recently uploaded (20)

PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Software Development Methodologies in 2025
KodekX
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Doc9.....................................
SofiaCollazos
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 

Java Servlet Programming under Ubuntu Linux by Tushar B Kute

  • 1. Programming Simple Servlet under Ubuntu GNU/Linux Tushar B Kute Nashik Linux Users Group [email protected]
  • 2. What can you build with Servlets? • Search Engines • E-Commerce Applications • Shopping Carts • Product Catalogs • Intranet Applications • Groupware Applications: – bulletin boards – file sharing
  • 3. Servlets vs. CGI • A Servlet does not run in a separate process. • A Servlet stays in memory between requests. • A CGI program needs to be loaded and started for each CGI request. • There is only a single instance of a servlet which answers all requests concurrently. Browser 1 Web Server Browser 2 Browser N Perl 1 Perl 2 Perl N Browser 1 Web Server Browser 2 Browser N Servlet
  • 4. • Performance – The performance of servlets is superior to CGI because there is no process creation for each client request. – Each request is handled by the servlet container process. – After a servlet has completed processing a request, it stays resident in memory, waiting for another request. • Portability – Like other Java technologies, servlet applications are portable. • Rapid development cycle – As a Java technology, servlets have access to the rich Java library that will help speed up the development process. • Robustness – Servlets are managed by the Java Virtual Machine. – Don't need to worry about memory leak or garbage collection, which helps you write robust applications. • Widespread acceptance – Java is a widely accepted technology. Benefits of Java Servlets
  • 5. • A servlet is a Java class that can be loaded dynamically into and run by a special web server. • This servlet-aware web server, is known as servlet container. • Servlets interact with clients via a request-response model based on HTTP. • Therefore, a servlet container must support HTTP as the protocol for client requests and server responses. • A servlet container also can support similar protocols such as HTTPS (HTTP over SSL) for secure transactions. Definitions
  • 6. Browser HTTP Server Static Content Servlet Container HTTP Request HTTP Response Servlet Servlet Container Architecture
  • 7. Receive Request is servlet loaded? is servlet current? Send Response Process Request Load Servlet Yes Yes No No How Servlets Work
  • 8. Servlet APIs • Every servlet must implement javax.servlet.Servlet interface • Most servlets implement the interface by extending one of these classes –javax.servlet.GenericServlet –javax.servlet.http.HttpServlet
  • 9. Generic Servlet & HTTP Servlet GenericServletGenericServlet service ( )Server ClientClient HTTPServletHTTPServlet service ( )HTTP Server BrowserBrowser request response doGet( ) doPost( ) request response
  • 10. Interface javax.servlet.Servlet • The Servlet interface defines methods – to initialize a servlet – to receive and respond to client requests – to destroy a servlet and its resources – to get any startup information – to return basic information about itself, such as its author, version and copyright. • Developers need to directly implement this interface only if their servlets cannot (or choose not to) inherit from GenericServlet or HttpServlet. Life Cycle Methods
  • 11. • void init(ServletConfig config) – Initializes the servlet. • void service(ServletRequest req, ServletResponse res) – Carries out a single request from the client. • void destroy() – Cleans up whatever resources are being held (e.g., memory, file handles, threads) and makes sure that any persistent state is synchronized with the servlet's current in-memory state. • ServletConfig getServletConfig() – Returns a servlet config object, which contains any initialization parameters and startup configuration for this servlet. • String getServletInfo() – Returns a string containing information about the servlet, such as its author, version, and copyright. GenericServlet - Methods
  • 13. HttpServlet - Methods • void doGet (HttpServletRequest request, HttpServletResponse response) –handles GET requests • void doPost (HttpServletRequest request, HttpServletResponse response) –handles POST requests • void doPut (HttpServletRequest request, HttpServletResponse response) –handles PUT requests • void doDelete (HttpServletRequest request, HttpServletResponse response) – handles DELETE requests
  • 14. Servlet Request Objects • provides client request information to a servlet. • the servlet container creates a servlet request object and passes it as an argument to the servlet's service method. • the ServletRequest interface define methods to retrieve data sent as client request: –parameter name and values – attributes – input stream • HTTPServletRequest extends the ServletRequest interface to provide request information for HTTP servlets
  • 15. HttpServletRequest - Methods Enumeration getParameterNames() an Enumeration of String objects, each String containing the name of a request parameter; or an empty Enumeration if the request has no parameters java.lang.String[] getParameterValues (java.lang.String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. java.lang.String getParameter (java.lang.String name) Returns the value of a request parameter as a String, or null if the parameter does not exist.
  • 16. HttpServletRequest - Methods Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this request. java.lang.String getMethod() Returns the name of the HTTP method with whichthi request was made, for example, GET, POST, or PUT. java.lang.String getQueryString() Returns the query string that is contained in the request URL after the path. HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one.
  • 17. Servlet Response Objects • Defines an object to assist a servlet in sending a response to the client. • The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.
  • 18. HttpServletResponse - Methods java.io.PrintWriter getWriter() Returns a PrintWriter object that can send character text to the client void setContentType (java.lang.String type) Sets the content type of the response being sent to the client. The content type may include the type of character encoding used, for example, text/html; charset=ISO-8859-4 int getBufferSize() Returns the actual buffer size used for the response
  • 19. • Create a directory structure under Tomcat for your application. • Write the servlet source code. • Compile your source code. • deploy the servlet • Run Tomcat • Call your servlet from a web browser Steps to Running a Servlet
  • 21. • Servlets implement the javax.servlet.Servlet interface. • Because most servlets extend web servers that use the HTTP protocol to interact with clients, the most common way to develop servlets is by specializing the javax.servlet.http.HttpServlet class. • The HttpServlet class implements the Servlet interface by extending the GenericServlet base class, and provides a framework for handling the HTTP protocol. • Its service() method supports standard HTTP requests by dispatching each request to a method designed to handle it. Write the Servlet Code
  • 22. Servlet Example 1: import java.io.*; 2: import javax.servlet.*; 3: import javax.servlet.http.*; 4: 5: public class MyServlet extends HttpServlet 6: { 7: protected void doGet(HttpServletRequest req, 8: HttpServletResponse res) 9: { 10: res.setContentType("text/html"); 11: PrintWriter out = res.getWriter(); 12: out.println( "<HTML><HEAD><TITLE> Hello You!” + 13: “</Title></HEAD>” + 14: “<Body> HelloWorld!!!</BODY></HTML>“ ); 14: out.close(); 16: } 17: }
  • 23. An Example of Servlet (I) Lines 1 to 3 import some packages which contain many classes which are used by the Servlet (almost every Servlet needs classes from these packages). The Servlet class is declared in line 5. Our Servlet extends javax.servlet.http.HttpServlet, the standard base class for HTTP Servlets. In lines 7 through 16 HttpServlet's doGet method is getting overridden
  • 24. An Example of Servlet (II) In line 12 we request a PrintWriter object to write text to the response message. In line 11 we use a method of the HttpServletResponse object to set the content type of the response that we are going to send. All response headers must be set before a PrintWriter or ServletOutputStream is requested to write body data to the response. In lines 13 and 14 we use the PrintWriter to write the text of type text/html (as specified through the content type).
  • 25. An Example of Servlet (III) The PrintWriter gets closed in line 15 when we are finished writing to it. In lines 18 through 21 we override the getServletInfo() method which is supposed to return information about the Servlet, e.g. the Servlet name, version, author and copyright notice. This is not required for the function of the HelloClientServlet but can provide valuable information to the user of a Servlet who sees the returned text in the administration tool of the Web Server.
  • 26. • Compile the Servlet class • • • The resulting MyServlet.class file should go under /var/lib/tomcat7/webapps/ROOT/WEB-INF/classes Compile the Servlet
  • 27. • In the Servlet container each application is represented by a servlet context • each servlet context is identified by a unique path prefix called context path • The remaining path is used in the selected context to find the specific Servlet to run, following the rules specified in the deployment descriptor. Deploy the Servlet
  • 28. • The deployment descriptor is a XML file called web.xml that resides in the WEB-INF directory within an application. <web-app xmlns=http://java.sun.com/xml/ns/j2ee……> <display-name>test</display-name> <description>test example</description> <servlet> <servlet-name>Testing</servlet-name> <servlet-class>TestingServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Testing</servlet-name> <url-pattern>/servlet/TestingServlet</url-pattern> </servlet-mapping> </web-app> Deployment Descriptor
  • 31. Start / Restart the Servlet Web Engine, Tomcat7
  • 32. • To execute your Servlet, type the following URL in the Browser’s address field: • http://localhost/MyServlet Run the Servlet
  • 33. • By default, servlets written by specializing the HttpServlet class can have multiple threads concurrently running its service() method. • If you would like to have only a single thread running a service method at a time, then your servlet should also implement the SingleThreadModel interface. – This does not involve writing any extra methods, merely declaring that the servlet implements the interface. Running service() on a single thread
  • 34. public class SurveyServlet extends HttpServlet implements SingleThreadModel { /* typical servlet code, with no threading concerns * in the service method. No extra code for the * SingleThreadModel interface. */ ... } Example