SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
Servlets




Static Pages


                 request


                 response

        Web
       browser
                            Web server
Dynamic Pages


           request                 request
                                              Servlet
                                              Servlet
                                               JSP
                                                JSP
           response                response
                                               ASP
                                                ASP
  Web
 browser
                      Web server




What is a Servlet?

Servlets are Java programs that can be run
dynamically in a Web Server
Servlets are a server-side technology
A Servlet is an intermediating layer between
an HTTP request of a client and the Web
server
What do Servlets do?

• Read data sent by the user (e.g., form data)
• Look up other information about request in the HTTP
  request (e.g. authentication data, cookies, etc.)
• Generate the results (may do this by talking to a database,
  file system, etc.)
• Format the results in a document (e.g., make it into HTML)
• Set the appropriate HTTP response parameters (e.g.
  cookies, content-type, etc.)
• Send the document to the user




 Supporting Servlets
  The Web server must support Servlets (since it must run the
  Servlets):
     Apache Tomcat
     Sun’s Java System Web Server and Java System
     Application Server
      IBM's WebSphere Application Server
     Allaire Jrun – an engine that can be added to IIS, PWS,
     old Apache Web servers etc…
     Oracle Application Server
     BEA WebLogic
The Servlet Interface
Java provides the interface Servlet
Specific Servlets implement this interface
Whenever the Web server is asked to invoke a
specific Servlet, it activates the method service() of
an instance of this Servlet


                                     MyServlet
        (HTTP)
        response
                              service(request,response)
       (HTTP)
       request




Servlet Hierarchy

                             service(ServletRequest,
      Servlet                   ServletResponse)


  Generic Servlet
                           doGet(HttpServletRequest ,
                             HttpServletResponse)
    HttpServlet            doPost(HttpServletRequest
                             HttpServletResponse)
                                     doPut
 YourOwnServlet
                                    doTrace
                                       …
Class HttpServlet

Class HttpServlet handles requests and
responses of HTTP protocol
The service() method of HttpServlet checks
the request method and calls the appropriate
HttpServlet method:
 doGet, doPost, doPut, doDelete, doTrace,
  doOptions or doHead
This class is abstract




Creating a Servlet
 Extend the class HTTPServlet
 Implement doGet or doPost (or both)
 Both methods get:
   HttpServletRequest: methods for getting form
   (query) data, HTTP request headers, etc.
   HttpServletResponse: methods for setting HTTP
   status codes, HTTP response headers, and get an
   output stream used for sending data to the client
 Usually implement doPost by calling doGet, or
 vice-versa
Returning HTML
    By default a text response is generated
    (text/plain)
    In order to generate HTML
        Tell the browser you are sending HTML, by
        setting the Content-Type header (text/html)
        Modify the printed text to create a legal HTML
        page
    You should set all headers before writing the
    document content.


import java.io.*;
import javax.servlet.*; import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse
  res) throws ServletException, IOException {
         res.setContentType("text/html");
         PrintWriter out = res.getWriter();

         out.println("<HTML><HEAD><TITLE>Hello
                     World</TITLE></HEAD>");
         out.println(“<BODY><H1>Hello World
                       </H1></BODY></HTML>");
         out.close();
    }
}
Configuring the Server
After you code your servlet, you need to compile it
to generate class files.
When your Servlet classes are ready, you have to
configure the Web server to recognize it.
This includes:
  Telling the Server that the Servlet exists
  Placing the Servlet class file in a place known to the
  server
  Telling the server which URL should be mapped to
  the Servlet
These details are server specific.
The Big Picture
                                         J2EE Web Component (WAR file)
J2EE Enterprise Application (EAR file)




                                         .class
                                                    .class
                                 .html
                                 .jpeg     .jar

                                          .jsp




                          Getting Information
                          From the Request
Getting HTTP Data

   Values of the HTTP request can be accessed
   through the HttpServletRequest object
   Get the value of the header hdr using
   getHeader("hdr") of the request argument
   Get all header names: getHeaderNames()
   Methods for specific request information:
   getCookies, getContentLength, getContentType,
   getMethod, getProtocol, etc.




import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class ShowRequestHeaders extends HttpServlet {

  public void doGet(HttpServletRequest request,
                 HttpServletResponse response)
       throws ServletException, IOException {

       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       String title = "Servlet Example:
                       Showing Request Headers";
out.println("<HTML><HEAD><TITLE>" + title +
     "</TITLE></HEAD>" +
     "<BODY BGCOLOR="#AACCAA" TEXT="#990000">n" +
     "<H1 ALIGN=CENTER>" + title + "</H1>n" +
     "<B>Request Method: </B>" +
     request.getMethod() + "<BR>n" +
     "<B>Request URI: </B>" +
     request.getRequestURI() + "<BR>n" +
     "<B>Request Protocol: </B>" +
     request.getProtocol() + "<BR><BR>n" +
     "<TABLE BORDER=1 ALIGN=CENTER>n" +
     "<TR BGCOLOR="#88AA88">n" +
     "<TH>Header Name<TH>Header Value");




    Enumeration headerNames = request.getHeaderNames();

    while(headerNames.hasMoreElements()) {
      String headerName =(String)headerNames.nextElement();
      out.println("<TR><TD>" + headerName);
      out.println("<TD>“ + request.getHeader(headerName));
    }
    out.println("</TABLE>n</BODY></HTML>");
}

 public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request, response);
  }
}
User Input in HTML
 Using HTML forms, we can pass
 parameters to web applications
 <form action=… method=…> …</form>
 comprises a single form
 • action: the address of the application to which
   the form data is sent
 • method: the HTTP method to use when
   passing parameters to the application (e.g.
   GET or POST)
