SlideShare une entreprise Scribd logo
1  sur  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!

Contenu connexe

Tendances

Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state managementpriya Nithya
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessionsvantinhkhuc
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaJainamParikh3
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
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 servletsJavaEE Trainers
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 

Tendances (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
 

Similaire à Programming Server side with Sevlet

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 developmentRandy Connolly
 
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 javaNiraj Bharambe
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servletsAamir Sohail
 
Server side programming
Server side programming Server side programming
Server side programming javed ahmed
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
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...WebStackAcademy
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
Intorduction to struts
Intorduction to strutsIntorduction to struts
Intorduction to strutsAnup72
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music storeADEEBANADEEM
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applicationshchen1
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptxMattMarino13
 

Similaire à 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
 

Plus de backdoor

Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Distributed Programming using RMI
 Distributed Programming using RMI Distributed Programming using RMI
Distributed Programming using RMIbackdoor
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMIbackdoor
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Appletbackdoor
 
Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programmingbackdoor
 
Windows Programming with Swing
Windows Programming with SwingWindows Programming with Swing
Windows Programming with Swingbackdoor
 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWTbackdoor
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
IO and serialization
IO and serializationIO and serialization
IO and serializationbackdoor
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
AWT Program output
AWT Program outputAWT Program output
AWT Program outputbackdoor
 
Data Security
Data SecurityData Security
Data Securitybackdoor
 
Ne Course Part One
Ne Course Part OneNe Course Part One
Ne Course Part Onebackdoor
 
Ne Course Part Two
Ne Course Part TwoNe Course Part Two
Ne Course Part Twobackdoor
 
Security Policy Checklist
Security Policy ChecklistSecurity Policy Checklist
Security Policy Checklistbackdoor
 

Plus 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
 

Dernier

business environment micro environment macro environment.pptx
business environment micro environment macro environment.pptxbusiness environment micro environment macro environment.pptx
business environment micro environment macro environment.pptxShruti Mittal
 
Jewish Resources in the Family Resource Centre
Jewish Resources in the Family Resource CentreJewish Resources in the Family Resource Centre
Jewish Resources in the Family Resource CentreNZSG
 
Planetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifePlanetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifeBhavana Pujan Kendra
 
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...Hector Del Castillo, CPM, CPMM
 
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdfChris Skinner
 
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxGo for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxRakhi Bazaar
 
Strategic Project Finance Essentials: A Project Manager’s Guide to Financial ...
Strategic Project Finance Essentials: A Project Manager’s Guide to Financial ...Strategic Project Finance Essentials: A Project Manager’s Guide to Financial ...
Strategic Project Finance Essentials: A Project Manager’s Guide to Financial ...Aggregage
 
Darshan Hiranandani [News About Next CEO].pdf
Darshan Hiranandani [News About Next CEO].pdfDarshan Hiranandani [News About Next CEO].pdf
Darshan Hiranandani [News About Next CEO].pdfShashank Mehta
 
Cyber Security Training in Office Environment
Cyber Security Training in Office EnvironmentCyber Security Training in Office Environment
Cyber Security Training in Office Environmentelijahj01012
 
Welding Electrode Making Machine By Deccan Dynamics
Welding Electrode Making Machine By Deccan DynamicsWelding Electrode Making Machine By Deccan Dynamics
Welding Electrode Making Machine By Deccan DynamicsIndiaMART InterMESH Limited
 
Technical Leaders - Working with the Management Team
Technical Leaders - Working with the Management TeamTechnical Leaders - Working with the Management Team
Technical Leaders - Working with the Management TeamArik Fletcher
 
Effective Strategies for Maximizing Your Profit When Selling Gold Jewelry
Effective Strategies for Maximizing Your Profit When Selling Gold JewelryEffective Strategies for Maximizing Your Profit When Selling Gold Jewelry
Effective Strategies for Maximizing Your Profit When Selling Gold JewelryWhittensFineJewelry1
 
Interoperability and ecosystems: Assembling the industrial metaverse
Interoperability and ecosystems:  Assembling the industrial metaverseInteroperability and ecosystems:  Assembling the industrial metaverse
Interoperability and ecosystems: Assembling the industrial metaverseSiemens
 
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...Operational Excellence Consulting
 
Appkodes Tinder Clone Script with Customisable Solutions.pptx
Appkodes Tinder Clone Script with Customisable Solutions.pptxAppkodes Tinder Clone Script with Customisable Solutions.pptx
Appkodes Tinder Clone Script with Customisable Solutions.pptxappkodes
 
Environmental Impact Of Rotary Screw Compressors
Environmental Impact Of Rotary Screw CompressorsEnvironmental Impact Of Rotary Screw Compressors
Environmental Impact Of Rotary Screw Compressorselgieurope
 
WSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfWSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfJamesConcepcion7
 
Horngren’s Financial & Managerial Accounting, 7th edition by Miller-Nobles so...
Horngren’s Financial & Managerial Accounting, 7th edition by Miller-Nobles so...Horngren’s Financial & Managerial Accounting, 7th edition by Miller-Nobles so...
Horngren’s Financial & Managerial Accounting, 7th edition by Miller-Nobles so...ssuserf63bd7
 
14680-51-4.pdf Good quality CAS Good quality CAS
14680-51-4.pdf  Good  quality CAS Good  quality CAS14680-51-4.pdf  Good  quality CAS Good  quality CAS
14680-51-4.pdf Good quality CAS Good quality CAScathy664059
 
Driving Business Impact for PMs with Jon Harmer
Driving Business Impact for PMs with Jon HarmerDriving Business Impact for PMs with Jon Harmer
Driving Business Impact for PMs with Jon HarmerAggregage
 

Dernier (20)

business environment micro environment macro environment.pptx
business environment micro environment macro environment.pptxbusiness environment micro environment macro environment.pptx
business environment micro environment macro environment.pptx
 
Jewish Resources in the Family Resource Centre
Jewish Resources in the Family Resource CentreJewish Resources in the Family Resource Centre
Jewish Resources in the Family Resource Centre
 
Planetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifePlanetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in Life
 
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
 
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
20220816-EthicsGrade_Scorecard-JP_Morgan_Chase-Q2-63_57.pdf
 
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxGo for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
 
Strategic Project Finance Essentials: A Project Manager’s Guide to Financial ...
Strategic Project Finance Essentials: A Project Manager’s Guide to Financial ...Strategic Project Finance Essentials: A Project Manager’s Guide to Financial ...
Strategic Project Finance Essentials: A Project Manager’s Guide to Financial ...
 
Darshan Hiranandani [News About Next CEO].pdf
Darshan Hiranandani [News About Next CEO].pdfDarshan Hiranandani [News About Next CEO].pdf
Darshan Hiranandani [News About Next CEO].pdf
 
Cyber Security Training in Office Environment
Cyber Security Training in Office EnvironmentCyber Security Training in Office Environment
Cyber Security Training in Office Environment
 
Welding Electrode Making Machine By Deccan Dynamics
Welding Electrode Making Machine By Deccan DynamicsWelding Electrode Making Machine By Deccan Dynamics
Welding Electrode Making Machine By Deccan Dynamics
 
Technical Leaders - Working with the Management Team
Technical Leaders - Working with the Management TeamTechnical Leaders - Working with the Management Team
Technical Leaders - Working with the Management Team
 
Effective Strategies for Maximizing Your Profit When Selling Gold Jewelry
Effective Strategies for Maximizing Your Profit When Selling Gold JewelryEffective Strategies for Maximizing Your Profit When Selling Gold Jewelry
Effective Strategies for Maximizing Your Profit When Selling Gold Jewelry
 
Interoperability and ecosystems: Assembling the industrial metaverse
Interoperability and ecosystems:  Assembling the industrial metaverseInteroperability and ecosystems:  Assembling the industrial metaverse
Interoperability and ecosystems: Assembling the industrial metaverse
 
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
The McKinsey 7S Framework: A Holistic Approach to Harmonizing All Parts of th...
 
Appkodes Tinder Clone Script with Customisable Solutions.pptx
Appkodes Tinder Clone Script with Customisable Solutions.pptxAppkodes Tinder Clone Script with Customisable Solutions.pptx
Appkodes Tinder Clone Script with Customisable Solutions.pptx
 
Environmental Impact Of Rotary Screw Compressors
Environmental Impact Of Rotary Screw CompressorsEnvironmental Impact Of Rotary Screw Compressors
Environmental Impact Of Rotary Screw Compressors
 
WSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfWSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdf
 
Horngren’s Financial & Managerial Accounting, 7th edition by Miller-Nobles so...
Horngren’s Financial & Managerial Accounting, 7th edition by Miller-Nobles so...Horngren’s Financial & Managerial Accounting, 7th edition by Miller-Nobles so...
Horngren’s Financial & Managerial Accounting, 7th edition by Miller-Nobles so...
 
14680-51-4.pdf Good quality CAS Good quality CAS
14680-51-4.pdf  Good  quality CAS Good  quality CAS14680-51-4.pdf  Good  quality CAS Good  quality CAS
14680-51-4.pdf Good quality CAS Good quality CAS
 
Driving Business Impact for PMs with Jon Harmer
Driving Business Impact for PMs with Jon HarmerDriving Business Impact for PMs with Jon Harmer
Driving Business Impact for PMs with Jon Harmer
 

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.