• No results found

Outline. CS 112 Introduction to Programming. Recap: HTML/CSS/Javascript. Admin. Outline

N/A
N/A
Protected

Academic year: 2021

Share "Outline. CS 112 Introduction to Programming. Recap: HTML/CSS/Javascript. Admin. Outline"

Copied!
9
0
0

Loading.... (view fulltext now)

Full text

(1)

CS 112 Introduction to

Programming

Web Programming:

Backend (server side) Programming

with Servlet, JSP

Yang (Richard) Yang

Computer Science Department

Yale University

308A Watson, Phone: 432-6400

Email: [email protected]

2

Outline

q

Admin and recap

q

Server-side web programming overview

q

Servlet programming

q

Java servlet page (JSP)

3

Admin

q

PS8 Part 2 (Bulldog tournament)

❍ 

Due Tuesday at 11:55 pm

q

Project checkpoint

❍ 

Due Thursday at 11:55 pm (Please use the

CHECKPOINT template)

q

Project demo day

❍ 

11:30 – 12:30 pm Apr. 30 at TEAL

Recap: HTML/CSS/Javascript

q

HTML: page content (model)

❍ 

Document object model (DOM)

q

CSS: display of content (view)

q

Javascript: interaction

5

Outline

q

Admin and recap

q

Server-side web programming overview

6

Web App--Server Side: Motivating Example

(OPS2b)

Madlib (template):

One of the most <adjective> characters in fiction is named "Tarzan of the <plural-noun> ." Tarzan was raised by a/an <noun> and lives in the <adjective> jungle in the heart of darkest <place> . He spends most of his time eating <plural-noun> and swinging from tree to <noun> . Whenever he gets angry, he beats on his chest and says, " <funny-noise> !" This is his war cry. Tarzan always dresses in <adjective> shorts made from the skin of a/an <noun> and his best friend is a/an <adjective> chimpanzee named Cheetah. He is supposed to be able to speak to elephants and <plural-noun> . In the movies, Tarzan is played by <person's-name> .

(2)

7

Web App--Server Side: Motivating Example

Welcome to the game of Mad Libs.

I will ask you to provide several words and phrases to fill in a mad lib story. The result will be displayed to you. Template file? tarzan.txt Please input an adjective: silly Please input a plural noun: apples Please input a noun: frisbee Please input an adjective: hungry Please input a place: New Haven, CT Please input a plural noun: bees Please input a noun: umbrella Please input a funny noise: burp Please input an adjective: shiny Please input a noun: jelly donut Please input an adjective: beautiful Please input a plural noun: spoons Please input a person's name: Keanu Reeves

Commandline Madlib (interaction):

Your mad-lib has been created:

One of the most silly characters in fiction is named "Tarzan of the apples ." Tarzan was raised by a/an frisbee and lives in the hungry jungle in the

heart of darkest New Haven, CT . He spends most of his time eating bees and swinging from tree to umbrella . Whenever he gets angry, he beats on his chest and says, " burp !" This is his war cry. Tarzan always dresses in shiny shorts made from the skin of a/an jelly donut and his best friend is a/an beautiful chimpanzee named Cheetah. He is supposed to be able to speak to elephants and spoons . In the movies, Tarzan is played by Keanu Reeves .

pseudo code?

Cmdline Madlib Pseudo Code

Display welcome message

Ask user to choose story template Process given template file foreach token in template file ask user input

store token -> user input mapping Display story

for each line

for each word in line if word is token print user input else

print word as it is

Web presents a

different medium

to deliver app.

The unit of interaction

is Web

page

.

Q: what Web pages?

http://mrt-cs112-0.appspot.com/

Webpage-Based Programming

q

One way to think about a dynamic Web page is to

think it as an object: it is constructed with given

input parameters

q

A Web page may collect input from user and then

create another Web page (object)--browsing

P1

input

input

P2

input

P3

Input to Create Each Page?

Display welcome message

Ask user to choose story template file Process given template file

