SlideShare una empresa de Scribd logo
1 de 90
IADCS Diploma Course Java Servlet Programming U Nyein Oo COO/Director (IT) Myanma Computer Co., Ltd(MCC)
Road Map ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What is a Servlet? ,[object Object],[object Object],[object Object],[object Object]
Life of a Servlet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Life of a Servlet (cont.) ,[object Object],[object Object],[object Object],[object Object],[object Object]
Life of a Servlet Web Browser Web Server Java Servlet Database 1,2 3 4,5 6
What can you build with Servlets? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Server Side Options ,[object Object],[object Object],[object Object],[object Object]
Server Side Options ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Common Features ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Decision Points ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Option 1:  CGI ,[object Object],[object Object],[object Object],[object Object]
CGI Architecture ,[object Object],[object Object],[object Object],Web Browser Web Server Perl/CGI Create New process
CGI Architecture ,[object Object],Browser 1 Web Server Perl 1 Browser 2 Browser N Perl 2 Perl N
CGI Architecture ,[object Object],[object Object],[object Object]
Option 2:  Fast CGI  ,[object Object],[object Object],[object Object],[object Object],[object Object]
Option 3:  Mod Perl ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Option 4:  ASP ,[object Object],[object Object],[object Object],[object Object],[object Object]
Option 5:  Cold Fusion ,[object Object],[object Object],[object Object],[object Object]
Option 6:  PHP ,[object Object],[object Object],[object Object],[object Object]
Advantages of Servlets ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Advantage 1:  Efficient ,[object Object],[object Object],[object Object]
Advantage 2:  Convenient ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Advantage 3:  Powerful ,[object Object],[object Object],[object Object],[object Object]
Advantage 4:  Portable ,[object Object],[object Object],[object Object],[object Object]
Advantage 5:  Secure ,[object Object],[object Object],[object Object],[object Object]
Advantage 6:  Inexpensive ,[object Object],[object Object],[object Object]
Java Server Pages ,[object Object],[object Object],[object Object]
Servlets v. JSP ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Servlet Engine ,[object Object],[object Object],[object Object],[object Object]
Stand Alone Servlet Engine ,[object Object],[object Object],[object Object]
Add-On Servlet Engine ,[object Object],[object Object]
Embedded Servlet Engine ,[object Object]
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(&quot;text/html&quot;); PrintWriter out = res.getWriter(); out.println(&quot;<HTML>&quot;); out.println(&quot;<HEAD><TITLE>Hello World</TITLE></HEAD>&quot;); out.println(&quot;<BODY>&quot;); out.println(&quot;<BIG>Hello World</BIG>&quot;); out.println(&quot;</BODY></HTML>&quot;); } } A Java Servlet : Looks like a regular  Java program
<html>  <head> <title>Hello, World JSP Example</title> </head>  <body> <h2> Hello, World!  The current time in milliseconds is  <%= System.currentTimeMillis() %>  </h2> </body> </html>  A JSP Page : Looks like a regular  HTML page. Embedded Java command to print current time.
Servlet Lift Cycle ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Life of a Servlet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Birth of Servlet The init() method ,[object Object],[object Object],[object Object]
Simple 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]
//  Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); out.println (&quot;I was born on:  &quot;+birthDate); out.close(); } }
Life of a Servlet ,[object Object],[object Object],[object Object]
Service() Method ,[object Object],Browser Browser Browser Web Server Single Instance of Servlet service() service() service()
Let’s Prove it… ,[object Object],[object Object],[object Object],[object Object],[object Object]
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Counter extends HttpServlet { //  Create an instance variable int count = 0; //  Handle an HTTP GET Request public void doGet(HttpServletRequest request,  HttpServletResponse response) throws IOException, ServletException  { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); count++; out.println (&quot;Since loading, this servlet has &quot; + &quot;been accessed &quot;+ count + &quot; times.&quot;); out.close(); } } Only one instance of the counter Servlet is created. Each browser request is therefore incrementing the same count variable.
The Service Method ,[object Object],[object Object],[object Object],[object Object]
Thread Synchronization ,[object Object],[object Object],[object Object]
package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class UserIDs extends HttpServlet { private int nextID = 0; public void doGet( HttpServletRequest  request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); String title = &quot;Your ID&quot;; String docType = … String id = &quot;User-ID-&quot; + nextID; out.println(&quot;<H2>&quot; + id + &quot;</H2>&quot;); nextID = nextID + 1; out.println(&quot;</BODY></HTML>&quot;); } } This code is problematic.  Can result in a race condition,  where two users can actually get the same User-ID!  For example: User 1 makes request: String id = &quot;User-ID-&quot; + nextID;  Gets nextId of 45. Now User 2 makes request, and pre-empts user 1: String id = &quot;User-ID-&quot; + nextID;  Gets nextId of 45 (same one!) Admittedly, this case is rare, but it’s especially problematic. Imagine if user Id was tied to credit card number!
How to Solve Synchronization Problems ,[object Object],[object Object],[object Object],[object Object]
Java Synchronization ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
SingleThreadModel Interface ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Death of a Servlet ,[object Object],[object Object],[object Object],[object Object],[object Object]
Example:  Death.java ,[object Object],[object Object],[object Object]
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Death extends HttpServlet { //  Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse  response)  throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); out.println (&quot;I am alive!&quot;); out.close(); } Continued….
//  This method is called when one stops //  the Java Web Server public void destroy() { try { FileWriter fileWriter = new FileWriter (&quot;rip.txt&quot;); Date now = new Date(); String rip = &quot;I was destroyed at:  &quot;+now.toString(); fileWriter.write (rip); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
A Persistent Counter ,[object Object],[object Object],[object Object],[object Object]
Persistent Counter ,[object Object],[object Object],[object Object]
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterPersist extends HttpServlet { String fileName = &quot;counter.txt&quot;; int count; public void init () { try {   FileReader fileReader = new FileReader (fileName);   BufferedReader bufferedReader = new BufferedReader (fileReader);   String initial = bufferedReader.readLine();   count = Integer.parseInt (initial); } catch (FileNotFoundException e) { count = 0; }  catch (IOException e) {  count = 0; }  catch (NumberFormatException e) { count = 0; } } At Start-up, load the counter from file. In the event of any exception, initialize count to 0. Continued….
//  Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException  { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); count++; out.println (&quot;Since loading, this servlet has &quot; +&quot;been accessed &quot;+ count + &quot; times.&quot;); out.close(); } Each time the doGet() method is called, increment the count variable. Continued….
//  At Shutdown, store counter back to file public void destroy() { try { FileWriter fileWriter = new FileWriter (fileName); String countStr = Integer.toString (count); fileWriter.write (countStr); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } When destroy() is called, store new counter variable back to counter.txt. Any problems with this code?
Tips for Debugging Servlets ,[object Object],[object Object],[object Object],[object Object],[object Object]
Servlet Cookie API ,[object Object],[object Object],[object Object],[object Object],[object Object]
Creating Cookies ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
1.  Cookie Constructor ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
2.  Set Cookie Attributes ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Cookie Name ,[object Object],[object Object],public String getName(); public void setName (String name);
Cookie Value ,[object Object],[object Object],public String getValue(); public void setValue (String value);
Domain Attributes public String getDomain (); public void setDomain(String domain); ,[object Object],[object Object]
Domain Example ,[object Object],[object Object],[object Object],[object Object]
Cookie Age ,[object Object],[object Object],[object Object],public int getMaxAge (); public void setMaxAge (int lifetime);
Cookie Expiration ,[object Object],[object Object],[object Object],[object Object],[object Object]
Path ,[object Object],public String getPath(); public void setPath (String path);
Path Example ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Cookie Version ,[object Object],[object Object],public int getVersion (); public void setVersion (int version);
Security ,[object Object],[object Object],public int getSecure (); public void setSecure (boolean);
Comments ,[object Object],[object Object],public int getComment (); public void Comment (String)
3.  Add Cookies to Response ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Reading Cookies ,[object Object],[object Object],[object Object],[object Object],[object Object]
Reading Cookies ,[object Object],[object Object]
Example I: Cookie Counter ,[object Object],[object Object],[object Object]
The Code ,[object Object],[object Object],[object Object],[object Object],[object Object]
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CookieCounter extends HttpServlet { public void doGet(HttpServletRequest req,  HttpServletResponse res)  throws ServletException, IOException { String name, value = null; Cookie cookie; int counter; res.setContentType(&quot;text/html&quot;); //  Try to extract the counter cookie (if one exists) Cookie[] cookies =  req.getCookies(); for (int i=0; i<cookies.length; i++) { cookie = cookies[i]; name = cookie.getName(); if (name.equals(&quot;counter&quot;)) value = cookie.getValue(); }
//  If possible, parse the counter value //  Otherwise, start over at 0. if (value != null) counter = Integer.parseInt (value); else counter = 0; //  Increment the counter counter++; //  Create a new counter cookie //  Cookie will exist for one year cookie = new Cookie (&quot;counter&quot;, Integer.toString(counter)); cookie.setMaxAge (60*60*24*365); res.addCookie (cookie); //  Output number of visits PrintWriter out = res.getWriter(); out.println (&quot;<HTML><BODY>&quot;); out.println (&quot;<H1>Number of visits:  &quot;+counter); out.println (&quot;</H1>&quot;); out.println (&quot;</BODY></HTML>&quot;); out.close(); } }
HTTP Tracer ,[object Object]
Example II:  Creating/Reading  Multiple Cookies ,[object Object],[object Object],[object Object],[object Object]
SetCookies.java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie(&quot;Session-Cookie-&quot; + i, &quot;Cookie-Value-S&quot; + i); response.addCookie(cookie); cookie = new Cookie(&quot;Persistent-Cookie-&quot; + i, &quot;Cookie-Value-P&quot; + i); // Cookie is valid for a year, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge (60*60*24*365); response.addCookie(cookie);  }  Code Fragment
ShowCookies.java ,[object Object],[object Object],[object Object]
Code Fragment ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thank You!

Más contenido relacionado

La actualidad más candente

Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
vantinhkhuc
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 

La actualidad más candente (20)

JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Servlets
ServletsServlets
Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
 
Servlets
ServletsServlets
Servlets
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Servlets
ServletsServlets
Servlets
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 

Similar a Programming Server side with Sevlet

Similar a Programming Server side with Sevlet (20)

Ecom 1
Ecom 1Ecom 1
Ecom 1
 
Web II - 01 - Introduction to server-side development
Web II - 01 - Introduction to server-side developmentWeb II - 01 - Introduction to server-side development
Web II - 01 - Introduction to server-side development
 
Unit 1st and 3rd notes of java
Unit 1st and 3rd notes of javaUnit 1st and 3rd notes of java
Unit 1st and 3rd notes of java
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
 
Server side programming
Server side programming Server side programming
Server side programming
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
sveltekit-en.pdf
sveltekit-en.pdfsveltekit-en.pdf
sveltekit-en.pdf
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
JAVA
JAVAJAVA
JAVA
 
Intorduction to struts
Intorduction to strutsIntorduction to struts
Intorduction to struts
 
Cgi
CgiCgi
Cgi
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
It and ej
It and ejIt and ej
It and ej
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 

Más de backdoor

Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
backdoor
 
Distributed Programming using RMI
 Distributed Programming using RMI Distributed Programming using RMI
Distributed Programming using RMI
backdoor
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMI
backdoor
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
backdoor
 
Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programming
backdoor
 
Windows Programming with Swing
Windows Programming with SwingWindows Programming with Swing
Windows Programming with Swing
backdoor
 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWT
backdoor
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
IO and serialization
IO and serializationIO and serialization
IO and serialization
backdoor
 
Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 
Java Intro
Java IntroJava Intro
Java Intro
backdoor
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
AWT Program output
AWT Program outputAWT Program output
AWT Program output
backdoor
 
Data Security
Data SecurityData Security
Data Security
backdoor
 
Ne Course Part One
Ne Course Part OneNe Course Part One
Ne Course Part One
backdoor
 
Ne Course Part Two
Ne Course Part TwoNe Course Part Two
Ne Course Part Two
backdoor
 
Security Policy Checklist
Security Policy ChecklistSecurity Policy Checklist
Security Policy Checklist
backdoor
 

Más de backdoor (20)

Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Distributed Programming using RMI
 Distributed Programming using RMI Distributed Programming using RMI
Distributed Programming using RMI
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMI
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
 
Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programming
 
Windows Programming with Swing
Windows Programming with SwingWindows Programming with Swing
Windows Programming with Swing
 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWT
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
IO and serialization
IO and serializationIO and serialization
IO and serialization
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Intro
Java IntroJava Intro
Java Intro
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
AWT Program output
AWT Program outputAWT Program output
AWT Program output
 
Net Man
Net ManNet Man
Net Man
 
Data Security
Data SecurityData Security
Data Security
 
Ne Course Part One
Ne Course Part OneNe Course Part One
Ne Course Part One
 
Ne Course Part Two
Ne Course Part TwoNe Course Part Two
Ne Course Part Two
 
Net Sec
Net SecNet Sec
Net Sec
 
Security Policy Checklist
Security Policy ChecklistSecurity Policy Checklist
Security Policy Checklist
 

Último

Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
amitlee9823
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
lizamodels9
 
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
amitlee9823
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Sheetaleventcompany
 
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Anamikakaur10
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
lizamodels9
 

Último (20)

Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with Culture
 
RSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataRSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors Data
 
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptx
 
Cracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxCracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptx
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMAN
 
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Century
 
Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperity
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investors
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
 
Uneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration PresentationUneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration Presentation
 

Programming Server side with Sevlet

  • 1. IADCS Diploma Course Java Servlet Programming U Nyein Oo COO/Director (IT) Myanma Computer Co., Ltd(MCC)
  • 2.
  • 3.
  • 4.
  • 5.
  • 6. Life of a Servlet Web Browser Web Server Java Servlet Database 1,2 3 4,5 6
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(&quot;text/html&quot;); PrintWriter out = res.getWriter(); out.println(&quot;<HTML>&quot;); out.println(&quot;<HEAD><TITLE>Hello World</TITLE></HEAD>&quot;); out.println(&quot;<BODY>&quot;); out.println(&quot;<BIG>Hello World</BIG>&quot;); out.println(&quot;</BODY></HTML>&quot;); } } A Java Servlet : Looks like a regular Java program
  • 35. <html> <head> <title>Hello, World JSP Example</title> </head> <body> <h2> Hello, World! The current time in milliseconds is <%= System.currentTimeMillis() %> </h2> </body> </html> A JSP Page : Looks like a regular HTML page. Embedded Java command to print current time.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41. // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); out.println (&quot;I was born on: &quot;+birthDate); out.close(); } }
  • 42.
  • 43.
  • 44.
  • 45. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Counter extends HttpServlet { // Create an instance variable int count = 0; // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); count++; out.println (&quot;Since loading, this servlet has &quot; + &quot;been accessed &quot;+ count + &quot; times.&quot;); out.close(); } } Only one instance of the counter Servlet is created. Each browser request is therefore incrementing the same count variable.
  • 46.
  • 47.
  • 48. package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class UserIDs extends HttpServlet { private int nextID = 0; public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); String title = &quot;Your ID&quot;; String docType = … String id = &quot;User-ID-&quot; + nextID; out.println(&quot;<H2>&quot; + id + &quot;</H2>&quot;); nextID = nextID + 1; out.println(&quot;</BODY></HTML>&quot;); } } This code is problematic. Can result in a race condition, where two users can actually get the same User-ID! For example: User 1 makes request: String id = &quot;User-ID-&quot; + nextID; Gets nextId of 45. Now User 2 makes request, and pre-empts user 1: String id = &quot;User-ID-&quot; + nextID; Gets nextId of 45 (same one!) Admittedly, this case is rare, but it’s especially problematic. Imagine if user Id was tied to credit card number!
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Death extends HttpServlet { // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); out.println (&quot;I am alive!&quot;); out.close(); } Continued….
  • 55. // This method is called when one stops // the Java Web Server public void destroy() { try { FileWriter fileWriter = new FileWriter (&quot;rip.txt&quot;); Date now = new Date(); String rip = &quot;I was destroyed at: &quot;+now.toString(); fileWriter.write (rip); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
  • 56.
  • 57.
  • 58. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterPersist extends HttpServlet { String fileName = &quot;counter.txt&quot;; int count; public void init () { try { FileReader fileReader = new FileReader (fileName); BufferedReader bufferedReader = new BufferedReader (fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt (initial); } catch (FileNotFoundException e) { count = 0; } catch (IOException e) { count = 0; } catch (NumberFormatException e) { count = 0; } } At Start-up, load the counter from file. In the event of any exception, initialize count to 0. Continued….
  • 59. // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); count++; out.println (&quot;Since loading, this servlet has &quot; +&quot;been accessed &quot;+ count + &quot; times.&quot;); out.close(); } Each time the doGet() method is called, increment the count variable. Continued….
  • 60. // At Shutdown, store counter back to file public void destroy() { try { FileWriter fileWriter = new FileWriter (fileName); String countStr = Integer.toString (count); fileWriter.write (countStr); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } When destroy() is called, store new counter variable back to counter.txt. Any problems with this code?
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CookieCounter extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String name, value = null; Cookie cookie; int counter; res.setContentType(&quot;text/html&quot;); // Try to extract the counter cookie (if one exists) Cookie[] cookies = req.getCookies(); for (int i=0; i<cookies.length; i++) { cookie = cookies[i]; name = cookie.getName(); if (name.equals(&quot;counter&quot;)) value = cookie.getValue(); }
  • 83. // If possible, parse the counter value // Otherwise, start over at 0. if (value != null) counter = Integer.parseInt (value); else counter = 0; // Increment the counter counter++; // Create a new counter cookie // Cookie will exist for one year cookie = new Cookie (&quot;counter&quot;, Integer.toString(counter)); cookie.setMaxAge (60*60*24*365); res.addCookie (cookie); // Output number of visits PrintWriter out = res.getWriter(); out.println (&quot;<HTML><BODY>&quot;); out.println (&quot;<H1>Number of visits: &quot;+counter); out.println (&quot;</H1>&quot;); out.println (&quot;</BODY></HTML>&quot;); out.close(); } }
  • 84.
  • 85.
  • 86.
  • 87. for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie(&quot;Session-Cookie-&quot; + i, &quot;Cookie-Value-S&quot; + i); response.addCookie(cookie); cookie = new Cookie(&quot;Persistent-Cookie-&quot; + i, &quot;Cookie-Value-P&quot; + i); // Cookie is valid for a year, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge (60*60*24*365); response.addCookie(cookie); } Code Fragment
  • 88.
  • 89.