comp2513 java servlet basics

19
Comp2513 Comp2513 Java Servlet Basics Java Servlet Basics Daniel L. Silver, Ph.D. Daniel L. Silver, Ph.D.

Upload: zasha

Post on 06-Jan-2016

36 views

Category:

Documents


0 download

DESCRIPTION

Comp2513 Java Servlet Basics. Daniel L. Silver, Ph.D. Objectives. To introduce the basic concepts of Java Servlets To discuss FORMs and Java Servlets Review more complex servlets Reference: DDEA Ch.7, Sharma p.110-122 and EJP (Ch.4) p.48-63. The Problems with Applets and CGI. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Comp2513 Java Servlet Basics

Comp2513Comp2513

Java Servlet BasicsJava Servlet Basics

Daniel L. Silver, Ph.D.Daniel L. Silver, Ph.D.

Page 2: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 2

ObjectivesObjectives

To introduce the basic concepts of Java To introduce the basic concepts of Java ServletsServlets

To discuss FORMs and Java ServletsTo discuss FORMs and Java Servlets Review more complex servletsReview more complex servlets Reference: DDEA Ch.7, Sharma p.110-122 Reference: DDEA Ch.7, Sharma p.110-122

and EJP (Ch.4) p.48-63and EJP (Ch.4) p.48-63

Page 3: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 3

The Problems The Problems with Applets and CGIwith Applets and CGI

Java Applets have three major drawbacks:Java Applets have three major drawbacks:– Take time to load onto clientTake time to load onto client

– May not work as planned (depends on JVM)May not work as planned (depends on JVM)

– Security risk for clientSecurity risk for client

Server-side code is preferred for business logicServer-side code is preferred for business logic CGI allows an application to run on server but CGI allows an application to run on server but

creates server performance problemscreates server performance problems Most notably each time a separate process must be Most notably each time a separate process must be

spawned (for Java a separate JVM is run)spawned (for Java a separate JVM is run)

Page 4: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 4

Enter ServletsEnter Servlets

Servlets overcome this problemServlets overcome this problem Servlets relie on a Servlet Engine Servlets relie on a Servlet Engine

(Application Server) to manage multiple (Application Server) to manage multiple requests for the same applicationrequests for the same application

Java servlets have the advantages of Java Java servlets have the advantages of Java applets but run on the server side applets but run on the server side

The Jserv engine from SUN was the first The Jserv engine from SUN was the first Java servlet engineJava servlet engine

Page 5: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 5

Java Servlet TechnologyJava Servlet Technology

Applications run on the server.Applications run on the server. Extend functionality of a web server and provide Extend functionality of a web server and provide

structure for a business environment.structure for a business environment. Servlets can be operating system and hardware Servlets can be operating system and hardware

platform independent.platform independent. Servlets process HTTP/HTML requests with all Servlets process HTTP/HTML requests with all

the benefits of the mature Java language the benefits of the mature Java language (portability, performance, reusability, and crash (portability, performance, reusability, and crash protection.)protection.)

Page 6: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 6

Applet vs. ServletApplet vs. Servlet

AppletApplet– Client side.Client side.– Takes time to load.Takes time to load.– JVM varies with JVM varies with

browser.browser.– Require compatible Require compatible

browserbrowser– Security issue if client Security issue if client

side program needs to side program needs to access sensitive data via access sensitive data via browser.browser.

ServletServlet– Server side.Server side.– Runs on request.Runs on request.– Constant JVMConstant JVM– No GUI required, can No GUI required, can

generate HTML, generate HTML, Javascript, Applet codeJavascript, Applet code

– Server side Server side programming and data programming and data access preferred for access preferred for business applications.business applications.

Page 7: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 7

CGIs vs. ServletsCGIs vs. Servlets

CGI programsCGI programs– Separate process for each Separate process for each

CGI programCGI program

– Mod_perl and FastCGI Mod_perl and FastCGI improves performance of improves performance of CGI but not to level of CGI but not to level of servletsservlets

