SlideShare a Scribd company logo
1 of 12
Download to read offline
Servlets
                      1
By: Abdalla Mahmoud .

Contents
            Servlets .............................................................................................. 1
             1. Introduction ................................................................................... 2
             2. First Servlet ................................................................................... 2
               2.1. Servlet class. ............................................................................ 2
               2.2. Deployment Descriptor .............................................................. 3
             2.3. Packaging the Web Module ............................................................ 4
             3. Analyzing the Request ..................................................................... 4
               3.1. Analyzing Request Headers......................................................... 4
               3.2. Analyzing Request Parameters .................................................... 4
               3.3. Analyzing Agent's Cookies .......................................................... 5
             4. Sending the Response ..................................................................... 6
               4.1. Sending Response Headers......................................................... 6
               4.2. Sending Response Content ......................................................... 6
               4.3. Sending Agent Cookies .............................................................. 7
             5. Hoax Example - Add Two Numbers.................................................... 8
               5.1. HTML Form............................................................................... 8
                 5.1.1. Packaging Static Resources ................................................... 8
               5.2. Process Servlet ......................................................................... 8
                 5.2.1. Mapping Process Servlet ....................................................... 9
             6. Hoax Example Revisited - Separate Controller from View ..................... 9
               6.1. Process Servlet ........................................................................ 10
               6.2. View Servlet ............................................................................ 10
             7. HTTP Sessions............................................................................... 11
               7.1. Creating HTTP Session .............................................................. 11
               7.2. Sharing Data ........................................................................... 12




1. http://www.abdallamahmoud.com/.



                                                      1
1. Introduction
   Servlets are web components that generate dynamic content to user agents. Like other
enterprise components, servlets are deployed on and managed by the application server.
Any Java EE compliant application server provides an implementation for HTTP server. JBoss
comes with Apache Tomcat embedded as the HTTP server.

Servlets are java classes that extend HttpServlet. The HttpServlet is a generic prototype for
a typical web component. The Java EE developer extends the class to create custom web
components. The class, by default, provides seven methods that can be overriden to satisfy
every possible HTTP method:

HTTP Methods Methods Provided by the HttpServlet Class.
void doGet(HttpServletRequest req, HttpServletResponse resp)
void doPost(HttpServletRequest req, HttpServletResponse resp)
void doDelete(HttpServletRequest req, HttpServletResponse resp)
void doHead(HttpServletRequest req, HttpServletResponse resp)
void doOptions(HttpServletRequest req, HttpServletResponse resp)
void doPut(HttpServletRequest req, HttpServletResponse resp)
void doTrace(HttpServletRequest req, HttpServletResponse resp)

The role of a servlet is to analyze the request and respond to it.




2. First Servlet

2.1. Servlet class.

The servlet class is a java class that extends the HttpServlet class and overrides one or
more HTTP methods methods in the super class. All servlet classes should be located under
WEB-INF/classes/ in the web module.




                                               2
file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;

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

public class MyFirstServlet extends HttpServlet {

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

           PrintWriter out = response.getWriter() ;
           out.println("<html>") ;
           out.println("<head>") ;
           out.println("<title>First Servlet</title>") ;
           out.println("</head>") ;
           out.println("<body>") ;
           out.println("<h1>My First Servlet</h1>") ;
           out.println("Hello world") ;

      }

}



2.2. Deployment Descriptor

Every web module is accossiated with a deployment descriptor file that describes the
components of the web application. The configuration file should be located in WEB-INF/
web.xml in the web module.

file: WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

      <servlet>
           <servlet-name>MyFirstServlet</servlet-name>
           <servlet-class>webapp.MyFirstServlet</servlet-class>
      </servlet>

      <servlet-mapping>
           <servlet-name>MyFirstServlet</servlet-name>
           <url-pattern>/foo</url-pattern>
      </servlet-mapping>




                                          3
</web-app>



2.3. Packaging the Web Module
Unlike business modules, web modules are packaged into war files (Web ARchive) rather than
jar files (Java ARchive). Same command is used here:

