SlideShare ist ein Scribd-Unternehmen logo
1 von 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))}

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java script
Java scriptJava script
Java script
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Arquitetura Node com NestJS
Arquitetura Node com NestJSArquitetura Node com NestJS
Arquitetura Node com NestJS
 
REST API
REST APIREST API
REST API
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 

Kürzlich hochgeladen (20)

ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 

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