servlets and java server pages object-oriented programming v22.0470 written by: haytham allos...

31
Servlets and Java Servlets and Java Server Pages Server Pages Object-Oriented Programming V22.0470 Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) Written by: Haytham Allos (Instructor) New York University (NYU) New York University (NYU)

Post on 20-Dec-2015

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Servlets and Java Server Servlets and Java Server PagesPages

Object-Oriented Programming V22.0470Object-Oriented Programming V22.0470

Written by: Haytham Allos (Instructor)Written by: Haytham Allos (Instructor)

New York University (NYU)New York University (NYU)

Page 2: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Static contentStatic content

• Web Server delivers contents of a Web Server delivers contents of a file (html)file (html)

•1. Browser sends request to Web Server

•3. Web Server sends HTML to Browser

•2. Web Server reads file from disk

•b

row

ser

•Web Server

Page 3: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Dynamic Content Dynamic Content

• CGI(CGI(Common Gateway InterfaceCommon Gateway Interface)program )program generates HTML that is returned to generates HTML that is returned to BrowserBrowser

•1. Browser sends request to Web Server

•5. Web Server sends HTML to Browser

•User Computer

•Server

•2. Web Server loads CGI program from disk

•CGI Program

•3. Web Server starts CGI program

•4. CGI program generates and returns HTML

•b

row

ser

•Web Server

Page 4: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

CGI has issuesCGI has issues

• performanceperformance– Web Server must create new process Web Server must create new process

for each request, limits scalabilityfor each request, limits scalability

• maintenance maintenance – presentation and business logic tightly presentation and business logic tightly

coupledcoupled

Page 5: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

AlternativesAlternatives

• FastCGI - persistent processFastCGI - persistent process

• mod_perl - perl interpreter mod_perl - perl interpreter embedded in Apache web serverembedded in Apache web server

• Server Extensions - Server Extensions - Netscape(NSAPI), Microsoft(ISAPI)Netscape(NSAPI), Microsoft(ISAPI)

• Active Server PagesActive Server Pages

Page 6: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Java ServletsJava Servlets

• replaces CGIreplaces CGI

• a Java programa Java program

• runs in Servlet Container or Engineruns in Servlet Container or Engine

• generates dynamic content(HTML, XML)generates dynamic content(HTML, XML)

• now part of J2EE architecturenow part of J2EE architecture

• good performance good performance

Page 7: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Java Servlets Continued... Java Servlets Continued...

• Advantages Advantages – generally faster, more efficient than generally faster, more efficient than

CGICGI

– runs as a thread not an OS processruns as a thread not an OS process

– Convenience - Java API’sConvenience - Java API’s

– secure - does not run in a shellsecure - does not run in a shell

– portable, vendor independentportable, vendor independent

Page 8: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Java Servlet DiagramJava Servlet Diagram

• Extends Web Server Extends Web Server

•1. Browser sends request to Web Server

•6. Web Server sends HTML to Browser

•2. Web Server sends request to Servlet Engine

•Servlet

•Servlet

•Servlet•5. Servlet generates and returns HTML

•b

row

ser

•Web Server

•Servlet Container

•DB

•Top

Lin

k

•4. Servlet can access database

•jd

bc

•3. Servlet Engine runs the servlet

Page 9: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Simple ServletSimple Servlet•

