comp 321 week 7. overview html and http basics dynamic web content servletsmvc tomcat in eclipse...

42
COMP 321 COMP 321 Week 7 Week 7

Upload: rodney-barber

Post on 30-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

COMP 321COMP 321

Week 7Week 7

Page 2: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

OverviewOverview

HTML and HTTP BasicsHTML and HTTP Basics

Dynamic Web ContentDynamic Web Content

ServletsServlets

MVCMVC

Tomcat in Eclipse DemonstrationTomcat in Eclipse Demonstration

Lab 7-1 IntroductionLab 7-1 Introduction

Page 3: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

What does a web server do?What does a web server do?

Receives request from clientReceives request from client

Returns response to clientReturns response to client

Page 4: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

What does a web client do?What does a web client do?

Sends request to serverSends request to server

Receives responseReceives response

Displays response to the userDisplays response to the user

Page 5: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

HTML and HTTPHTML and HTTP

HTTP (Hypertext Transport Protocol)HTTP (Hypertext Transport Protocol)– Protocol web clients and servers use to Protocol web clients and servers use to

communicatecommunicate– Specifies format of requests and responsesSpecifies format of requests and responses

HTML (Hypertext Markup Language)HTML (Hypertext Markup Language)– Format for specifying contents of a web pageFormat for specifying contents of a web page

Page 6: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

HTMLHTML<<htmlhtml>>

<!<!– Some sample HTML --– Some sample HTML -->>

<<headhead>>

<<titletitle>>A Login PageA Login Page</</titletitle>>

</</headhead>>

<<bodybody>>

<<h1 h1 alignalign=="center""center">>Skyler's Login PageSkyler's Login Page</</h1h1>>

<<p p alignalign=="right""right">>

<<img img srcsrc=="SKYLER2.jpg""SKYLER2.jpg" widthwidth=="130" "130" heightheight=="150""150"/>/>

</</pp>>

<<form form actionaction=="date2""date2">>

Name: Name: <<input input typetype=="text" "text" namename=="param1""param1"/></><brbr/>/>

Password: Password: <<input input typetype=="text" "text" namename=="param2""param2"/></><brbr/></><brbr/></><brbr/>/>

<<centercenter><><input input typetype=="SUBMIT""SUBMIT"/><//></centercenter>>

</</formform>>

</</bodybody>>

</</htmlhtml>>

Page 7: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

HTMLHTML

Page 8: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

HTTPHTTP

Runs on top of TCP/IPRuns on top of TCP/IPRequest Contains:Request Contains:– HTTP Method (GET, POST, etc.)HTTP Method (GET, POST, etc.)– Page to access (ex. www.google.com)Page to access (ex. www.google.com)– Form ParametersForm Parameters

Response Contains:Response Contains:– Status Code (ex. 200, 404, etc.)Status Code (ex. 200, 404, etc.)– Content-type (ex. text/html, image/jpg)Content-type (ex. text/html, image/jpg)– Content (ex. HTML document, picture, etc.)Content (ex. HTML document, picture, etc.)

Page 9: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

HTTP MethodsHTTP Methods

GETGET– Used to retrieve an objectUsed to retrieve an object– IdempotentIdempotent

POSTPOST– Used to send data, perform an operation, etc.Used to send data, perform an operation, etc.– Not idempotentNot idempotent

Page 10: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

GET vs. POSTGET vs. POST

Both can send dataBoth can send data

Reasons to use POSTReasons to use POST– GET parameters are visible in URLGET parameters are visible in URL– GET data size is extremely limitedGET data size is extremely limited

Reasons to use GETReasons to use GET– Parameters can be bookmarked along with Parameters can be bookmarked along with

URLURL

Page 11: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

HTTP RequestsHTTP Requests

WebServe DemoWebServe Demo

Check out Check out http://gauss.ececs.uc.edu/Users/Franco/Week7/J0/WebServe.java.html for more info for more info

Page 12: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

HTTP ResponseHTTP ResponseHTTP/1.1 200 OKHTTP/1.1 200 OK

Set-Cookie: JSESSIONID=0AAB6C8DE415E2E5F307CF334BFCA0C1; Path=/testELSet-Cookie: JSESSIONID=0AAB6C8DE415E2E5F307CF334BFCA0C1; Path=/testEL

Content-Type: text/htmlContent-Type: text/html

Content-Length: 397Content-Length: 397

Date: Wed, 19 Nov 2003 03:25:40 GMTDate: Wed, 19 Nov 2003 03:25:40 GMT

Server: Apache-Coyote/1.1Server: Apache-Coyote/1.1