GET Example
 <HTML>
 <FORM method="GET"
        action="http://www.google.com/search">
 <INPUT name="q" type="text">
 <INPUT type="submit">
 <INPUT type="reset">
 </FORM>
 </HTML>



  http://www.google.com/search?q=servlets




   POST Example
<HTML> <FORM method=“POST“
   action="http://www.google.com/search">
     <INPUT name=“q" type="text">
     <INPUT type="submit">
     <INPUT type="reset">
</FORM> </HTML>
   POST /search HTTP/1.1
   Host: www.google.com
   …
   Content-type: application/x-www-form-urlencoded
   Content-length: 10
   <empty-line>
   q=servlets
Getting the Parameter Values

     To get the value of a parameter named x:
         req.getParameter("x")
      where req is the service request argument
     If there can be multiple values for the
     parameter:
         req.getParameterValues("x")
     To get parameter names:
         req.getParameterNames()




<HTML>
<HEAD>
  <TITLE>Sending Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#CC90E0">
<H1 ALIGN="LEFT">Please enter the parameters</H1>

<FORM ACTION=“SetColors”
      METHOD=“GET”>
  <TABLE>
  <TR><TD>Background color:</TD>
  <TD><INPUT TYPE="TEXT" NAME="bgcolor"></TD></TR>
  <TR><TD>Font color:</TD>
  <TD><INPUT TYPE="TEXT" NAME="fgcolor"></TD></TR>
  <TR><TD>Font size:</TD>
  <TD><INPUT TYPE="TEXT" NAME="size"></TD></TR>
  </TABLE> <BR>
  <INPUT TYPE="SUBMIT" VALUE="Show Page">
</FORM>
</BODY>
</HTML>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class SetColors extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
        throws ServletException, IOException {


        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String bg = request.getParameter("bgcolor");
        String fg = request.getParameter("fgcolor");
        String size = request.getParameter("size");
out.println("<HTML><HEAD><TITLE>Set Colors Example" +
                   "</TITLE></HEAD>");
        out.println("<BODY text='" + fg +
                   "' bgcolor='" + bg + "'>");
        out.println("<H1>Set Colors Example</H1>");
        out.println("<FONT size='" + size + "'>");
        out.println("You requested a background color " +
                    bg + "<P>");
        out.println("You requested a font color " +
                    fg + "<P>");
        out.println("You requested a font size " +
            size + "<P>");
        out.println("</FONT></BODY></HTML>");
    }
}
Handling Post


 You don't have to do anything different to
 read POST data instead of GET data!!
           <FORM ACTION=“SetColors”
                  METHOD=“POST”> …

 public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
        throws ServletException, IOException {

       doGet(request, response);
 }




                Creating the
                Response of the
                Servlet
Setting the Response Status

  Use the following HttpServletResponse
  methods to set the response status:
  - setStatus(int sc)
      Use when there is no error, like 201 (created)
  - sendError(sc), sendError(sc, message)
      Use in erroneous situations, like 400 (bad request)
      The server may return a formatted message
  - sendRedirect(String location)
      Redirect to the new location