– Have difficult time Have difficult time maintaining state across maintaining state across requestsrequests

ServletsServlets– Run under single JVM Run under single JVM

(better performance)(better performance)

– Servlets loaded into Servlets loaded into memory with first call, and memory with first call, and stay in memorystay in memory

– Have built in state Have built in state preservation methodspreservation methods

– Java's inherent securityJava's inherent security

– Proprietary source code can Proprietary source code can be retained by only giving be retained by only giving up *.class files to the serverup *.class files to the server

Page 8: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 8

Websphere Java ServletWebsphere Java ServletRequest ProcessingRequest Processing

InternetInternet

Browser

Client

HTTP Server

HelloWorld.class

http://eagle.acadiau.ca/demo/servlet/HelloWorld

TomcatApp. Server

servlet/HelloWorld

demo/servlet/ equates to…/demo/WEB-INF/classes/HelloWorld.class

HTML

JVM

Page 9: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 9

Servlet Life-CycleServlet Life-Cycle

The servlet is initialized and is loaded into the The servlet is initialized and is loaded into the servers memoryservers memory

The servlet resides in memory and responds to The servlet resides in memory and responds to requests from clientsrequests from clients

The servlet is destroyed (by the server engine)The servlet is destroyed (by the server engine)

NOTE: When you update a servlet, Tomcat NOTE: When you update a servlet, Tomcat checks the modification date of the .class file and checks the modification date of the .class file and if it is more recent then the running version, the if it is more recent then the running version, the servlet is destroy and then re-initializeservlet is destroy and then re-initialize

Page 10: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 10

Fundamental parts of a ServletFundamental parts of a Servlet1. import javax.servlet.*; and import javax.servlet.http.*; 1. import javax.servlet.*; and import javax.servlet.http.*;

