SlideShare una empresa de Scribd logo
1 de 24


Servlets are part of the Java2EE specification.
 Servlets are modules that run on the server,
enabling you to extend the server’s functionality.
 Servlets work within a Web server environment,
and they are a key component of server side
 Java development. Servlets are an effective
replacement for CGI scripts.


Can be deployed into distributed server
environments.
 Servlets are platform- and server-independent.
 Servlets are easy to develop and follow a
standard API.
 Servlets are extensible. Java Server Pages (JSP)
build on top of the Servlet API.
 A servlet is a server resource, providing access to
other server resources, such as other servlets,
EJBs, JSPs, JDBC, and so on.
Method

Description

GET

The client requests information from the given
URL.

HEAD

Similar to GET, except the body is not retrieved.

POST

Client adds info to URI (HTML forms)

PUT

Used to place documents on the Server.

DELETE

Client deletes resource of URI.
Status

Code Category

100s
200s
300s
400s
500s

Informational
Successful
Redirection
Request Error
Server Error




The Servlet API defines a standard interface for
handling request and response between the
browser and the Web server.
The Servlet API is composed of two packages:
 javax.servlet - javax.servlet.GenericServlet

 javax.servlet.http - javax.servlet.HttpServlet
A generic servlet handling a request
An HTTP servlet handling GET and POST requests
Can use ServletOutputStream or PrintWriter to send data
back to the client.
1. reference the stream from the Response parameter:
ServletOutputStream out =response.getOutputStream();
2. get a reference to the writer from the Response
parameter:
PrintWriter out = response.getWriter();
3. Then write the output to the stream:
out.println(“<HTML>Inside HTML</HTML>”);
4. Finally, close the writer:
out.close();