Connection: closeConnection: close

<html><html>

......

</html></html>

Page 13: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

GET or POST?GET or POST?

A user is returning a login name and passwordA user is returning a login name and passwordA user is requesting a new page via a hyperlinkA user is requesting a new page via a hyperlinkA chat room user is sending a written responseA chat room user is sending a written responseA user hits the ‘Next’ button to see the next pageA user hits the ‘Next’ button to see the next pageA user hits the ‘Log out’ button on a secure A user hits the ‘Log out’ button on a secure banking sitebanking siteA user hits the ‘Back’ button on the browserA user hits the ‘Back’ button on the browserA user sends a name and address from to the A user sends a name and address from to the serverserverA user makes a radio button selectionA user makes a radio button selection

Page 14: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

GET or POST?GET or POST?

A user is returning a login name and passwordA user is returning a login name and password POST – the login and password shouldn’t be exposed POST – the login and password shouldn’t be exposed

in the address barin the address bar

A user is requesting a new page via a hyperlinkA user is requesting a new page via a hyperlink GET – this is the typical usage for getGET – this is the typical usage for get

A chat room user is sending a written responseA chat room user is sending a written response POST – the message could easily be too long for a POST – the message could easily be too long for a

GETGET

A user hits the ‘Next’ button to see the next pageA user hits the ‘Next’ button to see the next page Depending on the browser, nothing is sent to the Depending on the browser, nothing is sent to the

server in this caseserver in this case

Page 15: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

GET or POST?GET or POST?

A user hits the ‘Log out’ button on a secure A user hits the ‘Log out’ button on a secure banking sitebanking site Could be either – depends on implementationCould be either – depends on implementation

A user hits the ‘Back’ button on the browserA user hits the ‘Back’ button on the browser Could be either – the browser remembers whichCould be either – the browser remembers which

A user sends a name and address form to the A user sends a name and address form to the serverserver This would usually be a POSTThis would usually be a POST

A user makes a radio button selectionA user makes a radio button selection Nothing is sent to the server in this caseNothing is sent to the server in this case

Page 16: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

URL: URL: Uniform Resource LocatorUniform Resource Locator

http://www.wickedlysmart.com:80/beeradvice/select/beer1.htmlProtocol – httpProtocol – httpServer – www.wickedlysmart.comServer – www.wickedlysmart.comPort – 80Port – 80Path – /beeradvice/selectPath – /beeradvice/selectResource – beer1.htmlResource – beer1.htmlQuery String – not shown ?type=...Query String – not shown ?type=...

Page 17: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

TCP PortsTCP Ports

Used to allow multiple servers to run on a single Used to allow multiple servers to run on a single machinemachine

Each connection has a server name and Each connection has a server name and destination portdestination port

Standard ports are defined for common services:Standard ports are defined for common services: 21 – FTP21 – FTP 25 – SMPT25 – SMPT 80 – HTTP80 – HTTP 443 – HTTPS443 – HTTPS

Page 18: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Mapping URLs to ContentMapping URLs to Content

A: http://www.wickedlysmart.com/

Page 19: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Mapping URLs to ContentMapping URLs to Content

B: http://www.wickedlysmart.com/skiingAdvice

Page 20: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Mapping URLs to ContentMapping URLs to Content

C: http://www.wickedlysmart.com/beerAdvice

Page 21: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Mapping URLs to ContentMapping URLs to Content

D: www.wickedlysmart.com/beerAdvice/select/selectBeer.html

Page 22: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Dynamic ContentDynamic Content

Web servers know how to serve static Web servers know how to serve static pagespages

Many sites need to generate content Many sites need to generate content dynamically: at the time it is requesteddynamically: at the time it is requested

A helper (or CGI) application A helper (or CGI) application communicates with the web server to communicates with the web server to generate the contentgenerate the content

Page 23: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

First There Was CGI…First There Was CGI…

Client requests a link to a CGI URLClient requests a link to a CGI URL

Server launches and runs CGI program Server launches and runs CGI program with supplied parameterswith supplied parameters

Program creates web page and returns to Program creates web page and returns to serverserver

Server shuts down CGI program and Server shuts down CGI program and returns response to clientreturns response to client

Page 24: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

CGI vs. ServletsCGI vs. Servlets

Launching a new CGI process each time a Launching a new CGI process each time a request is made is expensiverequest is made is expensive

Servlets reuse the same JVM and even Servlets reuse the same JVM and even the same Servlet object for each request, the same Servlet object for each request, and only create a new threadand only create a new thread