- packages of servlet classes that implement the Java Servlet API- packages of servlet classes that implement the Java Servlet API2. public class HelloWorld extends HttpServlet { 2. public class HelloWorld extends HttpServlet {

- extends the HTTPServlet class- extends the HTTPServlet class3. init()3. init()

-intializes servlet after loading into memory-intializes servlet after loading into memory- place to perform operations done only once at start-up- place to perform operations done only once at start-up

- reading a current properties - reading a current properties - clearing log files, notifying other services that the servlet is running- clearing log files, notifying other services that the servlet is running

4. service(), doGet(), doPost()4. service(), doGet(), doPost()- this is where work is done- this is where work is done- each time the servlet is called a new thread of execution begins- each time the servlet is called a new thread of execution begins- input is passed to the Java code via either HTTP GET or POST commands- input is passed to the Java code via either HTTP GET or POST commands

5. destoy()5. destoy()- executed when server engine calls servlet to terminate- executed when server engine calls servlet to terminate- used to flush I/O, disconnect from database- used to flush I/O, disconnect from database

Page 11: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 11

Structure ofStructure ofa Servlet:a Servlet:

HelloWorldHelloWorld

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

public class HelloWorld extends HttpServlet {public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletExceptionthrows IOException, ServletException {{ response.setContentType("text/html");response.setContentType("text/html"); PrintWriter out = response.getWriter();PrintWriter out = response.getWriter(); out.println("<html>");out.println("<html>"); out.println("<body>");out.println("<body>"); out.println("<head>");out.println("<head>"); out.println("<title>Hello World!</title>");out.println("<title>Hello World!</title>"); out.println("</head>");out.println("</head>"); out.println("<body>");out.println("<body>"); out.println("<h1>Hello World!</h1>");out.println("<h1>Hello World!</h1>"); out.println("</body>");out.println("</body>"); out.println("</html>");out.println("</html>"); }}}}

Page 12: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 12

Some Basic Java ServletsSome Basic Java Servlets

Several examples …Several examples …http://eagle.acadiau.ca/demo/servletexample.htmlhttp://eagle.acadiau.ca/demo/servletexample.html

http://eagle.acadiau.ca:8080/examples/servlets/index.htmlhttp://eagle.acadiau.ca:8080/examples/servlets/index.html

http://www.servlets.com/jservlet2/examples/index.htmlhttp://www.servlets.com/jservlet2/examples/index.html

Java Developers Almanac:Java Developers Almanac:http://javaalmanac.com/egs/javax.servlet/pkg.htmlhttp://javaalmanac.com/egs/javax.servlet/pkg.html

Page 13: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 13

FORMS and Java ServletsFORMS and Java Servlets

Within HTML code on the client: A Within HTML code on the client: A FORM tag similar to CGI is used to pass FORM tag similar to CGI is used to pass data from a browser to a Java servlet:data from a browser to a Java servlet:… … <FORM ACTION = <FORM ACTION =

'http://eagle/store35/servlet/ShowFormVariables' 'http://eagle/store35/servlet/ShowFormVariables' METHOD=‘GET'>METHOD=‘GET'>Enter your first name <INPUT TYPE=text NAME='firstName' Enter your first name <INPUT TYPE=text NAME='firstName' VALUE=' '><br>VALUE=' '><br>

……

This will cause the web browser to generate This will cause the web browser to generate a URL a URL (if “Danny” is entered)(if “Danny” is entered):: http://eagle/demo/servlet/ShowFormVariables?firstName=Dannyhttp://eagle/demo/servlet/ShowFormVariables?firstName=Danny

Page 14: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 14

FORMS and Java ServletsFORMS and Java Servlets Within Java code on the server: The doGet servlet Within Java code on the server: The doGet servlet

method is used to obtain the two objects:method is used to obtain the two objects:– HttpServletRequest and HttpServletResponseHttpServletRequest and HttpServletResponse

HttpServletRequest is used to get the INPUT HttpServletRequest is used to get the INPUT parameter names and values: parameter names and values: – getParameterNames()getParameterNames()– getParameterValues()getParameterValues()

HttpServletResponse used to return HTML HttpServletResponse used to return HTML responseresponse– printlin()printlin()

Page 15: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 15

An Example of a Java Servlet An Example of a Java Servlet handling FORM inputhandling FORM input

From page 117 of Sharma – servlet that From page 117 of Sharma – servlet that returns browser input passed via a FORM returns browser input passed via a FORM tagtaghttp://eagle.acadiau.ca/danstech/ShowFormVariables.htmlhttp://eagle.acadiau.ca/danstech/ShowFormVariables.html

Here is the java source code :Here is the java source code :http://eagle/danstech/ShowFormVariables.javahttp://eagle/danstech/ShowFormVariables.java

Page 16: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 16

A more complex Servlet ExampleA more complex Servlet Example AddToShopppingCart.java from your store AddToShopppingCart.java from your store

provides a larger and more complex servlet provides a larger and more complex servlet exampleexample

Also see ClearShoppingCart.javaAlso see ClearShoppingCart.java

Page 17: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 17

Problems with Servlets ?Problems with Servlets ?

Do you see any problems with servlets from Do you see any problems with servlets from an E-Commerce perspective?an E-Commerce perspective?

Page 18: Comp2513 Java Servlet Basics

2002 Daniel L. Silver 18

Additional Web InfoAdditional Web Info

http://java.sun.com/products/servlet/http://java.sun.com/products/servlet/ http://developer.java.sun.com/developer/onlineTrahttp://developer.java.sun.com/developer/onlineTra

ining/Servlets/Fundamentals/ining/Servlets/Fundamentals/ http://hotwired.lycos.com/webmonkey/99/07/indehttp://hotwired.lycos.com/webmonkey/99/07/inde

x3a.html?tw=programmingx3a.html?tw=programming http://www.servlets.com/jservlet2/index.htmlhttp://www.servlets.com/jservlet2/index.html http://www.servlets.com/jservlet2/examples/http://www.servlets.com/jservlet2/examples/

index.htmlindex.html

Page 19: Comp2513 Java Servlet Basics

THE ENDTHE END

[email protected]@acadiau.ca