public class HelloWorld extends HttpServlet { public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response. setContentType(" text/ html"); PrintWriter out = response. getWriter(); out. println( "< HTML>" ); out. println( "< HEAD>< TITLE> Hello World</ TITLE></ HEAD>”); out. println( "< BODY>”); out. println( "< H1> Hello World</ H1>”); out. println( "</ BODY></ HTML>"); }}

Page 10: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Servlet IssuesServlet Issues

• servlet generating HTML results in servlet generating HTML results in presentation and business logic presentation and business logic tightly coupled with accompanying tightly coupled with accompanying maintenance issues.maintenance issues.

Page 11: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Java Server Pages(JSP)Java Server Pages(JSP)

• Built on Servlet technologyBuilt on Servlet technology

• simplified way to create pages containing simplified way to create pages containing dynamically generated content.dynamically generated content.

• converted into servlet, compiled and run converted into servlet, compiled and run as a normal servletas a normal servlet

• timestamp checked at specified interval, timestamp checked at specified interval, regenerated if necessary.regenerated if necessary.

Page 12: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Java Server Pages(JSP) Java Server Pages(JSP) continuedcontinued......

• jsp page containsjsp page contains– directives, comments, fixed template directives, comments, fixed template

data (HTML, XML), jsp expression or data (HTML, XML), jsp expression or tags, scriptletstags, scriptlets

Page 13: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Java Server Pages(JSP) Java Server Pages(JSP) continuedcontinued......

• Can be invoked from a browser via Can be invoked from a browser via URL or from a ServletURL or from a Servlet

• Java code can be in the jsp source Java code can be in the jsp source – keep simple keep simple

• Java code can be in a Java Bean Java code can be in a Java Bean – separates User Interface from Business separates User Interface from Business

LogicLogic

– Used via UseBean tag Used via UseBean tag

Page 14: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Java Server Page DiagramJava Server Page Diagram•

•1. Browser sends request to Web Server

•6. Web Server sends HTML to Browser

•2. Web Server sends request to Servlet Engine

•Servlet

•Servlet

•Servlet•6. JSP(Servlet) returns HTML

•b

row

ser

•Web Server

•Servlet Container

•DB

•Top

Lin

k

•5. JSP interacts with Java Bean(s) and/or Servlets

•jd

bc

•4. Servlet Container runs the JSP (Servlet)

•jsp

•JSP Engine

•Servlet source code

•Java Compiler

•JSP (Servlet)

•Java Bean

•3. JSP Engine generates servlet

Page 15: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Simple Java Server PageSimple Java Server Page

<HTML><BODY>Hello World. You are using a computer called <% request.getRemoteHost() %> !</BODY></HTML>

Page 16: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

MVC ArchitectureMVC Architecture• Model: data (java bean)Model: data (java bean)

• View: presentation / user interface (jsp)View: presentation / user interface (jsp)

• Controller: directs things / traffic cop (servlet)Controller: directs things / traffic cop (servlet)

•B

row

ser

•Servlet(controller)

•JSP(View) •Java Bean(Model)•DB

•Servlet Container

•request

•response

•1•instantiate •2

•3

•5 •4

Page 17: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

J2EE ArchitectureJ2EE Architecture

Page 18: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Servlet/JSP specificationsServlet/JSP specifications

• Servlet 2.0 JSP 1.0Servlet 2.0 JSP 1.0

• Servlet 2.2 JSP 1.1Servlet 2.2 JSP 1.1

• Servlet 2.3 JSP 1.2 Servlet 2.3 JSP 1.2 – Draft stageDraft stage

– J2EEJ2EE

Page 19: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

ResourcesResources

• http://java.sun.com/products/jsphttp://java.sun.com/products/jsp

• http://java.sun.com/products/servlethttp://java.sun.com/products/servlet

• BooksBooks– O’Reilly - http://www.ora.com/O’Reilly - http://www.ora.com/

– Prentice Hall - http://vig.prenhall.com/Prentice Hall - http://vig.prenhall.com/

– Addison-Wesley - http://www.aw.comAddison-Wesley - http://www.aw.com

Page 20: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Servlet/JSP FundamentalsServlet/JSP Fundamentals

• Servlets like any other Java class, except:Servlets like any other Java class, except:

• Must extend HttpServletMust extend HttpServlet

• Must contain a doPost or doGet methodMust contain a doPost or doGet method

• Come equipped to handle the laborious points Come equipped to handle the laborious points of httpof http

• Http requests and responses are made into Http requests and responses are made into Java objectsJava objects

• Best alternative to traditional CGIBest alternative to traditional CGI

Page 21: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Servlet/JSP FundamentalsServlet/JSP Fundamentals

• Anatomy of a ServletAnatomy of a Servlet– Optional init method, executes the first time a Optional init method, executes the first time a

servlet is invokedservlet is invoked

– doGet/doPost methods execute when request doGet/doPost methods execute when request is madeis made

– method signature accepts http request and method signature accepts http request and response as parametersresponse as parameters

– Optional destroy methodOptional destroy method

– wwwwww..servletsservlets..com com SamplesSamples

Page 22: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Servlet/JSP FundamentalsServlet/JSP Fundamentals

• One instance of Servlet for each Servlet One instance of Servlet for each Servlet namename

• Same instance serves all requests to that Same instance serves all requests to that namename

• Instance members persist across all requests Instance members persist across all requests to that name. to that name.

• Local /block variables in doPost & doGet are Local /block variables in doPost & doGet are unique to each requestunique to each request

Page 23: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

JSP as presentation modelJSP as presentation modelServletServlet

Performs thePerforms the

hard workhard work

ClientClient

requestrequest

JSPJSP

SuccessfulSuccessful

resultsresults

Helper objectsHelper objectsPersistent “bean” Persistent “bean”

objectsobjectsDB Connections, etcDB Connections, etc

JSPJSP

UnsuccessfulUnsuccessful

resultsresults

App logic

Presentation SubsequentSubsequent clientclient

requestrequest

Simple calls to bean properties

No servlet need if bean

still set

Page 24: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

JSP alternativesJSP alternatives

• JSP can still result in unwieldy code JSP can still result in unwieldy code creeping into HTML creeping into HTML

• Most HTML editors don’t like itMost HTML editors don’t like it

• JSP:Taglibs and other “templating” JSP:Taglibs and other “templating” programs may help.programs may help.

• Much depends on how HTML documents Much depends on how HTML documents are produced and what business logic you are produced and what business logic you are presentingare presenting

Page 25: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

In Depth ExamplesIn Depth Examples

• Encapsulation of SQL callsEncapsulation of SQL calls

• List results and view thread detailList results and view thread detail

• Post reply and add to favoritesPost reply and add to favorites

• Set all bean properties w/ requestSet all bean properties w/ request

• Edit usersEdit users

• Query centralQuery central

Page 26: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)

Pitfalls, surprises, and Pitfalls, surprises, and work-aroundswork-arounds

• HTTP works via requests and responses. HTTP works via requests and responses. Client caching of responses poses a Client caching of responses poses a problem.problem.

• Guard against evil use of the “back” buttonGuard against evil use of the “back” button

• Don’t assume everyone’s client will respond Don’t assume everyone’s client will respond properly to the “defaults”properly to the “defaults”

• Guard against easy spoofs of any GET Guard against easy spoofs of any GET request which alters data.request which alters data.

Page 27: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)
Page 28: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)
Page 29: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)
Page 30: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)
Page 31: Servlets and Java Server Pages Object-Oriented Programming V22.0470 Written by: Haytham Allos (Instructor) New York University (NYU)