SlideShare uma empresa 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))}

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Java servlets
Java servletsJava servlets
Java servlets
 
Bootstrap 3
Bootstrap 3Bootstrap 3
Bootstrap 3
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Servlet
Servlet Servlet
Servlet
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Tomcat
TomcatTomcat
Tomcat
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
Servlets
ServletsServlets
Servlets
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showThe complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
 
types of events in JS
types of events in JS types of events in JS
types of events in JS
 
AngularJS
AngularJS AngularJS
AngularJS
 
Enterprise java unit-2_chapter-1
Enterprise  java unit-2_chapter-1Enterprise  java unit-2_chapter-1
Enterprise java unit-2_chapter-1
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Java script
Java scriptJava script
Java script
 

Destaque

Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSPGeethu Mohan
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Appletsamitksaha
 
Java applets
Java appletsJava applets
Java appletslopjuan
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cyclemyrajendra
 
Data warehouse concepts
Data warehouse conceptsData warehouse concepts
Data warehouse conceptsobieefans
 
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
 
DATA WAREHOUSING
DATA WAREHOUSINGDATA WAREHOUSING
DATA WAREHOUSINGKing Julian
 
Data warehouse architecture
Data warehouse architectureData warehouse architecture
Data warehouse architecturepcherukumalla
 
Introduction to Data Warehousing
Introduction to Data WarehousingIntroduction to Data Warehousing
Introduction to Data WarehousingJason S
 
Data Warehousing and Data Mining
Data Warehousing and Data MiningData Warehousing and Data Mining
Data Warehousing and Data Miningidnats
 
Subversion - buenas prácticas
Subversion - buenas prácticasSubversion - buenas prácticas
Subversion - buenas prácticasIker Canarias
 
Introducción a Tomcat
Introducción a TomcatIntroducción a Tomcat
Introducción a TomcatIker Canarias
 

Destaque (18)

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

Semelhante a Servlets

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 BasicIMC Institute
 
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
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface pptTaha Malampatti
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren 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, environmentjoearunraja2
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slidesSasidhar Kothuru
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jspAnkit Minocha
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical filevarun arora
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
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 Augemfrancis
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 

Semelhante 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
 
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
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

Último

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
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)Jisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
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.christianmathematics
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
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Ữ Â...Nguyen Thanh Tu Collection
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
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.pdfAdmir Softic
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 

Último (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
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)
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
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.
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
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Ữ Â...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.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
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 

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