SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances (20)

PHP MVC
PHP MVCPHP MVC
PHP MVC
 
Sgml
SgmlSgml
Sgml
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
 
Android User Interface
Android User InterfaceAndroid User Interface
Android User Interface
 
Web Technology Lab File
Web Technology Lab FileWeb Technology Lab File
Web Technology Lab File
 
Python cgi programming
Python cgi programmingPython cgi programming
Python cgi programming
 
Flutter beyond hello world
Flutter beyond hello worldFlutter beyond hello world
Flutter beyond hello world
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
MVC Architecture
MVC ArchitectureMVC Architecture
MVC Architecture
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Web api
Web apiWeb api
Web api
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Flutter Festivals GDSC ASEB | Introduction to Dart
Flutter Festivals GDSC ASEB | Introduction to DartFlutter Festivals GDSC ASEB | Introduction to Dart
Flutter Festivals GDSC ASEB | Introduction to Dart
 
Swift UI - Declarative Programming [Pramati Technologies]
Swift UI - Declarative Programming [Pramati Technologies]Swift UI - Declarative Programming [Pramati Technologies]
Swift UI - Declarative Programming [Pramati Technologies]
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
 
Stress management
Stress managementStress management
Stress management
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 

En vedette

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
 

En vedette (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
 

Similaire à Java Servlet Programming under Ubuntu Linux by Tushar B Kute

Similaire à Java Servlet Programming under Ubuntu Linux by Tushar B Kute (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
 

Plus de 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
 

Plus de 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
 

Dernier

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

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