foreach token in template file ask user input

store token -> user input mapping Display story

for each line

for each word in line if word is token print user input else print word as it is

Input:

None

Input

Chosen

template

Who collect?

Input

User input

for each

token

Chosen

Template

Who collect?

P1

P2

P3

Server-side Page Creation

input

par

ame

ter

creat

ed ht

ml page

Q: What is the mechanism in Web to collect user input?

HTML Form

q

Form

(3)

HTML Form

q

A form gives instruction to the browser on

❍ 

inputs to be collected from user

❍ 

URL (program) to be invoked when sending to server

http://www.teaching-materials.org/htmlcss/lesson3/slides.html

<form action="/create" method="get”>

Step 1: Please pick an input story template:

<div>

<input type="text" name="file" size ="40" value="tarzan.txt">

</div>

<input type="

hidden

" name="Language" value="English”>

<div>

<input type="submit" value="Next" />

</div>

</form>

Program to

be invoked

An input item

to be collected

How input is

transported to

server:

get/post

Invisible on page. Used

to pass internal data

Form Input Type

http://www.teaching-materials.org/htmlcss/lesson3/slides.html

q

<input type=”text" name="q">

q

<input type=“checkbox” name = “myc”/>

q

<input type=“radio” name = “mypizzasize”/>

q

<input type=“range” min=“0” max=“10” name

= “cheesiness”/>

q

<select name="crust”>

<option value="thin">Thin</option>

<option value="thick">Thick</option>

<option value="cheese">Cheese</option>

</select>

Web Execution Flow: Client Side

q

After user clicks submit on a form,

browser

❍ 

encodes each input in a format <name>=<value>

❍ 

requests page with URL:

<form action>?<name>=<value>&<name>=<value>

http://www.bing.com/search?q=yale

Web Execution Flow: Server Side

q

Web server receives the request for the

URL, finds the application for the URL, and

passes the values of the parameters to the

application

q

The application retrieves the parameters,

generates a Web page, and sends the page

back to the browser to display

Google App Engine

17

q

A platform to simplify the

development and hosting of Web

applications

❍ 

Simplified deployment

•  Load balancing

•  Automatic scaling

❍ 

Useful high-level services and APIs

Discussion: What GAE can do to allow simple,

flexible server-side app programming?

q

Client browser

❍ 

After user clicks submit on a form, browser

•  encodes each input in a format <name>=<value>

•  requests page with URL:

<form action>?<name>=<value>&<name>=<value>

q

Web server

❍ 

receives the request for the URL,

❍ 

finds the application for the URL, and

❍ 

passes the values of the parameters to the

application.

❍ 

the application retrieves the request parameters,

generates a response Web page back to the

browser to display

web.xml:

User defines

URL mapping

(4)

Discussion: What GAE can do to allow simple,

flexible server-side app programming?

q

Client browser

❍ 

After user clicks submit on a form, browser

•  encodes each input in a format <name>=<value>

•  requests page with URL:

<form action>?<name>=<value>&<name>=<value>

q

Web server

❍ 

receives the request for the URL,

❍ 

finds the application for the URL, and

❍ 

passes the values of the parameters to the

application.

❍ 

the application retrieves the request parameters,

generates a response Web page back to the

browser to display

Define

Servlet

class: conduct

common processing

steps; app overrides

key step (

doGet/

doPost

) to define

app-specific behavior

Discussion: What GAE can do to allow simple,

flexible server-side app programming?

q

Client browser

❍ 

After user clicks submit on a form, browser

•  encodes each input in a format <name>=<value>

•  requests page with URL:

<form action>?<name>=<value>&<name>=<value>

q

Web server

❍ 

receives the request for the URL,

❍ 

finds the application for the URL, and

❍ 

passes the values of the parameters to the

application.

❍ 

the application retrieves the request parameters,

generates a response Web page back to the

browser to display

Define

HttpServletRequest

class to allow simple

methods to retrieve