Servlets can use J2EE security, Servlets can use J2EE security, transactions, and EJBs directlytransactions, and EJBs directly

Page 25: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

ServletsServlets

Live in a containerLive in a container

Are called by container when specific Are called by container when specific requests arriverequests arrive doGet() called for GET requestsdoGet() called for GET requests doPost() called for POST requestsdoPost() called for POST requests

Page 26: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

The Servlet ContainerThe Servlet Container

Handles all communicationHandles all communication

Manages Servlet LifecycleManages Servlet Lifecycle

Handles MultithreadingHandles Multithreading

Allows Declarative SecurityAllows Declarative Security

Handles JSP SupportHandles JSP Support

Page 27: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Servlet Request ProcessingServlet Request Processing

1.1. User clicks a link that contains a Servlet URLUser clicks a link that contains a Servlet URL2.2. Container creates HttpServletRequest and Container creates HttpServletRequest and

HttpServletResponse objectsHttpServletResponse objects3.3. Container finds correct Servlet, and creates thread for Container finds correct Servlet, and creates thread for

requestrequest4.4. Container calls doGet() or doPost() with request and Container calls doGet() or doPost() with request and

response objectsresponse objects5.5. Servlet generates dynamic page, and puts it in the Servlet generates dynamic page, and puts it in the

response objectresponse object6.6. The thread completes, the server converts the response The thread completes, the server converts the response

to an HTTP response, and returns it to the clientto an HTTP response, and returns it to the client

Page 28: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Servlet ExampleServlet Examplepublicpublic classclass Ch2Servlet Ch2Servlet extendsextends HttpServlet {HttpServlet {

publicpublic voidvoid doGet(HttpServletRequest request,doGet(HttpServletRequest request,

HttpServletResponse response) HttpServletResponse response) throwsthrows IOException {IOException {

PrintWriter out = response.getWriter();PrintWriter out = response.getWriter();

Date today = Date today = newnew Date();Date();

out.println(out.println(

"<html>""<html>" + +

"<body>""<body>" + +

"<h1 style=\"text-align:center\">""<h1 style=\"text-align:center\">" + +

"HF\'s Chapter2 Servlet</h1>""HF\'s Chapter2 Servlet</h1>" + +

"<br/>""<br/>" + today + + today +

"</body>""</body>" + +

"</html>""</html>"););

}}

}}

Page 29: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Servlet Mapping BasicsServlet Mapping Basics

Public URL Name – the URL that is Public URL Name – the URL that is exposed to the browserexposed to the browser

““Secret” Deployment Name – internal Secret” Deployment Name – internal name used to tie URL and File Path name used to tie URL and File Path togethertogether

File Path Name – actual location of class File Path Name – actual location of class file on diskfile on disk

Page 30: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Deployment DescriptorDeployment Descriptor<web-app ...><web-app ...> <servlet><servlet> <servlet-name>Internal Name 1</servlet-name><servlet-name>Internal Name 1</servlet-name> <servlet-class>foo.Servlet1</servlet-class><servlet-class>foo.Servlet1</servlet-class> </servlet></servlet> <servlet><servlet> <servlet-name>Internal Name 2</servlet-name><servlet-name>Internal Name 2</servlet-name> <servlet-class>foo.Servlet2</servlet-class><servlet-class>foo.Servlet2</servlet-class> </servlet></servlet> <servlet-mapping><servlet-mapping> <servlet-name>Internal Name 1</servlet-name><servlet-name>Internal Name 1</servlet-name> <url-pattern>/Public1</url-pattern><url-pattern>/Public1</url-pattern> </servlet-mapping></servlet-mapping> <servlet-mapping><servlet-mapping> <servlet-name>Internal Name 2</servlet-name><servlet-name>Internal Name 2</servlet-name> <url-pattern>/Public2</url-pattern><url-pattern>/Public2</url-pattern> </servlet-mapping></servlet-mapping></web-app></web-app>

Page 31: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Case Study – GeekDatesCase Study – GeekDates

Bryan creates a dating siteBryan creates a dating site

One Servlet per pageOne Servlet per page MainPageServletMainPageServlet InputDQLServletInputDQLServlet DoDQLQueryServletDoDQLQueryServlet etc.etc.

Page 32: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Case Study – GeekDates cont’dCase Study – GeekDates cont’dpublicpublic classclass DatingServlet DatingServlet extendsextends HttpServlet {HttpServlet {

publicpublic voidvoid doGet(HttpServletRequest request,doGet(HttpServletRequest request,

HttpServletResponse response) HttpServletResponse response) throwsthrows IOExceptionIOException

// business logic goes here// business logic goes here

// (read db, write db, etc.)// (read db, write db, etc.)

PrintWriter out = response.getWriter();PrintWriter out = response.getWriter();

// Ugly HTML strings embedded in Java go here// Ugly HTML strings embedded in Java go here

}}

}}