Command Prompt
C:workspace> jar cf foo.war WEB-INF/classes/webapp/*.class WEB-INF/web.xml



3. Analyzing the Request
   The web server is responsible for listening to agent connections, read and understand
HTTP request, then encapsulates it structured in an object. The object is then passed to the
servlet's HTTP method's method as an argument to the request parameter. The following
sections show the request object and how it can be used in different contexts.

3.1. Analyzing Request Headers

Request headers can be retrieved using method String getHeader(String name).

file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;

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

public class MyFirstServlet extends HttpServlet {

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

             String agent = request.getHeader("User-Agent") ;

      }

}


3.2. Analyzing Request Parameters

Request parameters can be retrieved using method String getParameter(String name).

file: WEB-INF/classes/webapp/MyFirstServlet.java



                                             4
package webapp ;

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

public class MyFirstServlet extends HttpServlet {

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

            int id = Integer.parseInt(request.getParameter("id")) ;
            PrintWriter out = response.getWriter() ;
            out.println("You have requested topic with id:" + id) ;

        }

}


3.3. Analyzing Agent's Cookies

Agent cookies can be retrieved using method Cookie[] getCookies(). Objects of class
Cookie used to represent an agent's cookie. Cookie's name and value are encapsulated in
methods getName() and getValue() respectively.

file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;

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

public class MyFirstServlet extends HttpServlet {

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

            Cookie[] cookies = request.getCookies() ;
            for(int i = 0 ; i < cookies.length ; i++) {

                String cookieName = cookies[i].getName() ;
                String cookieValue = cookies[i].getValue() ;

                //process the cookie

            }

    }



                                          5
}


4. Sending the Response
    The web server is responsible for sending response to agents, then close the connection.
It provides a response object that encapsulates different response data and actions.The
following sections show the response object and how it can be used in different contexts.

4.1. Sending Response Headers

Response headers can be added to the response using the method void addHeader(String
name, String value).

file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;

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

public class MyFirstServlet extends HttpServlet {

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

            response.addHeader("Content-Type",        "text/html");

      }

}


4.2. Sending Response Content

Response content can be written to the agent using the response's output stream. It can be
retrieved using the method PrintWriter getWriter().

file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;

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

public class MyFirstServlet extends HttpServlet {




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

           //get a reference to the stream of the output to the agent
           PrintWriter out = response.getWriter() ;

           //write to the stream >> the output
           out.println("<html>") ;
           out.println("<head>") ;
           out.println("<title>First Servlet</title>") ;
           out.println("</head>") ;
           out.println("<body>") ;
           out.println("<h1>My First Servlet</h1>") ;
           out.println("Hello world") ;
           out.println("</body>") ;
           out.println("</html>") ;

      }

}


4.3. Sending Agent Cookies

Cookies can be sent to be added or modified at the agent using the method
addCookie(Cookie cookie). A cookie object should be passed encapsulating the cookie's
data. A cookie object can be instantiated using constructor Cookie(String name, String
value).

file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;

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

public class MyFirstServlet extends HttpServlet {

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

           response.addCookie(new Cookie("user_id", "125"));

      }

}




                                          7
5. Hoax Example - Add Two Numbers
  Our target is to develop a web application that allows a user to add two numbers. The
application will consist of the following resources:

     • A form page (page.html).
     • A servlet that process and display the output (ProcessServlet).

5.1. HTML Form

file: page.html
<html>

      <head><title>Add Two Numbers</title></head>

      <body>

            <form method="POST" action="/process">
                 Number 1:<input type="textfield" name="num1"/><br/>
                 Number 2:<input type="textfield" name="num2"/><br/>
                 <input type="submit" value="Add"/>
            </form>

      </body>

</html>


5.1.1. Packaging Static Resources

Static resources such as html pages (.html) and images (.jpeg, .png, .gif) are packages in
the root of the web archive, and need not to be mapped in the .

5.2. Process Servlet

file: WEB-INF/classes/webapp/ProcessServlet.java
package webapp ;

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

public class ProcessServlet extends HttpServlet {

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




                                            8
float num1 = Float.parseFloat(request.getParameter("num1")) ;
            float num2 = Float.parseFloat(request.getParameter("num2")) ;
            float result = num1 + num2 ;
            String message = "Result = " + result ;

            PrintWriter out = response.getWriter() ;

            out.println("<html>") ;
            out.println("<head>") ;
            out.println("<title>Result by Process Servlet</title>") ;
            out.println("</head>") ;
            out.println("<body>") ;
            out.println(message) ;
            out.println("</body>") ;
            out.println("</html>") ;

      }

}


5.2.1. Mapping Process Servlet

Add the following mappings in the web.xml file:

file: WEB-INF/web.xml
      ...

      <servlet>
           <servlet-name>ProcessServlet</servlet-name>
           <servlet-class>webapp.ProcessServlet</servlet-class>
      </servlet>

      <servlet-mapping>
           <servlet-name>ProcessServlet</servlet-name>
           <url-pattern>/process</url-pattern>
      </servlet-mapping>

      ...


6. Hoax Example Revisited - Separate Controller from View
Our target is to redevelop the previous web application so as to consist of the following
resources:

     • A form page (page.html).
     • A servlet that process and display the output (ProcessServlet).
     • Another servlet that display the output (ViewServlet).




                                             9
The web application will work in the following scenario: the user requests page.html, fill
the form, post the data. The data is processed by ProvessServlet, which will forward the
request to the ViewServlet to view the data. Although a trivial example, it's the main
concept in separating the controller from the view in web design patterns.

6.1. Process Servlet

file: WEB-INF/classes/webapp/ProcessServlet.java
package webapp ;

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

public class ProcessServlet extends HttpServlet {

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

            float num1 = Float.parseFloat(request.getParameter("num1")) ;
            float num2 = Float.parseFloat(request.getParameter("num2")) ;
            float result = num1 + num2 ;

            //set attribute to be shared with the delegates

            request.setAttribute("result", result) ;

            //create a request dispatcher from the request object
            RequestDispatcher rd = request.getRequestDispatcher("/view") ;
            //forward the request passing request and response objects
            rd.forward(request, response) ;

    }

}


6.2. View Servlet

file: WEB-INF/classes/webapp/ViewServlet.java
package webapp ;

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

public class ViewServlet extends HttpServlet {




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

            float result = (Float) request.getAttribute("result") ;
            String message = "Result = " + result ;

            PrintWriter out = response.getWriter() ;

            out.println("<html>") ;
            out.println("<head>") ;
            out.println("<title>Result by Process Servlet</title>") ;
            out.println("</head>") ;
            out.println("<body>") ;
            out.println(message) ;
            out.println("</body>") ;
            out.println("</html>") ;

      }

}


7. HTTP Sessions
   As we saw later, HTTP is a stateless protocol. To overcome this in stateful web applications,
session concept should be implemented. In Java EE, session concept is abstracted and
provided via the HttpSession interface. A reference to a session object can obtained using
the method HttpSession getSession() in the request object.

7.1. Creating HTTP Session

file: WEB-INF/classes/webapp/MyFirstServlet.java
package webapp ;

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

public class MyFirstServlet extends HttpServlet {

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

            HttpSession session = request.getSession() ;
            session.setAttribute("user_id", "505") ;

      }




                                              11
}


7.2. Sharing Data

Data can be shared using the method void setAttribute(String name, Object value).
Any other page can retrieve shared data using the method Object getAttribute().




                                       12

More Related Content

What's hot

Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19aminmesbahi
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernatetrustparency
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
Java Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application SecurityJava Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application SecurityIMC Institute
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorial
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorialHibernate, Spring, Eclipse, HSQL Database & Maven tutorial
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorialRaghavan Mohan
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slidesSasidhar Kothuru
 
Glassfish JEE Server Administration - Module 4 Load Balancer
Glassfish JEE Server Administration - Module 4 Load BalancerGlassfish JEE Server Administration - Module 4 Load Balancer
Glassfish JEE Server Administration - Module 4 Load BalancerDanairat Thanabodithammachari
 
Modelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST urlModelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST urlXebia IT Architects
 
.NET Core, ASP.NET Core Course, Session 18
 .NET Core, ASP.NET Core Course, Session 18 .NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18aminmesbahi
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaJainamParikh3
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojosdeconf
 

What's hot (20)

Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
 
Glassfish JEE Server Administration - Clustering
Glassfish JEE Server Administration - ClusteringGlassfish JEE Server Administration - Clustering
Glassfish JEE Server Administration - Clustering
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernate
 
J2EE-assignment
 J2EE-assignment J2EE-assignment
J2EE-assignment
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
Java Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application SecurityJava Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application Security
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorial
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorialHibernate, Spring, Eclipse, HSQL Database & Maven tutorial
Hibernate, Spring, Eclipse, HSQL Database & Maven tutorial
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
JEE Programming - 05 JSP
JEE Programming - 05 JSPJEE Programming - 05 JSP
JEE Programming - 05 JSP
 
Glassfish JEE Server Administration - Module 4 Load Balancer
Glassfish JEE Server Administration - Module 4 Load BalancerGlassfish JEE Server Administration - Module 4 Load Balancer
Glassfish JEE Server Administration - Module 4 Load Balancer
 
Modelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST urlModelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST url
 
.NET Core, ASP.NET Core Course, Session 18
 .NET Core, ASP.NET Core Course, Session 18 .NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojo
 

Viewers also liked

Introduction to Java Enterprise Edition
Introduction to Java Enterprise EditionIntroduction to Java Enterprise Edition
Introduction to Java Enterprise EditionAbdalla Mahmoud
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2Rajiv Gupta
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 
CBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationCBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationGuru Ji
 

Viewers also liked (9)

IBM_Participation_4
IBM_Participation_4IBM_Participation_4
IBM_Participation_4
 
JavaServer Pages
JavaServer PagesJavaServer Pages
JavaServer Pages
 
Java EE Services
Java EE ServicesJava EE Services
Java EE Services
 
Persistence
PersistencePersistence
Persistence
 
Introduction to Java Enterprise Edition
Introduction to Java Enterprise EditionIntroduction to Java Enterprise Edition
Introduction to Java Enterprise Edition
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
CBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationCBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL Presentation
 
eCertificate-JAVA-2
eCertificate-JAVA-2eCertificate-JAVA-2
eCertificate-JAVA-2
 

Similar to Servlets

Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassCODE WHITE GmbH
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4than sare
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jspAnkit Minocha
 
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
 
JSR 168 Portal - Overview
JSR 168 Portal - OverviewJSR 168 Portal - Overview
JSR 168 Portal - OverviewVinay Kumar
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 
Struts tutorial
Struts tutorialStruts tutorial
Struts tutorialOPENLANE
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Introduction to the World Wide Web
Introduction to the World Wide WebIntroduction to the World Wide Web
Introduction to the World Wide WebAbdalla Mahmoud
 

Similar to Servlets (20)

Servlets
ServletsServlets
Servlets
 
Express node js
Express node jsExpress node js
Express node js
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
Servlets
ServletsServlets
Servlets
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
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
 
JSR 168 Portal - Overview
JSR 168 Portal - OverviewJSR 168 Portal - Overview
JSR 168 Portal - Overview
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Struts 1
Struts 1Struts 1
Struts 1
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
Struts tutorial
Struts tutorialStruts tutorial
Struts tutorial
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
XSS
XSSXSS
XSS
 
XSS
XSSXSS
XSS
 
Introduction to the World Wide Web
Introduction to the World Wide WebIntroduction to the World Wide Web
Introduction to the World Wide Web
 
Node js getting started
Node js getting startedNode js getting started
Node js getting started
 

Recently uploaded

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

Servlets

  • 1. Servlets 1 By: Abdalla Mahmoud . Contents Servlets .............................................................................................. 1 1. Introduction ................................................................................... 2 2. First Servlet ................................................................................... 2 2.1. Servlet class. ............................................................................ 2 2.2. Deployment Descriptor .............................................................. 3 2.3. Packaging the Web Module ............................................................ 4 3. Analyzing the Request ..................................................................... 4 3.1. Analyzing Request Headers......................................................... 4 3.2. Analyzing Request Parameters .................................................... 4 3.3. Analyzing Agent's Cookies .......................................................... 5 4. Sending the Response ..................................................................... 6 4.1. Sending Response Headers......................................................... 6 4.2. Sending Response Content ......................................................... 6 4.3. Sending Agent Cookies .............................................................. 7 5. Hoax Example - Add Two Numbers.................................................... 8 5.1. HTML Form............................................................................... 8 5.1.1. Packaging Static Resources ................................................... 8 5.2. Process Servlet ......................................................................... 8 5.2.1. Mapping Process Servlet ....................................................... 9 6. Hoax Example Revisited - Separate Controller from View ..................... 9 6.1. Process Servlet ........................................................................ 10 6.2. View Servlet ............................................................................ 10 7. HTTP Sessions............................................................................... 11 7.1. Creating HTTP Session .............................................................. 11 7.2. Sharing Data ........................................................................... 12 1. http://www.abdallamahmoud.com/. 1
  • 2. 1. Introduction Servlets are web components that generate dynamic content to user agents. Like other enterprise components, servlets are deployed on and managed by the application server. Any Java EE compliant application server provides an implementation for HTTP server. JBoss comes with Apache Tomcat embedded as the HTTP server. Servlets are java classes that extend HttpServlet. The HttpServlet is a generic prototype for a typical web component. The Java EE developer extends the class to create custom web components. The class, by default, provides seven methods that can be overriden to satisfy every possible HTTP method: HTTP Methods Methods Provided by the HttpServlet Class. void doGet(HttpServletRequest req, HttpServletResponse resp) void doPost(HttpServletRequest req, HttpServletResponse resp) void doDelete(HttpServletRequest req, HttpServletResponse resp) void doHead(HttpServletRequest req, HttpServletResponse resp) void doOptions(HttpServletRequest req, HttpServletResponse resp) void doPut(HttpServletRequest req, HttpServletResponse resp) void doTrace(HttpServletRequest req, HttpServletResponse resp) The role of a servlet is to analyze the request and respond to it. 2. First Servlet 2.1. Servlet class. The servlet class is a java class that extends the HttpServlet class and overrides one or more HTTP methods methods in the super class. All servlet classes should be located under WEB-INF/classes/ in the web module. 2
  • 3. file: WEB-INF/classes/webapp/MyFirstServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class MyFirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter() ; out.println("<html>") ; out.println("<head>") ; out.println("<title>First Servlet</title>") ; out.println("</head>") ; out.println("<body>") ; out.println("<h1>My First Servlet</h1>") ; out.println("Hello world") ; } } 2.2. Deployment Descriptor Every web module is accossiated with a deployment descriptor file that describes the components of the web application. The configuration file should be located in WEB-INF/ web.xml in the web module. file: WEB-INF/web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>MyFirstServlet</servlet-name> <servlet-class>webapp.MyFirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyFirstServlet</servlet-name> <url-pattern>/foo</url-pattern> </servlet-mapping> 3
  • 4. </web-app> 2.3. Packaging the Web Module Unlike business modules, web modules are packaged into war files (Web ARchive) rather than jar files (Java ARchive). Same command is used here: Command Prompt C:workspace> jar cf foo.war WEB-INF/classes/webapp/*.class WEB-INF/web.xml 3. Analyzing the Request The web server is responsible for listening to agent connections, read and understand HTTP request, then encapsulates it structured in an object. The object is then passed to the servlet's HTTP method's method as an argument to the request parameter. The following sections show the request object and how it can be used in different contexts. 3.1. Analyzing Request Headers Request headers can be retrieved using method String getHeader(String name). file: WEB-INF/classes/webapp/MyFirstServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class MyFirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String agent = request.getHeader("User-Agent") ; } } 3.2. Analyzing Request Parameters Request parameters can be retrieved using method String getParameter(String name). file: WEB-INF/classes/webapp/MyFirstServlet.java 4
  • 5. package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class MyFirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int id = Integer.parseInt(request.getParameter("id")) ; PrintWriter out = response.getWriter() ; out.println("You have requested topic with id:" + id) ; } } 3.3. Analyzing Agent's Cookies Agent cookies can be retrieved using method Cookie[] getCookies(). Objects of class Cookie used to represent an agent's cookie. Cookie's name and value are encapsulated in methods getName() and getValue() respectively. file: WEB-INF/classes/webapp/MyFirstServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class MyFirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Cookie[] cookies = request.getCookies() ; for(int i = 0 ; i < cookies.length ; i++) { String cookieName = cookies[i].getName() ; String cookieValue = cookies[i].getValue() ; //process the cookie } } 5
  • 6. } 4. Sending the Response The web server is responsible for sending response to agents, then close the connection. It provides a response object that encapsulates different response data and actions.The following sections show the response object and how it can be used in different contexts. 4.1. Sending Response Headers Response headers can be added to the response using the method void addHeader(String name, String value). file: WEB-INF/classes/webapp/MyFirstServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class MyFirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.addHeader("Content-Type", "text/html"); } } 4.2. Sending Response Content Response content can be written to the agent using the response's output stream. It can be retrieved using the method PrintWriter getWriter(). file: WEB-INF/classes/webapp/MyFirstServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class MyFirstServlet extends HttpServlet { 6
  • 7. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //get a reference to the stream of the output to the agent PrintWriter out = response.getWriter() ; //write to the stream >> the output out.println("<html>") ; out.println("<head>") ; out.println("<title>First Servlet</title>") ; out.println("</head>") ; out.println("<body>") ; out.println("<h1>My First Servlet</h1>") ; out.println("Hello world") ; out.println("</body>") ; out.println("</html>") ; } } 4.3. Sending Agent Cookies Cookies can be sent to be added or modified at the agent using the method addCookie(Cookie cookie). A cookie object should be passed encapsulating the cookie's data. A cookie object can be instantiated using constructor Cookie(String name, String value). file: WEB-INF/classes/webapp/MyFirstServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class MyFirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.addCookie(new Cookie("user_id", "125")); } } 7
  • 8. 5. Hoax Example - Add Two Numbers Our target is to develop a web application that allows a user to add two numbers. The application will consist of the following resources: • A form page (page.html). • A servlet that process and display the output (ProcessServlet). 5.1. HTML Form file: page.html <html> <head><title>Add Two Numbers</title></head> <body> <form method="POST" action="/process"> Number 1:<input type="textfield" name="num1"/><br/> Number 2:<input type="textfield" name="num2"/><br/> <input type="submit" value="Add"/> </form> </body> </html> 5.1.1. Packaging Static Resources Static resources such as html pages (.html) and images (.jpeg, .png, .gif) are packages in the root of the web archive, and need not to be mapped in the . 5.2. Process Servlet file: WEB-INF/classes/webapp/ProcessServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class ProcessServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { 8
  • 9. float num1 = Float.parseFloat(request.getParameter("num1")) ; float num2 = Float.parseFloat(request.getParameter("num2")) ; float result = num1 + num2 ; String message = "Result = " + result ; PrintWriter out = response.getWriter() ; out.println("<html>") ; out.println("<head>") ; out.println("<title>Result by Process Servlet</title>") ; out.println("</head>") ; out.println("<body>") ; out.println(message) ; out.println("</body>") ; out.println("</html>") ; } } 5.2.1. Mapping Process Servlet Add the following mappings in the web.xml file: file: WEB-INF/web.xml ... <servlet> <servlet-name>ProcessServlet</servlet-name> <servlet-class>webapp.ProcessServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ProcessServlet</servlet-name> <url-pattern>/process</url-pattern> </servlet-mapping> ... 6. Hoax Example Revisited - Separate Controller from View Our target is to redevelop the previous web application so as to consist of the following resources: • A form page (page.html). • A servlet that process and display the output (ProcessServlet). • Another servlet that display the output (ViewServlet). 9
  • 10. The web application will work in the following scenario: the user requests page.html, fill the form, post the data. The data is processed by ProvessServlet, which will forward the request to the ViewServlet to view the data. Although a trivial example, it's the main concept in separating the controller from the view in web design patterns. 6.1. Process Servlet file: WEB-INF/classes/webapp/ProcessServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class ProcessServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { float num1 = Float.parseFloat(request.getParameter("num1")) ; float num2 = Float.parseFloat(request.getParameter("num2")) ; float result = num1 + num2 ; //set attribute to be shared with the delegates request.setAttribute("result", result) ; //create a request dispatcher from the request object RequestDispatcher rd = request.getRequestDispatcher("/view") ; //forward the request passing request and response objects rd.forward(request, response) ; } } 6.2. View Servlet file: WEB-INF/classes/webapp/ViewServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class ViewServlet extends HttpServlet { 10
  • 11. public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { float result = (Float) request.getAttribute("result") ; String message = "Result = " + result ; PrintWriter out = response.getWriter() ; out.println("<html>") ; out.println("<head>") ; out.println("<title>Result by Process Servlet</title>") ; out.println("</head>") ; out.println("<body>") ; out.println(message) ; out.println("</body>") ; out.println("</html>") ; } } 7. HTTP Sessions As we saw later, HTTP is a stateless protocol. To overcome this in stateful web applications, session concept should be implemented. In Java EE, session concept is abstracted and provided via the HttpSession interface. A reference to a session object can obtained using the method HttpSession getSession() in the request object. 7.1. Creating HTTP Session file: WEB-INF/classes/webapp/MyFirstServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class MyFirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession() ; session.setAttribute("user_id", "505") ; } 11
  • 12. } 7.2. Sharing Data Data can be shared using the method void setAttribute(String name, Object value). Any other page can retrieve shared data using the method Object getAttribute(). 12