SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Data link layer (Unit 2).pdf
Data link layer (Unit 2).pdfData link layer (Unit 2).pdf
Data link layer (Unit 2).pdfBharatiPatelPhDStude
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysMartin Chapman
 
Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptxMargaret Mary
 
Running IBM MQ in the Cloud
Running IBM MQ in the CloudRunning IBM MQ in the Cloud
Running IBM MQ in the CloudRobert Parker
 

Was ist angesagt? (6)

Data link layer (Unit 2).pdf
Data link layer (Unit 2).pdfData link layer (Unit 2).pdf
Data link layer (Unit 2).pdf
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptx
 
Object oriented analysis and design unit- i
Object oriented analysis and design unit- iObject oriented analysis and design unit- i
Object oriented analysis and design unit- i
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Running IBM MQ in the Cloud
Running IBM MQ in the CloudRunning IBM MQ in the Cloud
Running IBM MQ in the Cloud
 

Andere mochten auch

Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1Asad Khan
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)Skillwise Group
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWRSweNz FixEd
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservicesNilanjan Roy
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkMohit Belwal
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)Fahad Golra
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 

Andere mochten auch (14)

Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
 
Hibernate
HibernateHibernate
Hibernate
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWR
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Json
JsonJson
Json
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

Ă„hnlich wie Build Simple Servlets Ubuntu

JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servletsdeepak kumar
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesbharathiv53
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptMouDhara1
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overviewramya marichamy
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIPRIYADARSINISK
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Liit tyit sem 5 enterprise java unit 1 notes 2018
Liit tyit sem 5 enterprise java  unit 1 notes 2018 Liit tyit sem 5 enterprise java  unit 1 notes 2018
Liit tyit sem 5 enterprise java unit 1 notes 2018 tanujaparihar
 
Java servlets
Java servletsJava servlets
Java servletsyuvarani p
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 

Ă„hnlich wie Build Simple Servlets Ubuntu (20)

JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Servlets
ServletsServlets
Servlets
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Servlets
ServletsServlets
Servlets
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Servlets
ServletsServlets
Servlets
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Liit tyit sem 5 enterprise java unit 1 notes 2018
Liit tyit sem 5 enterprise java  unit 1 notes 2018 Liit tyit sem 5 enterprise java  unit 1 notes 2018
Liit tyit sem 5 enterprise java unit 1 notes 2018
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Servlet
Servlet Servlet
Servlet
 

Mehr von Tushar B Kute

Apache Pig: A big data processor
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processorTushar B Kute
 
01 Introduction to Android
01 Introduction to Android01 Introduction to Android
01 Introduction to AndroidTushar B Kute
 
Ubuntu OS and it's Flavours
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's FlavoursTushar B Kute
 
Install Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteTushar B Kute
 
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteTushar B Kute
 
Share File easily between computers using sftp
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftpTushar B Kute
 
Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in LinuxTushar B Kute
 
Implementation of FIFO in Linux
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in LinuxTushar B Kute
 
Implementation of Pipe in Linux
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in LinuxTushar B Kute
 
Basic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsTushar B Kute
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxTushar B Kute
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxTushar B Kute
 
Part 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingTushar B Kute
 
Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Tushar B Kute
 
Open source applications softwares
Open source applications softwaresOpen source applications softwares
Open source applications softwaresTushar B Kute
 
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Tushar B Kute
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteTushar B Kute
 
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTushar B Kute
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 

Mehr von Tushar B Kute (20)

Apache Pig: A big data processor
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processor
 
01 Introduction to Android
01 Introduction to Android01 Introduction to Android
01 Introduction to Android
 
Ubuntu OS and it's Flavours
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's Flavours
 
Install Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. Kute
 
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. Kute
 
Share File easily between computers using sftp
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftp
 
Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in Linux
 
Implementation of FIFO in Linux
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in Linux
 
Implementation of Pipe in Linux
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in Linux
 
Basic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix Threads
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
 
Part 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module Programming
 
Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)
 
Open source applications softwares
Open source applications softwaresOpen source applications softwares
Open source applications softwares
 
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
 
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrc
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 

KĂĽrzlich hochgeladen

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĂşjo
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

KĂĽrzlich hochgeladen (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Build Simple Servlets Ubuntu

  • 1. Programming Simple Servlet under Ubuntu GNU/Linux Tushar B Kute Nashik Linux Users Group tushar@tusharkute.com
  • 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