parameter, e.g.,

getParameter(“name”)

Discussion: What GAE can do to allow simple,

flexible server-side app programming?

q

Client browser

❍ 

After user clicks submit on a form, browser

•  encodes each input in a format <name>=<value>

•  requests page with URL:

<form action>?<name>=<value>&<name>=<value>

q

Web server

❍ 

receives the request for the URL,

❍ 

finds the application for the URL, and

❍ 

passes the values of the parameters to the

application.

❍ 

the application retrieves the request parameters,

generates a response Web page back to the

browser to display

Define

HttpServletResponse

class to allow simple

methods to write response

(not worry about sending

across network), e.g.,

getWriter().println( “<p>Hello”)

Example

Display welcome message

Ask user to choose story template file Process given template file

foreach token in template file ask user input

store token -> user input mapping Display story

for each line

for each word in line if word is token print user input else print word as it is

Input: None

index.html

(see Note)

web.xml

23 <?xml version="1.0" encoding="utf-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5”> <welcome-file-list>

<welcome-file>index.html</welcome-file> </welcome-file-list>

</web-app>

Example

Display welcome message

Ask user to choose story template file Process given template file

foreach token in template file ask user input

store token -> user input mapping Display story

for each line

for each word in line if word is token print user input else

print word as it is

Input: Chosen template CreateMadlibServlet.java

(5)

web.xml

q 

Allow a WebApp

developer to

declare the

applications

(servlets), and

which servlet will

serve which URL

25 <?xml version="1.0" encoding="utf-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet>

<servlet-name>CreateMadlibServlet</servlet-name> <servlet-class>madlibs.CreateMadlibServlet</servlet-class> </servlet>

<servlet-mapping>

<servlet-name>CreateMadlibServlet</servlet-name>

<url-pattern>/create</url-pattern>

</servlet-mapping> <welcome-file-list>

<welcome-file>index.html</welcome-file> </welcome-file-list>

</web-app>

Example

Display welcome message

Ask user to choose story template file Process given template file

foreach token in template file ask user input

store token -> user input mapping Display story

for each line

for each word in line if word is token print user input else

print word as it is

Input: User input for each token/template DisplayMadlibServlet.java

web.xml

q 

Allow a WebApp

developer to

declare the

applications

(servlets), and

which servlet will

serve which URL

27 <?xml version="1.0" encoding="utf-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet>

<servlet-name>CreateMadlibServlet</servlet-name> <servlet-class>madlibs.CreateMadlibServlet</servlet-class> </servlet>

<servlet>

<servlet-name>DisplayMadlibServlet</servlet-name> <servlet-class>madlibs.DisplayMadlibServlet</servlet-class> </servlet>

<servlet-mapping>

<servlet-name>CreateMadlibServlet</servlet-name>

<url-pattern>/create</url-pattern>

</servlet-mapping> <servlet-mapping>

<servlet-name>DisplayMadlibServlet</servlet-name>

<url-pattern>/display</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.html</welcome-file> </welcome-file-list>

</web-app>

28

Outline

q

Admin and recap

q

Server-side programming overview

q

Java Servlet

q

Java Servlet Page (jsp)

Motivation

q

Most used statement in

CreateMadlibServlet.java?

29

Motivation

q

For many Web pages, most of the content

will be static, and hence only a small

portion will be generated dynamically

q

The Servlet architecture asks you to print

the whole document (i.e., a large number of

Java print and escape statements for

printing the static part)

q

JSP goal: remove most of the print

statements

(6)

Motivating Example

q

Generate an html page consisting of a list

of 10 random numbers

31

Manual HTML

32

<html>

<body>

<h2>My list</h2>

<ul>

<li>1: 9</li>

<li>2: 3</li>

<li>3: 5</li>

<li>4: 1</li>

<li>5: 7</li>

<li>6: 4</li>

<li>7: 0</li>

<li>8: 2</li>

<li>9: 8</li>

<li>10: 9</li>