Setting the Response Status

 Class HTTPServletResponse has static
 integer variables for popular status codes
   for example:
    SC_OK(200), SC_NOT_MODIFIED(304),
    SC_UNAUTHORIZED(401),
     SC_BAD_REQUEST(400)
 Status code 200 (OK) is the default
Setting Response Headers
 Use the following HTTPServletResponse
 methods to set the response headers:
  - setHeader(String hdr, String value),
    setIntHeader(String hdr, int value)
      Override existing header value
  - addHeader(String hdr, String value),
    addIntHeader(String hdr, int value)
      The header is added even if another header
      with the same title exists




Specific Response Headers
  Class HTTPServletResponse provides
  setters for some specific headers:
   - setContentType
   - setContentLength
       automatically set if the entire response fits
       inside the response buffer
  - setDateHeader
  - setCharacterEncoding
More Header Methods

• containsHeader(String header)
    Check existence of a header in the response
• addCookie(Cookie)
• sendRedirect(String url)
    automatically sets the Location header
 Do not write information to the response
 after sendError or sendRedirect




Reference
 Representation and Management of Data on the Internet (67633),
 Yehoshua Sagiv, The Hebrew University - Institute of Computer
 Science.

Más contenido relacionado

La actualidad más candente

Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet backdoor
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationMicha Kops
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksRandy Connolly
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionMazenetsolution
 
Automated testing web services - part 1
Automated testing web services - part 1Automated testing web services - part 1
Automated testing web services - part 1Aleh Struneuski
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaJainamParikh3
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface pptTaha Malampatti
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyYahoo
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in SwiftPeter Friese
 

La actualidad más candente (20)

Ajax chap 3
Ajax chap 3Ajax chap 3
Ajax chap 3
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
 
JavaScript
JavaScriptJavaScript
JavaScript
 
AJAX
AJAXAJAX
AJAX
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
SERVIET
SERVIETSERVIET
SERVIET
 
Introduction to ASP.Net Viewstate
Introduction to ASP.Net ViewstateIntroduction to ASP.Net Viewstate
Introduction to ASP.Net Viewstate
 
Automated testing web services - part 1
Automated testing web services - part 1Automated testing web services - part 1
Automated testing web services - part 1
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
 
Servlets
ServletsServlets
Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - Italy
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
W3 C11
W3 C11W3 C11
W3 C11
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 

Destacado (20)

01 session tracking
01   session tracking01   session tracking
01 session tracking
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Lecture17
Lecture17Lecture17
Lecture17
 
Get and post methods
Get and post methodsGet and post methods
Get and post methods
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
Java servlets
Java servletsJava servlets
Java servlets
 
JSP
JSPJSP
JSP
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
HTTP Basics
HTTP BasicsHTTP Basics
HTTP Basics
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
HyperText Transfer Protocol (HTTP)
HyperText Transfer Protocol (HTTP)HyperText Transfer Protocol (HTTP)
HyperText Transfer Protocol (HTTP)
 

Similar a Servlets intro

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
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slidesSasidhar Kothuru
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 
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
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
HTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfHTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.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
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_kathir
 

