SlideShare a Scribd company logo
Java Servlets Svetlin Nakov Borislava Spasova
Contents Java Servlets Technology Overview What is a Java Servlet? Servlet Services Why Use Servlets? Time Servlet – Example Deploying Servlets on Eclipse IDE Servlets Architecture Servlets API Servlets Life-Cycle
Contents (2) Servlet Examples Processing Parameters – Hello Servlet Image Counter Servlet Using Sessions What is a Session? The Sessions API Session Timeout Session Examples Login / Logout Application The Browser's Cache Problems
Java Servlets Technology Overview
What is a Java Servlet? Java  Servlets  are: Technology for generating dynamic Web pages (like PHP, ASP, ASP.NET, ...) P rotocol and platform-independent server side components, written in Java , which extend the standard Web servers Java programs that serve HTTP requests The  HttpServlet  class Provides d ynamic  Web content  generation   (HTML, XML, ���)
What is a Java Servlet? (2) Servlets P rovide a general framework for services built  on  the request-response paradigm Portable to any Java application server Have access to the entire family of Java and Java EE APIs JDBC, Persistence, EJB, JMS, JAX-WS, JTA, JTS, RMI, JNDI, JAXP, ... Fundamental part of all Java Web application technologies (JSP, JSF, ...)
Servlet Services Java Servlets provide many useful services Provides low-level API for building Internet services Serves as foundation to JavaServer Pages (JSP) and JavaServer Faces (JSF) technologies Can deliver multiple types of data to any client XML, HTML, WML, GIF, etc... Can serve as “Controller” of JSP/Servlet application
Why Use Servlets? Portability Write once, serve everywhere Power Can take advantage of all Java APIs Elegance Simplicity due to abstraction Efficiency & Endurance  Highly scalable
Why Use Servlets? (2) Safety Strong type-checking  Memory management Integration  Servlets tightly coupled with server Extensibility & Flexibility  Servlets designed to be easily extensible, though currently optimized for HTTP uses Flexible invocation of servlet  (SSI, servlet-chaining, filters, etc.)
Time Servlet – Example import java.io.*;  import javax.servlet.*;  import javax.servlet.http.*;  public class  Time Servlet extends HttpServlet {  public void doGet(HttpServletRequest aRequest,  HttpServletResponse aResponse)  throws ServletException, IOException {  PrintWriter out = aResponse.getWriter();  out.println(&quot;<HTML>&quot;);  out.println(&quot;The time is: &quot; +  new java.util.Date());  out.println(&quot;</HTML>&quot;);  }  }
Deploying Servlets on Eclipse IDE First create new Web application
Deploying Servlets on Eclipse IDE (2) Add new servlet to the Web application
Deploying Servlets on Eclipse IDE (3) Run the servlet
Deploying Servlets on Eclipse IDE (4) The servlet in action
Java Servlets Technical Architecture
Servlets Architecture The  HttpServlet  class Serves client's HTTP requests For each of the HTTP methods, GET, POST,  and others ,  there is c orresponding method : doGet ( … )  – serves HTTP GET requests doPost ( … )  – serves HTTP POST requests doPut ( … ) ,  doHead ( … ) ,  doDelete ( … ) ,  doTrace ( … ) ,  doOptions ( … ) The Servlet usually must implement one of the first two methods or the  service( … )  method
Servlets Architecture (2) The  HttpServletRequest  object Contains the request data from the client HTTP request headers Form data and query parameters Other client data (cookies, path, etc.) The  HttpServletResponse  object Encapsulates data sent back to client HTTP response headers (content type, cookies, etc.) Response body (as  OutputStream )
Servlets Architecture (3) The HTTP GET method is used when: The processing of the request does not change the state of the server The amount of form data is small You want to allow the request to be bookmarked The HTTP POST method is used when: The processing of the request changes the state of the server, e.g. storing data in a DB The amount of form data is large The contents of the data should not be visible in the URL (for example, passwords)
Servlets API The most important servlet functionality: Retrieve  the  HTML form parameters from the request  (both GET and POST parameters) Retrieve a servlet initialization parameter Retrieve HTTP request header information HttpServletRequest.getParameter( String ) ServletConfig.getInitParameter () HttpServletRequest.getHeader( String )
Servlets API (2) Set an HTTP response header  /  content type Acquire a  text  stream for the response Acquire a binary stream for the response Redirect an HTTP request to another URL HttpServletResponse.setHeader (<name>, <value>) /  HttpServletResponse.setContentType( String ) HttpServletResponse.getWriter() HttpServletResponse . getOutputStream() HttpServletResponse.sendRedirect()
Servlets Life-Cycle You can provide an implementation of these methods in  HttpServlet  descendent classes to manipulate the servlet instance and the resources it depends on The Web container manages the life cycle of servlet instances The life-cycle methods should not be called by your code init() ...() service() doGet() doPost() doDelete() destroy() doPut() New Destroyed Running
The init() Method Called by the Web container when the servlet instance is first created The Servlets specification guarantees that no requests will be processed by this servlet until the init method has completed Override the  init()  method when: You need to create or open any  servlet-specific  resources that you need for processing user requests You need to initialize the state of the servlet
The service() Method Called by the Web container to process a user request Dispatches the HTTP requests to  doGet( … ) ,  doPost( … ) ,  etc. depending on the HTTP request method (GET, POST, and so on) Sends the result as HTTP response Usually we do not need to override this method
The destroy() Method Called by the Web container when the servlet instance is being eliminated The Servlet specification guarantees that all requests will be completely processed before this method is called Override the destroy method when: You need to release any  servlet-specific  resources that you had opened in the  init()  method You need to persist the state of the servlet
Java Servlets Examples
Processing Parameters – Hello Servlet We want to create a servlet that takes an user name as a parameter and says &quot;Hello,  <user_name>&quot; We need HTML form with a text field The servlet can later retrieve the value entered in the form field <form method=&quot; GET or POST &quot; action=&quot; the servlet &quot;>  <input type=&quot;text&quot; name=&quot; user_name &quot;> </form> String  n ame =   r equest.getParameter(&quot;user_name&quot;);
Hello Servlet – Example <html><body>  <form method=&quot;GET&quot; action=&quot;HelloServlet&quot;>  Please enter your name:  <input type=&quot;text&quot; name=&quot; user_name &quot;>  <input type=&quot;submit&quot; value=&quot;OK&quot;>  </form>  </body></html> HelloForm.html import java.io.*;  import javax.servlet.*;  import javax.servlet.http.*;  public class HelloServlet extends HttpServlet { Hello Servlet . java
Hello Servlet – Example public void doGet(HttpServletRequest  r equest, HttpServletResponse  r esponse) throws ServletException, IOException { r esponse.setContentType(&quot;text/html&quot;);  ServletOutputStream out =  r esponse.getOutputStream();  String userName =   r equest.getParameter(&quot;user_name&quot;);   out.println(&quot;<html> <head> &quot;);  out.println(&quot;<title>Hello Servlet</title>&quot;);  out.println(&quot;</head><body>&quot;);  out.println(&quot;<h1>Hello, &quot; + userName + &quot;</h1>&quot;);  out.println(&quot;</body></html>&quot;); } Hello Servlet . java
Creating The Form in Eclipse IDE Create new HTML form
Creating New Servlet in Eclipse IDE Create new Servlet
Hello Servlet in Action
Hello Servlet – HTTP Request What happens when the user enters his name? Internet Explorer (IE) sends the following HTTP request to Tomcat GET /FirstWebApp/HelloServlet?user_name=Nakov   HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg,image/pjpeg, application/vnd.ms-excel,   application/vnd.ms-powerpoint, application/msword,   application/x-shockwave-flash, */* Accept-Language: bg Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;   Windows NT 5.1; Q312461) Host: nakov:808 4 Connection: Keep-Alive
Hello Servlet – HTTP Response What happens when Tomcat receive and process the HTTP request Tomcat sends the following HTTP response to Internet Explorer HTTP/1.1 200 OK Content-Length:  100 Date: Fri, 26 Mar 200 6  10:06:28 GMT Server: Apache-Coyote/1.1 <html><head> <title>Hello Servlet</title> </head><body> <h1>Hello, Nakov</h1> </body></html>
Image Counter Servlet We want to create a servlet that displays an image counter (as JPEG image) The servlet should maintain an internal counter Can be initialized in the  init()  method and incremented in the  doGet ()  method It should produce binary output (the JPEG) image The content type should be set to &quot;image/jpeg&quot;
Image Counter Servlet (2) import javax.servlet.*; import javax.servlet.http.*; ... public class ImageCounterServlet extends HttpServlet {  private String mStartDate;  private int mVisitCounter;  public void init() {  mStartDate = (new Date()).toString();  mVisitCounter = 0;  }  public BufferedImage createImage(String msg) { ... }
Image Counter Servlet (3) public void doGet(HttpServletRequest request,  HttpServletResponse response)  throws IOException, ServletException {  String msg;  synchronized(this) {  mVisitCounter++;  msg = &quot;&quot; + mVisitCounter + &quot; visits since &quot; + mStartDate;  }  BufferedImage image = createImage(msg);  response.setContentType(&quot;image/jpeg&quot;);  OutputStream out = response.getOutputStream(); // Encode the image in JPEG format and // write the image to the output stream   }  }
Image Counter Servlet in Action
Using Sessions
What is a Session? A session is a state associated with particular user that is maintained at the server side Sessions persist between the HTTP requests Sessions e nable  creating  applications that depend on individual user data. For example: Login / logout functionality Wizard pages Shopping  c arts Personalization  s ervices Maintaining state about the user’s preferences
Sessions in Servlets Servlets include a built-in Session s  API Sessions are maintained automatically, with no additional coding The Web container associates an unique  HttpSession  object to each different client Different clients have different session objects at the server Requests from the same client have the same session object Sessions can store various data
The Sessions API The sessions API allows To get the  HttpSession  object from the  HTTPServletRequest  object Extract data from the user’s session object Append data to the user’s session object Extract meta-information about the session object, e.g. when was the session created
Getting The Session Object To get  the  session object  use  the  method   HttpServletRequest.getSession() Example: If  the  user already has a session, the existing session is returned If no session  still  exists, a new one is created and returned If you want to know if this is a new session, call the  isNew()  method HttpSession session = request.getSession();
Behind  T he Scenes  When you call  getSession ()  each user is automatically assigned a unique  Session ID How does this Session ID get to the user? Option 1: If the browser supports cookies, the servlet will automatically create a session cookie, and store the session ID within the cookie In Tomcat, the cookie is called  JSESSIONID Option 2: If the browser does not support cookies, the servlet will try to extract the session ID from the URL
Extracting Data From  The  Session  The  s ession object works like a  HashMap E nables  storing  any type of Java object Objects are stored by key (like in hash tables) Extracting existing object: Getting  a list of all “keys”   associated with  the session Integer accessCount = (Integer)   session.getAttribute(&quot;accessCount&quot;); Enumeration attributes = request.getAttributeNames();
Storing  Data  In   The  Session  We can store data in the session object for using it later Objects in the session can be removed when not needed more HttpSession session = request.getSession(); session.setAttribute(&quot;name&quot;, &quot;Svetlin Nakov&quot;); session. remove Attribute(&quot;name&quot;);
Getting  Additional Session Information   Getting the unique session ID associated with this user, e.g.  gj9xswvw9p Checking if the session was just created Checking when the session was first created Checking when the session was last active public boolean isNew(); public String getId(); public long getLastAccessedTime(); public long getCreationTime();
Session Timeout We can get the maximal session validity interval ( in seconds ) After such interval of inactivity the session is automatically invalidated We can modify the maximal inactivity interval A negative value specifies that the session should never time out public int getMaxInactiveInterval(); public void setMaxInactiveInterval (int seconds) ;
Terminating Sessions  To terminate session manually use the method: Typically done during the &quot;user logout&quot; The session can become invalid not only manually Sessions can expire automatically due to inactivity public void invalidate() ;
Login / Logout – Example We want to create a simple Web application that restricts the access by login form We will use sessions to store information about the authenticated users We will use the key &quot;username&quot; When it present, there is a logged in user During the login we will add the user name in the session Logout will invalidate the session The main servlet will check the current user
Login Form <html> <head><title>Login</title></head> <body> <form method=&quot;POST&quot; action=&quot;LoginServlet&quot;> Please login:<br> Username:  <input type=&quot;text&quot; name=&quot;username&quot;><br> Password:  <input type=&quot;password&quot; name=&quot;password&quot;><br> <input type=&quot;submit&quot; value=&quot;Login&quot;> </form> </body> </html> LoginForm.html
Login Servlet public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String username =   req.getParameter(&quot;username&quot;); String password =   req.getParameter(&quot;password&quot;); PrintWriter out = resp.getWriter(); if (isLoginValid(username, password)) { HttpSession session = req.getSession(); session.setAttribute(&quot;USER&quot;, username); response.sendRedirect(&quot;MainServlet&quot;); } else { response.sendRedirect(&quot;InvalidLogin.html&quot;); } } } Login Servlet . java
Main Servlet public class MainServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = request.getSession(); String userName = (String)   s ession.getAttribute(&quot;USER&quot;); if (userName != null) { response.setContentType(&quot;text/html&quot;); ServletOutputStream out =   resp.getOutputStream(); out.println(&quot;<html> <body><h1> &quot;); out.println(&quot;Hello, &quot; + userName + &quot;! &quot;); out.println(&quot; </h1> </body></html>&quot;); } else { response.sendRedirect(&quot;LoginForm.html&quot;); } } } MainServlet.java
Logout Servlet public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.invalidate(); response.setContentType(&quot;text/html&quot;); ServletOutputStream out = response.getOutputStream(); out.println(&quot;<html><head>&quot;); out.println(&quot;<title>Logout</title></head>&quot;); out.println(&quot;<body>&quot;); out.println(&quot;<h1>Logout successfull.</h1>&quot;); out.println(&quot;</body></html>&quot;); } } LogoutServlet.java
Invalid Login Page <html> <head> <title>Error</title> </head> <body> <h1>Invalid login!</h1> Please <a href=&quot;LoginForm.html&quot;>try again</a>. </body> </html> InvalidLogin.html
The Browser's Cache Problems Most Web browsers use caching of the displayed pages and images This can cause the user to see old state of the pages Seems like a bug in the application To prevent showing the old state we need to disable the browser cache: response.setHeader(&quot;Pragma&quot;, &quot;No-cache&quot;); response.setDateHeader(&quot;Expires&quot;, 0); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;);
Problems Create a servlet that prints in a table the numbers from 1 to 1000 and their square root. Create a servlet that takes as parameters two integer numbers and calculates their sum. Create a HTML form that invokes the servlet. Try to use GET and POST methods. Implement a servlet that plays the &quot;Number guess game&quot;. When the client first invoke the servlet it generates a random number in the range [1..100]. The user is asked to guess this number. At each guess the servlet says only &quot;greater&quot; or &quot;smaller&quot;. The game ends when the user tell the number.
Homework Create a servlet that takes as a parameter a number and displays it as image that is hard to be recognized by OCR software. The image should have intentionally inserted defects. Create an HTML form and a servlet for performing conversions of distances from one metric to another. The metrics that should be supported are: meter, centimeter, kilometer, foot, inch, yard, mile. 1 cm = 0.01 meters 1 km = 1000 meters 1 foot = 0.3048 meters 1 inch = 0.0254 meters  1 yard = 0.9144 meters 1 mile = 1609.344 meters
Homework (2) Create a sequence of HTML forms and servlets that allow entering information about a student. The information is entered in 3 steps in 3 separate forms: Step 1: First name, last name, age Step 2: Address (country, town, street) Step 3: University, faculty, specialty The data entered in the 3 steps should be stored in the session and finally displayed. Create a servlet that reads an image (from  WEB-INFmgogo.gif ) and returns it.

More Related Content

What's hot

Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
Surbhi Panhalkar
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
prabhu rajendran
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
Halil Burak Cetinkaya
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Kasun Madusanke
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
Servlets
ServletsServlets
Servlets
Geethu Mohan
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
Naveen Sihag
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
UC San Diego
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
Venkateswara Rao N
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Event handling
Event handlingEvent handling
Event handling
swapnac12
 

What's hot (20)

Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Servlets
ServletsServlets
Servlets
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Javascript
JavascriptJavascript
Javascript
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Event handling
Event handlingEvent handling
Event handling
 

Viewers also liked

Java Servlets
Java ServletsJava Servlets
Java Servlets
Nitin Pai
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
kamal kotecha
 
Java basic
Java basicJava basic
Java basic
Sonam Sharma
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
Ravi Kant Sahu
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
Eduonix Learning Solutions
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
mahir jain
 
Core java slides
Core java slidesCore java slides
Core java slides
Abhilash Nair
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Veerabadra Badra
 

Viewers also liked (11)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java basic
Java basicJava basic
Java basic
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Core java slides
Core java slidesCore java slides
Core java slides
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Similar to Java Servlets

Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
Arumugam90
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
Ankit Minocha
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
Shubhani Jain
 
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
bharathiv53
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
Servlets
ServletsServlets
SCWCD 2. servlet req - resp (cap3 - cap4)
SCWCD 2. servlet   req - resp (cap3 - cap4)SCWCD 2. servlet   req - resp (cap3 - cap4)
SCWCD 2. servlet req - resp (cap3 - cap4)
Francesco Ierna
 
Server-side Technologies in Java
Server-side Technologies in JavaServer-side Technologies in Java
Server-side Technologies in Java
Anirban Majumdar
 
18CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-318CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-3
sivakumarmcs
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
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
 
Servlet by Rj
Servlet by RjServlet by Rj
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
Eleonora Ciceri
 

Similar to Java Servlets (20)

Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Servlet
Servlet Servlet
Servlet
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
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
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Servlets
ServletsServlets
Servlets
 
SCWCD 2. servlet req - resp (cap3 - cap4)
SCWCD 2. servlet   req - resp (cap3 - cap4)SCWCD 2. servlet   req - resp (cap3 - cap4)
SCWCD 2. servlet req - resp (cap3 - cap4)
 
Server-side Technologies in Java
Server-side Technologies in JavaServer-side Technologies in Java
Server-side Technologies in Java
 
18CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-318CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-3
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
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...
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 

More from BG Java EE Course

Rich faces
Rich facesRich faces
Rich faces
BG Java EE Course
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
BG Java EE Course
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
BG Java EE Course
 
JSTL
JSTLJSTL
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
BG Java EE Course
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
BG Java EE Course
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
BG Java EE Course
 
CSS
CSSCSS
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
BG Java EE Course
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
BG Java EE Course
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
BG Java EE Course
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
BG Java EE Course
 
Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
BG Java EE Course
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
BG Java EE Course
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
BG Java EE Course
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
BG Java EE Course
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
BG Java EE Course
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
BG Java EE Course
 

More from BG Java EE Course (20)

Rich faces
Rich facesRich faces
Rich faces
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
JSTL
JSTLJSTL
JSTL
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
CSS
CSSCSS
CSS
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
 
Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 

Recently uploaded

DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
Toru Tamaki
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Mydbops
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Erasmo Purificato
 
20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf
Sally Laouacheria
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
Matthew Sinclair
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Chris Swan
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
Matthew Sinclair
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 

Recently uploaded (20)

DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
 
20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 

Java Servlets

  • 1. Java Servlets Svetlin Nakov Borislava Spasova
  • 2. Contents Java Servlets Technology Overview What is a Java Servlet? Servlet Services Why Use Servlets? Time Servlet – Example Deploying Servlets on Eclipse IDE Servlets Architecture Servlets API Servlets Life-Cycle
  • 3. Contents (2) Servlet Examples Processing Parameters – Hello Servlet Image Counter Servlet Using Sessions What is a Session? The Sessions API Session Timeout Session Examples Login / Logout Application The Browser's Cache Problems
  • 5. What is a Java Servlet? Java Servlets are: Technology for generating dynamic Web pages (like PHP, ASP, ASP.NET, ...) P rotocol and platform-independent server side components, written in Java , which extend the standard Web servers Java programs that serve HTTP requests The HttpServlet class Provides d ynamic Web content generation (HTML, XML, …)
  • 6. What is a Java Servlet? (2) Servlets P rovide a general framework for services built on the request-response paradigm Portable to any Java application server Have access to the entire family of Java and Java EE APIs JDBC, Persistence, EJB, JMS, JAX-WS, JTA, JTS, RMI, JNDI, JAXP, ... Fundamental part of all Java Web application technologies (JSP, JSF, ...)
  • 7. Servlet Services Java Servlets provide many useful services Provides low-level API for building Internet services Serves as foundation to JavaServer Pages (JSP) and JavaServer Faces (JSF) technologies Can deliver multiple types of data to any client XML, HTML, WML, GIF, etc... Can serve as “Controller” of JSP/Servlet application
  • 8. Why Use Servlets? Portability Write once, serve everywhere Power Can take advantage of all Java APIs Elegance Simplicity due to abstraction Efficiency & Endurance Highly scalable
  • 9. Why Use Servlets? (2) Safety Strong type-checking Memory management Integration Servlets tightly coupled with server Extensibility & Flexibility Servlets designed to be easily extensible, though currently optimized for HTTP uses Flexible invocation of servlet (SSI, servlet-chaining, filters, etc.)
  • 10. Time Servlet – Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Time Servlet extends HttpServlet { public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException { PrintWriter out = aResponse.getWriter(); out.println(&quot;<HTML>&quot;); out.println(&quot;The time is: &quot; + new java.util.Date()); out.println(&quot;</HTML>&quot;); } }
  • 11. Deploying Servlets on Eclipse IDE First create new Web application
  • 12. Deploying Servlets on Eclipse IDE (2) Add new servlet to the Web application
  • 13. Deploying Servlets on Eclipse IDE (3) Run the servlet
  • 14. Deploying Servlets on Eclipse IDE (4) The servlet in action
  • 15. Java Servlets Technical Architecture
  • 16. Servlets Architecture The HttpServlet class Serves client's HTTP requests For each of the HTTP methods, GET, POST, and others , there is c orresponding method : doGet ( … ) – serves HTTP GET requests doPost ( … ) – serves HTTP POST requests doPut ( … ) , doHead ( … ) , doDelete ( … ) , doTrace ( … ) , doOptions ( … ) The Servlet usually must implement one of the first two methods or the service( … ) method
  • 17. Servlets Architecture (2) The HttpServletRequest object Contains the request data from the client HTTP request headers Form data and query parameters Other client data (cookies, path, etc.) The HttpServletResponse object Encapsulates data sent back to client HTTP response headers (content type, cookies, etc.) Response body (as OutputStream )
  • 18. Servlets Architecture (3) The HTTP GET method is used when: The processing of the request does not change the state of the server The amount of form data is small You want to allow the request to be bookmarked The HTTP POST method is used when: The processing of the request changes the state of the server, e.g. storing data in a DB The amount of form data is large The contents of the data should not be visible in the URL (for example, passwords)
  • 19. Servlets API The most important servlet functionality: Retrieve the HTML form parameters from the request (both GET and POST parameters) Retrieve a servlet initialization parameter Retrieve HTTP request header information HttpServletRequest.getParameter( String ) ServletConfig.getInitParameter () HttpServletRequest.getHeader( String )
  • 20. Servlets API (2) Set an HTTP response header / content type Acquire a text stream for the response Acquire a binary stream for the response Redirect an HTTP request to another URL HttpServletResponse.setHeader (<name>, <value>) / HttpServletResponse.setContentType( String ) HttpServletResponse.getWriter() HttpServletResponse . getOutputStream() HttpServletResponse.sendRedirect()
  • 21. Servlets Life-Cycle You can provide an implementation of these methods in HttpServlet descendent classes to manipulate the servlet instance and the resources it depends on The Web container manages the life cycle of servlet instances The life-cycle methods should not be called by your code init() ...() service() doGet() doPost() doDelete() destroy() doPut() New Destroyed Running
  • 22. The init() Method Called by the Web container when the servlet instance is first created The Servlets specification guarantees that no requests will be processed by this servlet until the init method has completed Override the init() method when: You need to create or open any servlet-specific resources that you need for processing user requests You need to initialize the state of the servlet
  • 23. The service() Method Called by the Web container to process a user request Dispatches the HTTP requests to doGet( … ) , doPost( … ) , etc. depending on the HTTP request method (GET, POST, and so on) Sends the result as HTTP response Usually we do not need to override this method
  • 24. The destroy() Method Called by the Web container when the servlet instance is being eliminated The Servlet specification guarantees that all requests will be completely processed before this method is called Override the destroy method when: You need to release any servlet-specific resources that you had opened in the init() method You need to persist the state of the servlet
  • 26. Processing Parameters – Hello Servlet We want to create a servlet that takes an user name as a parameter and says &quot;Hello, <user_name>&quot; We need HTML form with a text field The servlet can later retrieve the value entered in the form field <form method=&quot; GET or POST &quot; action=&quot; the servlet &quot;> <input type=&quot;text&quot; name=&quot; user_name &quot;> </form> String n ame = r equest.getParameter(&quot;user_name&quot;);
  • 27. Hello Servlet – Example <html><body> <form method=&quot;GET&quot; action=&quot;HelloServlet&quot;> Please enter your name: <input type=&quot;text&quot; name=&quot; user_name &quot;> <input type=&quot;submit&quot; value=&quot;OK&quot;> </form> </body></html> HelloForm.html import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { Hello Servlet . java
  • 28. Hello Servlet – Example public void doGet(HttpServletRequest r equest, HttpServletResponse r esponse) throws ServletException, IOException { r esponse.setContentType(&quot;text/html&quot;); ServletOutputStream out = r esponse.getOutputStream(); String userName = r equest.getParameter(&quot;user_name&quot;); out.println(&quot;<html> <head> &quot;); out.println(&quot;<title>Hello Servlet</title>&quot;); out.println(&quot;</head><body>&quot;); out.println(&quot;<h1>Hello, &quot; + userName + &quot;</h1>&quot;); out.println(&quot;</body></html>&quot;); } Hello Servlet . java
  • 29. Creating The Form in Eclipse IDE Create new HTML form
  • 30. Creating New Servlet in Eclipse IDE Create new Servlet
  • 32. Hello Servlet – HTTP Request What happens when the user enters his name? Internet Explorer (IE) sends the following HTTP request to Tomcat GET /FirstWebApp/HelloServlet?user_name=Nakov HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg,image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */* Accept-Language: bg Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461) Host: nakov:808 4 Connection: Keep-Alive
  • 33. Hello Servlet – HTTP Response What happens when Tomcat receive and process the HTTP request Tomcat sends the following HTTP response to Internet Explorer HTTP/1.1 200 OK Content-Length: 100 Date: Fri, 26 Mar 200 6 10:06:28 GMT Server: Apache-Coyote/1.1 <html><head> <title>Hello Servlet</title> </head><body> <h1>Hello, Nakov</h1> </body></html>
  • 34. Image Counter Servlet We want to create a servlet that displays an image counter (as JPEG image) The servlet should maintain an internal counter Can be initialized in the init() method and incremented in the doGet () method It should produce binary output (the JPEG) image The content type should be set to &quot;image/jpeg&quot;
  • 35. Image Counter Servlet (2) import javax.servlet.*; import javax.servlet.http.*; ... public class ImageCounterServlet extends HttpServlet { private String mStartDate; private int mVisitCounter; public void init() { mStartDate = (new Date()).toString(); mVisitCounter = 0; } public BufferedImage createImage(String msg) { ... }
  • 36. Image Counter Servlet (3) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String msg; synchronized(this) { mVisitCounter++; msg = &quot;&quot; + mVisitCounter + &quot; visits since &quot; + mStartDate; } BufferedImage image = createImage(msg); response.setContentType(&quot;image/jpeg&quot;); OutputStream out = response.getOutputStream(); // Encode the image in JPEG format and // write the image to the output stream } }
  • 39. What is a Session? A session is a state associated with particular user that is maintained at the server side Sessions persist between the HTTP requests Sessions e nable creating applications that depend on individual user data. For example: Login / logout functionality Wizard pages Shopping c arts Personalization s ervices Maintaining state about the user’s preferences
  • 40. Sessions in Servlets Servlets include a built-in Session s API Sessions are maintained automatically, with no additional coding The Web container associates an unique HttpSession object to each different client Different clients have different session objects at the server Requests from the same client have the same session object Sessions can store various data
  • 41. The Sessions API The sessions API allows To get the HttpSession object from the HTTPServletRequest object Extract data from the user’s session object Append data to the user’s session object Extract meta-information about the session object, e.g. when was the session created
  • 42. Getting The Session Object To get the session object use the method HttpServletRequest.getSession() Example: If the user already has a session, the existing session is returned If no session still exists, a new one is created and returned If you want to know if this is a new session, call the isNew() method HttpSession session = request.getSession();
  • 43. Behind T he Scenes When you call getSession () each user is automatically assigned a unique Session ID How does this Session ID get to the user? Option 1: If the browser supports cookies, the servlet will automatically create a session cookie, and store the session ID within the cookie In Tomcat, the cookie is called JSESSIONID Option 2: If the browser does not support cookies, the servlet will try to extract the session ID from the URL
  • 44. Extracting Data From The Session The s ession object works like a HashMap E nables storing any type of Java object Objects are stored by key (like in hash tables) Extracting existing object: Getting a list of all “keys” associated with the session Integer accessCount = (Integer) session.getAttribute(&quot;accessCount&quot;); Enumeration attributes = request.getAttributeNames();
  • 45. Storing Data In The Session We can store data in the session object for using it later Objects in the session can be removed when not needed more HttpSession session = request.getSession(); session.setAttribute(&quot;name&quot;, &quot;Svetlin Nakov&quot;); session. remove Attribute(&quot;name&quot;);
  • 46. Getting Additional Session Information Getting the unique session ID associated with this user, e.g. gj9xswvw9p Checking if the session was just created Checking when the session was first created Checking when the session was last active public boolean isNew(); public String getId(); public long getLastAccessedTime(); public long getCreationTime();
  • 47. Session Timeout We can get the maximal session validity interval ( in seconds ) After such interval of inactivity the session is automatically invalidated We can modify the maximal inactivity interval A negative value specifies that the session should never time out public int getMaxInactiveInterval(); public void setMaxInactiveInterval (int seconds) ;
  • 48. Terminating Sessions To terminate session manually use the method: Typically done during the &quot;user logout&quot; The session can become invalid not only manually Sessions can expire automatically due to inactivity public void invalidate() ;
  • 49. Login / Logout – Example We want to create a simple Web application that restricts the access by login form We will use sessions to store information about the authenticated users We will use the key &quot;username&quot; When it present, there is a logged in user During the login we will add the user name in the session Logout will invalidate the session The main servlet will check the current user
  • 50. Login Form <html> <head><title>Login</title></head> <body> <form method=&quot;POST&quot; action=&quot;LoginServlet&quot;> Please login:<br> Username: <input type=&quot;text&quot; name=&quot;username&quot;><br> Password: <input type=&quot;password&quot; name=&quot;password&quot;><br> <input type=&quot;submit&quot; value=&quot;Login&quot;> </form> </body> </html> LoginForm.html
  • 51. Login Servlet public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String username = req.getParameter(&quot;username&quot;); String password = req.getParameter(&quot;password&quot;); PrintWriter out = resp.getWriter(); if (isLoginValid(username, password)) { HttpSession session = req.getSession(); session.setAttribute(&quot;USER&quot;, username); response.sendRedirect(&quot;MainServlet&quot;); } else { response.sendRedirect(&quot;InvalidLogin.html&quot;); } } } Login Servlet . java
  • 52. Main Servlet public class MainServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = request.getSession(); String userName = (String) s ession.getAttribute(&quot;USER&quot;); if (userName != null) { response.setContentType(&quot;text/html&quot;); ServletOutputStream out = resp.getOutputStream(); out.println(&quot;<html> <body><h1> &quot;); out.println(&quot;Hello, &quot; + userName + &quot;! &quot;); out.println(&quot; </h1> </body></html>&quot;); } else { response.sendRedirect(&quot;LoginForm.html&quot;); } } } MainServlet.java
  • 53. Logout Servlet public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.invalidate(); response.setContentType(&quot;text/html&quot;); ServletOutputStream out = response.getOutputStream(); out.println(&quot;<html><head>&quot;); out.println(&quot;<title>Logout</title></head>&quot;); out.println(&quot;<body>&quot;); out.println(&quot;<h1>Logout successfull.</h1>&quot;); out.println(&quot;</body></html>&quot;); } } LogoutServlet.java
  • 54. Invalid Login Page <html> <head> <title>Error</title> </head> <body> <h1>Invalid login!</h1> Please <a href=&quot;LoginForm.html&quot;>try again</a>. </body> </html> InvalidLogin.html
  • 55. The Browser's Cache Problems Most Web browsers use caching of the displayed pages and images This can cause the user to see old state of the pages Seems like a bug in the application To prevent showing the old state we need to disable the browser cache: response.setHeader(&quot;Pragma&quot;, &quot;No-cache&quot;); response.setDateHeader(&quot;Expires&quot;, 0); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;);
  • 56. Problems Create a servlet that prints in a table the numbers from 1 to 1000 and their square root. Create a servlet that takes as parameters two integer numbers and calculates their sum. Create a HTML form that invokes the servlet. Try to use GET and POST methods. Implement a servlet that plays the &quot;Number guess game&quot;. When the client first invoke the servlet it generates a random number in the range [1..100]. The user is asked to guess this number. At each guess the servlet says only &quot;greater&quot; or &quot;smaller&quot;. The game ends when the user tell the number.
  • 57. Homework Create a servlet that takes as a parameter a number and displays it as image that is hard to be recognized by OCR software. The image should have intentionally inserted defects. Create an HTML form and a servlet for performing conversions of distances from one metric to another. The metrics that should be supported are: meter, centimeter, kilometer, foot, inch, yard, mile. 1 cm = 0.01 meters 1 km = 1000 meters 1 foot = 0.3048 meters 1 inch = 0.0254 meters 1 yard = 0.9144 meters 1 mile = 1609.344 meters
  • 58. Homework (2) Create a sequence of HTML forms and servlets that allow entering information about a student. The information is entered in 3 steps in 3 separate forms: Step 1: First name, last name, age Step 2: Address (country, town, street) Step 3: University, faculty, specialty The data entered in the 3 steps should be stored in the session and finally displayed. Create a servlet that reads an image (from WEB-INFmgogo.gif ) and returns it.

Editor's Notes

  1. ## * * 07/16/96
  2. ## * * 07/16/96
  3. ## * * 07/16/96 Example of HTTP GET: Google search Example of HTTP POST: Login page
  4. ## * * 07/16/96
  5. ## * * 07/16/96
  6. ## * * 07/16/96
  7. ## * * 07/16/96
  8. Note: As of Servlet 2.2, the getValue() method is now deprecated. Use getAttribute() instead.
  9. Note: As of Servlet 2.2, the getValue() method is now deprecated. Use getAttribute() instead.