</ul>

</body>

</html>

Servlet

33 import java.util.Random;

publicclass NumListServlet extends HttpServlet {

publicvoid doPost(HttpServletRequest req, HttpServletResponse resp) 


throws IOException { doGet(req, resp); }

publicvoid doGet(HttpServletRequest req, HttpServletResponse resp)

throws IOException {

resp.setContentType("text/html");

resp.getWriter().println("<html>"); resp.getWriter().println("<body>"); resp.getWriter().println(”<h2>My list</h2>"); resp.getWriter().println("<ul>"); Random rand = new Random(); for (int i = 1; i < 11; i ++) { resp.getWriter().print(” <li>"); resp.getWriter().print( i + ”: ” + rand.nextInt(10) ); resp.getWriter().println("</li>"); } resp.getWriter().println("</ul>"); resp.getWriter().println("</body>"); resp.getWriter().println("</html>"); }

JSP Motivation

34 import java.util.Random;

publicclass NumListServlet extends HttpServlet {

publicvoid doPost(HttpServletRequest req, HttpServletResponse resp) 


throws IOException { doGet(req, resp); }

publicvoid doGet(HttpServletRequest req, HttpServletResponse resp)

throws IOException {

resp.setContentType("text/html");

resp.getWriter().println("<html>"); resp.getWriter().println("<body>"); resp.getWriter().println(”<h2>My list</h2>"); resp.getWriter().println("<ul>"); Random rand = new Random(); for (int i = 1; i < 11; i ++) { resp.getWriter().print(” <li>"); resp.getWriter().print(i + ”: ” + rand.nextInt(10) ); resp.getWriter().println("</li>"); } resp.getWriter().println("</ul>"); resp.getWriter().println("</body>"); resp.getWriter().println("</html>"); }

JSP Motivation

35 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ page import=“java.util.Random"%>

<html>

<body>

<h2>My list</h2>

<ul> <%