MIME – Multiple Internet Mail Extension
Identifies extension of each file in the
HTTPResponse
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class srvltJust extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException {
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();
out.println(“<HTML>”);
out.println(“<HEAD><TITLE>Servlet</TITLE></HEAD>”);
out.println(“<BODY>”);
out.println(“<H1>This is a just a Servlet!</H1>”);
out.println(“</BODY></HTML>”);
out.close();
Parameters
 public String getParameter(String name)
 public Enumeration getParameterNames()
 public String[] getParameterValues(String name)
Content
 public int getContentLength() - returns the length, in
bytes. -1 is returned if the length is not known.
 getContentType() - returns the request’s MIME type
of the content (null if it’s not known).
 getCharacterEncoding() - returns the name character
encoding style of the request.
Header Methods
 setDateHeader()
 setIntHeader()
 setContentType()
 setContentLength()
 addCookie()
 sendError()
Ways to manage session,
 Hidden form fields
 URL rewriting
 Persistent cookies
 Session tracking API
<input type=”hidden” name=”pageid” value=”5”>


public String getParameter(String name)
 public Enumeration getParameterNames()
 public String[] getParameterValues(String name)
http://myServer/servlets/srvltEmp?EMPID=1009&
DEPID=200
API for persistent cookie is,
javax.servlet.http.Cookie
To create a new cookie,
 Cookie cookie(String name, String value)

 Eg: Cookie cookie = new Cookie("ID", "123");

To get all available cookies,
 req.getCookies()

To send back the cookie name
 response.addCookie(cookie_name)


A servlet with getSession( ) method retrieves the current
HttpSession object
Eg: public HttpSession HttpServletRequest.getSession(boolean )



Set properties by,
public void HttpSession.setAttribute(String name, Object value)
Eg: session.setAttribute(“name”, id);



Get properties by,
public void HttpSession.setMaxInactiveInterval(int secs)


Get current session id by,
public String getId()
 Whether it is a new cookie or referenced,
public boolean isNew
 Start of a session
public long getCreationTime()
 Last session activity
public long getLastAccessedTime
 Session invalidating by,
public void invalidate()
 Removing attribute by,
public void removeAttribute(String name)
import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*;
import javax.servlet.http.*;
public class srvltHoldAppID extends HttpServlet
{public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
resp.setContentType(“text/html”);
PrintWriter out = res.getWriter();
String sAPPID` = “undefined”;
String[] sAPPID = req.getParameter(“APPID”);
if(sAPPID != null && sAPPID.length > 0) {
// Create session:
HttpSession session = req.getSession();
session.setAttribute(“APPID”, sAPPID);
}}}
ServletContext sc = this.getServletContext();
RequestDispatcher rd =
sc.getRequestDispatcher(“/srvltComplete”);
if (rd !=null) {
try {
rd.forward(req, res);
}
catch (Exception e) {
// Handle Exception
}
}
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sSQL = “……….”
InitialContext ic = new InitialContext()
//Get a reference to the datasource
String dsName = “java:comp/env/jdbc/emplphone”
DataSource ds = (DataSource) ic.lookup(dsName)
conn = ds.getConnection() // Get a Connection
stmt = conn.createStatement()
rs = stmt.executeQuery(sSQL)
while( rs.next())
{out.println(rs.getString(1))}

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlets
ServletsServlets
Servlets
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
servlet in java
servlet in javaservlet in java
servlet in java
 
Session bean
Session beanSession bean
Session bean
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Jsp tag library
Jsp tag libraryJsp tag library
Jsp tag library
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Enterprise java unit-1_chapter-1
Enterprise java unit-1_chapter-1Enterprise java unit-1_chapter-1
Enterprise java unit-1_chapter-1
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Web api
Web apiWeb api
Web api
 
Java Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web ApplicationJava Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web Application
 

Destacado

Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
Geethu Mohan
 
Java applets
Java appletsJava applets
Java applets
lopjuan
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
myrajendra
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Nitin Pai
 
Data warehouse architecture
Data warehouse architectureData warehouse architecture
Data warehouse architecture
pcherukumalla
 

Destacado (17)

Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
 
Applet java
Applet javaApplet java
Applet java
 
Java applets
Java appletsJava applets
Java applets
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Data warehouse concepts
Data warehouse conceptsData warehouse concepts
Data warehouse concepts
 
Java applets
Java appletsJava applets
Java applets
 
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
 
DATA WAREHOUSING
DATA WAREHOUSINGDATA WAREHOUSING
DATA WAREHOUSING
 
DATA WAREHOUSING
DATA WAREHOUSINGDATA WAREHOUSING
DATA WAREHOUSING
 
Data warehouse architecture
Data warehouse architectureData warehouse architecture
Data warehouse architecture
 
DATA WAREHOUSING AND DATA MINING
DATA WAREHOUSING AND DATA MININGDATA WAREHOUSING AND DATA MINING
DATA WAREHOUSING AND DATA MINING
 
Introduction to Data Warehousing
Introduction to Data WarehousingIntroduction to Data Warehousing
Introduction to Data Warehousing
 
Data Warehousing and Data Mining
Data Warehousing and Data MiningData Warehousing and Data Mining
Data Warehousing and Data Mining
 
Subversion - buenas prácticas
Subversion - buenas prácticasSubversion - buenas prácticas
Subversion - buenas prácticas
 
Introducción a Tomcat
Introducción a TomcatIntroducción a Tomcat
Introducción a Tomcat
 

Similar a Servlets

Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
joearunraja2
 
Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 

Similar a Servlets (20)

Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
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
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
Servlets
ServletsServlets
Servlets
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Servlet
Servlet Servlet
Servlet
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Ajax
AjaxAjax
Ajax
 
servlets
servletsservlets
servlets
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R AugeHTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
 
Java servlets
Java servletsJava servlets
Java servlets
 

Último

Último (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 

Servlets

  • 1.
  • 2.  Servlets are part of the Java2EE specification.  Servlets are modules that run on the server, enabling you to extend the server’s functionality.  Servlets work within a Web server environment, and they are a key component of server side  Java development. Servlets are an effective replacement for CGI scripts.
  • 3.  Can be deployed into distributed server environments.  Servlets are platform- and server-independent.  Servlets are easy to develop and follow a standard API.  Servlets are extensible. Java Server Pages (JSP) build on top of the Servlet API.  A servlet is a server resource, providing access to other server resources, such as other servlets, EJBs, JSPs, JDBC, and so on.
  • 4. Method Description GET The client requests information from the given URL. HEAD Similar to GET, except the body is not retrieved. POST Client adds info to URI (HTML forms) PUT Used to place documents on the Server. DELETE Client deletes resource of URI.
  • 6.   The Servlet API defines a standard interface for handling request and response between the browser and the Web server. The Servlet API is composed of two packages:  javax.servlet - javax.servlet.GenericServlet  javax.servlet.http - javax.servlet.HttpServlet
  • 7. A generic servlet handling a request
  • 8. An HTTP servlet handling GET and POST requests
  • 9. Can use ServletOutputStream or PrintWriter to send data back to the client. 1. reference the stream from the Response parameter: ServletOutputStream out =response.getOutputStream(); 2. get a reference to the writer from the Response parameter: PrintWriter out = response.getWriter(); 3. Then write the output to the stream: out.println(“<HTML>Inside HTML</HTML>”); 4. Finally, close the writer: out.close();
  • 10.   MIME – Multiple Internet Mail Extension Identifies extension of each file in the HTTPResponse response.setContentType(“text/html”); PrintWriter out = response.getWriter();
  • 11. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class srvltJust extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(“text/html”); PrintWriter out = res.getWriter(); out.println(“<HTML>”); out.println(“<HEAD><TITLE>Servlet</TITLE></HEAD>”); out.println(“<BODY>”); out.println(“<H1>This is a just a Servlet!</H1>”); out.println(“</BODY></HTML>”); out.close();
  • 12.
  • 13.
  • 14. Parameters  public String getParameter(String name)  public Enumeration getParameterNames()  public String[] getParameterValues(String name) Content  public int getContentLength() - returns the length, in bytes. -1 is returned if the length is not known.  getContentType() - returns the request’s MIME type of the content (null if it’s not known).  getCharacterEncoding() - returns the name character encoding style of the request.
  • 15. Header Methods  setDateHeader()  setIntHeader()  setContentType()  setContentLength()  addCookie()  sendError()
  • 16. Ways to manage session,  Hidden form fields  URL rewriting  Persistent cookies  Session tracking API
  • 17. <input type=”hidden” name=”pageid” value=”5”>  public String getParameter(String name)  public Enumeration getParameterNames()  public String[] getParameterValues(String name)
  • 19. API for persistent cookie is, javax.servlet.http.Cookie To create a new cookie,  Cookie cookie(String name, String value)  Eg: Cookie cookie = new Cookie("ID", "123"); To get all available cookies,  req.getCookies() To send back the cookie name  response.addCookie(cookie_name)
  • 20.  A servlet with getSession( ) method retrieves the current HttpSession object Eg: public HttpSession HttpServletRequest.getSession(boolean )  Set properties by, public void HttpSession.setAttribute(String name, Object value) Eg: session.setAttribute(“name”, id);  Get properties by, public void HttpSession.setMaxInactiveInterval(int secs)
  • 21.  Get current session id by, public String getId()  Whether it is a new cookie or referenced, public boolean isNew  Start of a session public long getCreationTime()  Last session activity public long getLastAccessedTime  Session invalidating by, public void invalidate()  Removing attribute by, public void removeAttribute(String name)
  • 22. import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class srvltHoldAppID extends HttpServlet {public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { resp.setContentType(“text/html”); PrintWriter out = res.getWriter(); String sAPPID` = “undefined”; String[] sAPPID = req.getParameter(“APPID”); if(sAPPID != null && sAPPID.length > 0) { // Create session: HttpSession session = req.getSession(); session.setAttribute(“APPID”, sAPPID); }}}
  • 23. ServletContext sc = this.getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(“/srvltComplete”); if (rd !=null) { try { rd.forward(req, res); } catch (Exception e) { // Handle Exception } }
  • 24. Connection conn = null; Statement stmt = null; ResultSet rs = null; String sSQL = “……….” InitialContext ic = new InitialContext() //Get a reference to the datasource String dsName = “java:comp/env/jdbc/emplphone” DataSource ds = (DataSource) ic.lookup(dsName) conn = ds.getConnection() // Get a Connection stmt = conn.createStatement() rs = stmt.executeQuery(sSQL) while( rs.next()) {out.println(rs.getString(1))}