SlideShare a Scribd company logo
1 of 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))}

More Related Content

What's hot

Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3sandeep54552
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3sandeep54552
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Enterprise java unit-2_chapter-1
Enterprise  java unit-2_chapter-1Enterprise  java unit-2_chapter-1
Enterprise java unit-2_chapter-1sandeep54552
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Enterprise java unit-1_chapter-2
Enterprise java unit-1_chapter-2Enterprise java unit-1_chapter-2
Enterprise java unit-1_chapter-2sandeep54552
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache TomcatAuwal Amshi
 

What's hot (20)

Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Enterprise java unit-2_chapter-1
Enterprise  java unit-2_chapter-1Enterprise  java unit-2_chapter-1
Enterprise java unit-2_chapter-1
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Java RMI
Java RMIJava RMI
Java RMI
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Enterprise java unit-1_chapter-2
Enterprise java unit-1_chapter-2Enterprise java unit-1_chapter-2
Enterprise java unit-1_chapter-2
 
JDBC
JDBCJDBC
JDBC
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to 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 servletslopjuan
 

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

Recently uploaded

BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...Nguyen Thanh Tu Collection
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Celine George
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Denish Jangid
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesRased Khan
 
Essential Safety precautions during monsoon season
Essential Safety precautions during monsoon seasonEssential Safety precautions during monsoon season
Essential Safety precautions during monsoon seasonMayur Khatri
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesashishpaul799
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointELaRue0
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfbu07226
 
Mbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptxMbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptxnuriaiuzzolino1
 
The Ultimate Guide to Social Media Marketing in 2024.pdf
The Ultimate Guide to Social Media Marketing in 2024.pdfThe Ultimate Guide to Social Media Marketing in 2024.pdf
The Ultimate Guide to Social Media Marketing in 2024.pdfdm4ashexcelr
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticspragatimahajan3
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/siemaillard
 
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Mark Carrigan
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Mohamed Rizk Khodair
 
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45MysoreMuleSoftMeetup
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxheathfieldcps1
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resourcesaileywriter
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
Essential Safety precautions during monsoon season
Essential Safety precautions during monsoon seasonEssential Safety precautions during monsoon season
Essential Safety precautions during monsoon season
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
Mbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptxMbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptx
 
The Ultimate Guide to Social Media Marketing in 2024.pdf
The Ultimate Guide to Social Media Marketing in 2024.pdfThe Ultimate Guide to Social Media Marketing in 2024.pdf
The Ultimate Guide to Social Media Marketing in 2024.pdf
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 

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