Random rand = new Random(); for (int i = 1; i < 11; i ++) { resp.getWriter().print(” <li>"); resp.getWriter().print(i + ”: ” + rand.nextInt(10) ); resp.getWriter().println("</li>"); } %> </ul> </body> </html>

Directive

Called a JSP

scriptlet, containing

a fragment of java

code

Why it does not work?

Run test.jsp as /test

(7)

web.xml

37 <?xml version="1.0" encoding="utf-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<servlet>

<servlet-name>CreateMadlibServlet</servlet-name>

<servlet-class>madlibs.CreateMadlibServlet</servlet-class>

</servlet>

<servlet>

<servlet-name>DisplayMadlibServlet</servlet-name>

<servlet-class>madlibs.DisplayMadlibServlet</servlet-class>

</servlet> <servlet> <servlet-name>TestJSP</servlet-name> <jsp-file>test.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>TestJSP</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping> ... <welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list> </web-app>

JSP Motivation

38 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ page import=“java.util.Random"%>

<html>

<body>

<h2>My list</h2>

<ul>

<%

Random rand = new Random(); for (int i = 1; i < 11; i ++) { response.getWriter().print(” <li>");

response.getWriter().print(i + ”: ” + rand.nextInt(10) ); response.getWriter().println("</li>");

} %> </ul> </body> </html>

Directive

Called a JSP

scriptlet, containing

a fragment of java

code

implicit

object

See http://www.tutorialspoint.com/jsp/jsp_implicit_objects.htm for implicit objects

Output

39

Problem

40 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ page import=“java.util.Random"%>

<html>

<body>

<h2>My list</h2>

<ul>

<%

Random rand = new Random(); for (int i = 1; i < 11; i ++) { response.getWriter().print(” <li>");

response.getWriter().print(i + ”: ” + rand.nextInt(10) ); response.getWriter().println("</li>");

} %> </ul> </body> </html>

Use implicit object

out

to print. out !=

response.getWrite()

Fix

41 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ page import=“java.util.Random"%>

<html>

<body>

<h2>My list</h2>

<ul> <%

Random rand = new Random(); for (int i = 1; i < 11; i ++) { out.print(” <li>");

out.print(i + ”: ” + rand.nextInt(10) ); out.println("</li>");

} %> </ul> </body> </html>

Motivation

42 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ page import=“java.util.Random"%>

<html>

<body>

<h2>My list</h2>

<ul>

<%

Random rand = new Random(); for (int i = 1; i < 11; i ++) { out.print(” <li>");

out.print(i + ”: ” + rand.nextInt(10) ); out.println("</li>");

} %> </ul> </body> </html>

What if we do not

want to use the print

(8)

Attempt

43 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ page import=“java.util.Random"%>

<html>

<body>

<h2>My list</h2>

<ul> <%

Random rand = new Random(); for (int i = 1; i < 11; i ++) { %> <li> i : rand.nextInt(10) </li> <% } %> </ul> </body> </html>

Problem: i and

rand.NextInt(10) are not

treated as Java exp.

JSP Expression

44 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ page import=“java.util.Random"%>

<html>

<body>

<h2>My list</h2>

<ul>

<%

Random rand = new Random(); for (int i = 1; i < 11; i ++) { %> <li> <%= i %>: <%= rand.nextInt(10) %> </li> <% } %> </ul> </body> </html>

<%= %> encloses

JSP expression, whose

value appears in the

output to out.

Motivation: Reduce Embedded

Scriptlets

45 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ page import=“java.util.Random” %>

<html>

<body>

<h2>My list</h2>

<ul> <%

Random rand = new Random(); for (int i = 1; i < 11; i ++) { %> <li> <%= i %>: <%= rand.nextInt(10) %> </li> <% } %> </ul> </body> </html>

JSTL (JavaServer Pages

Stanard Tag Library)

q

Objective: introduce JSP tags for common

tasks such as conditional execution, loops,

XML data access

46

Motivation: Reduce Embedded

Scriptlets

47 <%@ page contentType="text/html;charset=UTF-8" language="java” %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page import=“java.util.Random” %>

<html>

<body>

<h2>My list</h2>

<ul> <%

Random rand = new Random(); %>

<c:forEach var="i" begin="1" end=“10">

<li> <c:out value="${i}"/> <%= rand.nextInt(10) %></li> </c:forEach> </ul> </body> </html> http://www.tutorialspoint.com/jsp/jstl_core_foreach_tag.htm

Java Servlet Page (JSP)

q

History

❍ 

Released in 1999

❍ 

Similar to PHP but supports more sophisticated

J2EE programming

q

Can be considered as a high-level

abstraction of Java servlets

q

In real implementation, JSPs are

translated to servlets at runtime

(9)

Exercise

q

Turn CreateMadlibServlet.java into

createmadlib.jsp

References

Related documents

Matrix Please select the matrix then input the corresponding monitor output number, video input channel number, and then you can click video switch button to complete the

Create a memorable Christmas dinner or New Year's Eve party with 25 holiday table setting ideas centerpieces decorations from Pinterest.. We use cookies to personalise content and

If “Yes”, please attach copies. If “No”, please provide details of the basis of engagement used by the Proposer. Please outline by attachment the formal procedures in place

・Please do not enter 0 (If there are no figure to input, please keep the column empty).. ・Please do not input unit

 Please turn off the power switch, when changing the power cord or signal cable, or select the input mode switch..  Extreme frequency boosts in connection with a high input

Please provide input to help us define the factors we need to consider related to the selection and implementation of an identity management solution?. Please comment on the

InputPlayerID = input(&#34;Enter your chosen ID&#34;) Score = int(input(&#34;Please enter the score&#34;)) JoannePlayer = Player(InputPlayerID) if JoannePlayer.SetScore(Score)

(c) Subject and in addition to clause 44 in the Standard Terms, the Tenant acknowledges that any notice or other writing is sufficiently served on the Tenant if served personally