SlideShare a Scribd company logo
1 of 58
Java Servlets Svetlin Nakov Borislava Spasova
Contents ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Contents (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java Servlets Technology Overview
What is a Java Servlet? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What is a Java Servlet? (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Servlet Services ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Why Use Servlets? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Why Use Servlets? (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Time Servlet – Example ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Deploying Servlets on Eclipse IDE ,[object Object]
Deploying Servlets on Eclipse IDE (2) ,[object Object]
Deploying Servlets on Eclipse IDE (3) ,[object Object]
Deploying Servlets on Eclipse IDE (4) ,[object Object]
Java Servlets Technical Architecture
Servlets Architecture ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Servlets Architecture (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Servlets Architecture (3) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Servlets API ,[object Object],[object Object],[object Object],[object Object],HttpServletRequest.getParameter( String ) ServletConfig.getInitParameter () HttpServletRequest.getHeader( String )
Servlets API (2) ,[object Object],[object Object],[object Object],[object Object],HttpServletResponse.setHeader (<name>, <value>) /  HttpServletResponse.setContentType( String ) HttpServletResponse.getWriter() HttpServletResponse . getOutputStream() HttpServletResponse.sendRedirect()
Servlets Life-Cycle ,[object Object],[object Object],[object Object],init() ...() service() doGet() doPost() doDelete() destroy() doPut() New Destroyed Running
The init() Method ,[object Object],[object Object],[object Object],[object Object],[object Object]
The service() Method ,[object Object],[object Object],[object Object],[object Object]
The destroy() Method ,[object Object],[object Object],[object Object],[object Object],[object Object]
Java Servlets Examples
Processing Parameters – Hello Servlet ,[object Object],[object Object],[object Object],<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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],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 ,[object Object]
Creating New Servlet in Eclipse IDE ,[object Object]
Hello Servlet in Action
Hello Servlet – HTTP Request ,[object Object],[object Object],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 ,[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object]
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? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Sessions in Servlets ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The Sessions API ,[object Object],[object Object],[object Object],[object Object],[object Object]
Getting The Session Object ,[object Object],[object Object],[object Object],[object Object],[object Object],HttpSession session = request.getSession();
Behind  T he Scenes  ,[object Object],[object Object],[object Object],[object Object],[object Object]
Extracting Data From  The  Session  ,[object Object],[object Object],[object Object],[object Object],[object Object],Integer accessCount = (Integer)   session.getAttribute(&quot;accessCount&quot;); Enumeration attributes = request.getAttributeNames();
Storing  Data  In   The  Session  ,[object Object],[object Object],HttpSession session = request.getSession(); session.setAttribute(&quot;name&quot;, &quot;Svetlin Nakov&quot;); session. remove Attribute(&quot;name&quot;);
Getting  Additional Session Information   ,[object Object],[object Object],[object Object],[object Object],public boolean isNew(); public String getId(); public long getLastAccessedTime(); public long getCreationTime();
Session Timeout ,[object Object],[object Object],[object Object],[object Object],public int getMaxInactiveInterval(); public void setMaxInactiveInterval (int seconds) ;
Terminating Sessions  ,[object Object],[object Object],[object Object],[object Object],public void invalidate() ;
Login / Logout – Example ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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 ,[object Object],[object Object],[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object]
Homework ,[object Object],[object Object],[object Object],[object Object],[object Object]
Homework (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

More Related Content

What's hot

Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 

What's hot (20)

jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Introduction of Html/css/js
Introduction of Html/css/jsIntroduction of Html/css/js
Introduction of Html/css/js
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
servlet in java
servlet in javaservlet in java
servlet in java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 

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

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
 
Servlets
ServletsServlets
Servlets
 
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
 
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

Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
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
 

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

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Java Servlets

  • 1. Java Servlets Svetlin Nakov Borislava Spasova
  • 2.
  • 3.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15. Java Servlets Technical Architecture
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 26.
  • 27.
  • 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.
  • 30.
  • 32.
  • 33.
  • 34.
  • 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.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 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.
  • 56.
  • 57.
  • 58.

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.