Similar a Servlets intro (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
servletsservlets
servlets
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Ajax
AjaxAjax
Ajax
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Servlet
Servlet Servlet
Servlet
 
Lecture5
Lecture5Lecture5
Lecture5
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
Servlet Part 2
Servlet Part 2Servlet Part 2
Servlet Part 2
 
Servlets
ServletsServlets
Servlets
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
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
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
HTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfHTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdf
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Servlets
ServletsServlets
Servlets
 
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
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 

Más de vantinhkhuc (20)

Security overview
Security overviewSecurity overview
Security overview
 
Rmi
RmiRmi
Rmi
 
Md5
Md5Md5
Md5
 
Lecture11 b
Lecture11 bLecture11 b
Lecture11 b
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture9
Lecture9Lecture9
Lecture9
 
Lecture6
Lecture6Lecture6
Lecture6
 
Jsse
JsseJsse
Jsse
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Jsp examples
Jsp examplesJsp examples
Jsp examples
 
Jpa
JpaJpa
Jpa
 
Ejb examples
Ejb examplesEjb examples
Ejb examples
 
Corba
CorbaCorba
Corba
 
Ajax
AjaxAjax
Ajax
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
Chc6b0c6a1ng 12
Chc6b0c6a1ng 12Chc6b0c6a1ng 12
Chc6b0c6a1ng 12
 
Ch06
Ch06Ch06
Ch06
 
Bai4
Bai4Bai4
Bai4
 
Ajas11 alok
Ajas11 alokAjas11 alok
Ajas11 alok
 
Java
JavaJava
Java
 

Servlets intro

  • 1. Servlets Static Pages request response Web browser Web server
  • 2. Dynamic Pages request request Servlet Servlet JSP JSP response response ASP ASP Web browser Web server What is a Servlet? Servlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an intermediating layer between an HTTP request of a client and the Web server
  • 3. What do Servlets do? • Read data sent by the user (e.g., form data) • Look up other information about request in the HTTP request (e.g. authentication data, cookies, etc.) • Generate the results (may do this by talking to a database, file system, etc.) • Format the results in a document (e.g., make it into HTML) • Set the appropriate HTTP response parameters (e.g. cookies, content-type, etc.) • Send the document to the user Supporting Servlets The Web server must support Servlets (since it must run the Servlets): Apache Tomcat Sun’s Java System Web Server and Java System Application Server IBM's WebSphere Application Server Allaire Jrun – an engine that can be added to IIS, PWS, old Apache Web servers etc… Oracle Application Server BEA WebLogic
  • 4. The Servlet Interface Java provides the interface Servlet Specific Servlets implement this interface Whenever the Web server is asked to invoke a specific Servlet, it activates the method service() of an instance of this Servlet MyServlet (HTTP) response service(request,response) (HTTP) request Servlet Hierarchy service(ServletRequest, Servlet ServletResponse) Generic Servlet doGet(HttpServletRequest , HttpServletResponse) HttpServlet doPost(HttpServletRequest HttpServletResponse) doPut YourOwnServlet doTrace …
  • 5. Class HttpServlet Class HttpServlet handles requests and responses of HTTP protocol The service() method of HttpServlet checks the request method and calls the appropriate HttpServlet method: doGet, doPost, doPut, doDelete, doTrace, doOptions or doHead This class is abstract Creating a Servlet Extend the class HTTPServlet Implement doGet or doPost (or both) Both methods get: HttpServletRequest: methods for getting form (query) data, HTTP request headers, etc. HttpServletResponse: methods for setting HTTP status codes, HTTP response headers, and get an output stream used for sending data to the client Usually implement doPost by calling doGet, or vice-versa
  • 6. Returning HTML By default a text response is generated (text/plain) In order to generate HTML Tell the browser you are sending HTML, by setting the Content-Type header (text/html) Modify the printed text to create a legal HTML page You should set all headers before writing the document content. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><HEAD><TITLE>Hello World</TITLE></HEAD>"); out.println(“<BODY><H1>Hello World </H1></BODY></HTML>"); out.close(); } }
  • 7. Configuring the Server After you code your servlet, you need to compile it to generate class files. When your Servlet classes are ready, you have to configure the Web server to recognize it. This includes: Telling the Server that the Servlet exists Placing the Servlet class file in a place known to the server Telling the server which URL should be mapped to the Servlet These details are server specific.
  • 8. The Big Picture J2EE Web Component (WAR file) J2EE Enterprise Application (EAR file) .class .class .html .jpeg .jar .jsp Getting Information From the Request
  • 9. Getting HTTP Data Values of the HTTP request can be accessed through the HttpServletRequest object Get the value of the header hdr using getHeader("hdr") of the request argument Get all header names: getHeaderNames() Methods for specific request information: getCookies, getContentLength, getContentType, getMethod, getProtocol, etc. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Servlet Example: Showing Request Headers";
  • 10. out.println("<HTML><HEAD><TITLE>" + title + "</TITLE></HEAD>" + "<BODY BGCOLOR="#AACCAA" TEXT="#990000">n" + "<H1 ALIGN=CENTER>" + title + "</H1>n" + "<B>Request Method: </B>" + request.getMethod() + "<BR>n" + "<B>Request URI: </B>" + request.getRequestURI() + "<BR>n" + "<B>Request Protocol: </B>" + request.getProtocol() + "<BR><BR>n" + "<TABLE BORDER=1 ALIGN=CENTER>n" + "<TR BGCOLOR="#88AA88">n" + "<TH>Header Name<TH>Header Value"); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName =(String)headerNames.nextElement(); out.println("<TR><TD>" + headerName); out.println("<TD>“ + request.getHeader(headerName)); } out.println("</TABLE>n</BODY></HTML>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
  • 11. User Input in HTML Using HTML forms, we can pass parameters to web applications <form action=… method=…> …</form> comprises a single form • action: the address of the application to which the form data is sent • method: the HTTP method to use when passing parameters to the application (e.g. GET or POST)
  • 12. GET Example <HTML> <FORM method="GET" action="http://www.google.com/search"> <INPUT name="q" type="text"> <INPUT type="submit"> <INPUT type="reset"> </FORM> </HTML> http://www.google.com/search?q=servlets POST Example <HTML> <FORM method=“POST“ action="http://www.google.com/search"> <INPUT name=“q" type="text"> <INPUT type="submit"> <INPUT type="reset"> </FORM> </HTML> POST /search HTTP/1.1 Host: www.google.com … Content-type: application/x-www-form-urlencoded Content-length: 10 <empty-line> q=servlets
  • 13. Getting the Parameter Values To get the value of a parameter named x: req.getParameter("x") where req is the service request argument If there can be multiple values for the parameter: req.getParameterValues("x") To get parameter names: req.getParameterNames() <HTML> <HEAD> <TITLE>Sending Parameters</TITLE> </HEAD> <BODY BGCOLOR="#CC90E0"> <H1 ALIGN="LEFT">Please enter the parameters</H1> <FORM ACTION=“SetColors” METHOD=“GET”> <TABLE> <TR><TD>Background color:</TD> <TD><INPUT TYPE="TEXT" NAME="bgcolor"></TD></TR> <TR><TD>Font color:</TD> <TD><INPUT TYPE="TEXT" NAME="fgcolor"></TD></TR> <TR><TD>Font size:</TD> <TD><INPUT TYPE="TEXT" NAME="size"></TD></TR> </TABLE> <BR> <INPUT TYPE="SUBMIT" VALUE="Show Page"> </FORM> </BODY> </HTML>
  • 14. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SetColors extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String bg = request.getParameter("bgcolor"); String fg = request.getParameter("fgcolor"); String size = request.getParameter("size");
  • 15. out.println("<HTML><HEAD><TITLE>Set Colors Example" + "</TITLE></HEAD>"); out.println("<BODY text='" + fg + "' bgcolor='" + bg + "'>"); out.println("<H1>Set Colors Example</H1>"); out.println("<FONT size='" + size + "'>"); out.println("You requested a background color " + bg + "<P>"); out.println("You requested a font color " + fg + "<P>"); out.println("You requested a font size " + size + "<P>"); out.println("</FONT></BODY></HTML>"); } }
  • 16. Handling Post You don't have to do anything different to read POST data instead of GET data!! <FORM ACTION=“SetColors” METHOD=“POST”> … public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } Creating the Response of the Servlet
  • 17. Setting the Response Status Use the following HttpServletResponse methods to set the response status: - setStatus(int sc) Use when there is no error, like 201 (created) - sendError(sc), sendError(sc, message) Use in erroneous situations, like 400 (bad request) The server may return a formatted message - sendRedirect(String location) Redirect to the new location Setting the Response Status Class HTTPServletResponse has static integer variables for popular status codes for example: SC_OK(200), SC_NOT_MODIFIED(304), SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400) Status code 200 (OK) is the default
  • 18. Setting Response Headers Use the following HTTPServletResponse methods to set the response headers: - setHeader(String hdr, String value), setIntHeader(String hdr, int value) Override existing header value - addHeader(String hdr, String value), addIntHeader(String hdr, int value) The header is added even if another header with the same title exists Specific Response Headers Class HTTPServletResponse provides setters for some specific headers: - setContentType - setContentLength automatically set if the entire response fits inside the response buffer - setDateHeader - setCharacterEncoding
  • 19. More Header Methods • containsHeader(String header) Check existence of a header in the response • addCookie(Cookie) • sendRedirect(String url) automatically sets the Location header Do not write information to the response after sendError or sendRedirect Reference Representation and Management of Data on the Internet (67633), Yehoshua Sagiv, The Hebrew University - Institute of Computer Science.