Page 33: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

GeekDates 2.0GeekDates 2.0

Bryan moves HTML to JSPsBryan moves HTML to JSPs Each servlet performs business logic, then Each servlet performs business logic, then

redirects to JSPredirects to JSP JSPs contain HTML with small amounts of JSPs contain HTML with small amounts of

Java sprinkled inJava sprinkled in JSPs only display data they’re given, and JSPs only display data they’re given, and

presentation is now separate from business presentation is now separate from business logiclogic

Page 34: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Case Study – GeekDates cont’dCase Study – GeekDates cont’d

What if we want access GeekDates from a What if we want access GeekDates from a Swing app?Swing app? Can’t be done – business logic is entangled Can’t be done – business logic is entangled

with Servlet-specific codewith Servlet-specific code Bryan should have used the MVC (Model-Bryan should have used the MVC (Model-

View-Controller) patternView-Controller) pattern

Page 35: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

MVCMVC

ModelModel Holds stateHolds state Holds business logic - contains rules for getting and Holds business logic - contains rules for getting and

updating stateupdating state

ViewView Gets state from Gets state from ModelModel (through (through ControllerController), and ), and

displays itdisplays it Sends user input to Sends user input to ControllerController

ControllerController Takes user input from Takes user input from ViewView and sends to and sends to ModelModel Allows Allows ViewView to access to access ModelModel

Page 36: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

GeekDates 3.0GeekDates 3.0

Now Bryan creates a model class for each Now Bryan creates a model class for each pagepage InputSignupModel.javaInputSignupModel.java InputSignupServlet.javaInputSignupServlet.java InputSignup.jspInputSignup.jsp

All of the Servlets have nearly the same All of the Servlets have nearly the same logic. What can we do about this?logic. What can we do about this?

Page 37: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Who’s Responsible?Who’s Responsible?

TaskTask Web ServerWeb Server ContainerContainer ServletServlet

Creates request & response objectsCreates request & response objects

Calls the service() methodCalls the service() method

Starts a new thread to handle requestStarts a new thread to handle request

Converts a response object to an HTTP Converts a response object to an HTTP responseresponse

Knows HTTPKnows HTTP

Adds HTML to the response objectAdds HTML to the response object

Has a reference to the response objectsHas a reference to the response objects

Finds URLs in the DDFinds URLs in the DD

Deletes the request and responseDeletes the request and response

Coordinates making dynamic contentCoordinates making dynamic content

Manages lifecyclesManages lifecycles

Name that matches <servlet-class> in DDName that matches <servlet-class> in DD

Page 38: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Who’s Responsible?Who’s Responsible?

TaskTask Web ServerWeb Server ContainerContainer ServletServlet

Creates request & response objectsCreates request & response objects XX

Calls the service() methodCalls the service() method XX

Starts a new thread to handle requestStarts a new thread to handle request XX

Converts a response object to an HTTP Converts a response object to an HTTP responseresponse

xx

Knows HTTPKnows HTTP xx

Adds HTML to the response objectAdds HTML to the response object xx

Has a reference to the response objectsHas a reference to the response objects xx xx

Finds URLs in the DDFinds URLs in the DD xx

Deletes the request and responseDeletes the request and response xx

Coordinates making dynamic contentCoordinates making dynamic content xx xx

Manages lifecyclesManages lifecycles xx

Name that matches <servlet-class> in DDName that matches <servlet-class> in DD xx

Page 39: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

J2EEJ2EE

J2EE is a group of specifications – Servlet, J2EE is a group of specifications – Servlet, JSP, EJB, etc.JSP, EJB, etc.

A fully-compliant container must have a A fully-compliant container must have a Servlet container and an EJB containerServlet container and an EJB container

Tomcat is a web container, not a full J2EE Tomcat is a web container, not a full J2EE application server (no EJBs)application server (no EJBs)

Page 40: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Tomcat with Eclipse DemonstrationTomcat with Eclipse Demonstration

Page 41: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Lab 7-1 IntroductionLab 7-1 Introduction

Page 42: COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction

Progress CheckProgress Check

Due this week:Due this week: Lab 5-2 Database Application InterfacesLab 5-2 Database Application Interfaces

Due next week:Due next week: Lab 7-1 Preparing to Build Web ApplicationsLab 7-1 Preparing to Build Web Applications