Server-Side Web Programming: Java. Copyright 2017 by Robert M. Dondero, Ph.D Princeton University

Similar documents
Server-Side Web Programming: Python (Part 2) Copyright 2017 by Robert M. Dondero, Ph.D Princeton University

Server-Side Web Programming: Python (Part 1) Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

COS 333: Advanced Programming Techniques. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Web Architecture and Development

Chapter Two Bonus Lesson: JavaDoc

Introduction to Computer Science I

Setting Up the Development Environment

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Web Architecture and Development

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

web.py Tutorial Tom Kelliher, CS 317 This tutorial is the tutorial from the web.py web site, with a few revisions for our local environment.

COS 333: Advanced Programming Techniques

Certified Core Java Developer VS-1036

29-27 May 2013 CERN WEB FRAMEWORKS. Adrian Mönnich

class objects instances Fields Constructors Methods static

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

SSC - Web applications and development Introduction and Java Servlet (I)

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

Chapter 1 Introduction to Computers, Programs, and Java

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Lecture 02, Fall 2018 Friday September 7

A Long Time Ago 2 / 64

UIMA Simple Server User Guide

Igniting QuantLib on a Zeppelin

How to make a "hello world" program in Java with Eclipse *

Chapter 1 Introduction to Java

HOW TO FLASK. And a very short intro to web development and databases

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

Class 1: Homework. Intro to Computer Science CSCI-UA.0101 New York University Courant Institute of Mathematical Sciences Fall 2017

Pemrograman Jaringan Web Client Access PTIIK

Session 13. RESTful Services Part 2. Lecture Objectives

CS/ENGRD 2110 FALL Lecture 2: Objects and classes in Java

Project 1. Java Control Structures 1/17/2014. Project 1 and Java Intro. Project 1 (2) To familiarize with

Ch04 JavaServer Pages (JSP)

Eng. Mohammed S. Abdualal

Quick housekeeping Last Two Homeworks Extra Credit for demoing project prototypes Reminder about Project Deadlines/specifics Class on April 12th Resul

1.00 Lecture 8. Using An Existing Class, cont.

Unifer Documentation. Release V1.0. Matthew S

Welcome to CSSE 220. We are excited that you are here:

IBM LOT-985. Developing IBM Lotus Notes and Domino(R) 8.5 Applications.

CS506 Web Design & Development Final Term Solved MCQs with Reference

IBM Rational Software

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Using IDLE for

MEAP Edition Manning Early Access Program Get Programming with Java Version 1

Java Server Page (JSP)

IQTIDAR ALI Lecturer IBMS Agriculture University Peshawar

EPL660: Information Retrieval and Search Engines Lab 3

Type Declarations. [... <id> τ... ] <id> : τ. Γ <num> : number. Γ true : boolean. Γ false : boolean. Γ e 1 : number.

Web Application Architecture (based J2EE 1.4 Tutorial)

Python 1: Intro! Max Dougherty Andrew Schmitt

Appendix C WORKSHOP. SYS-ED/ Computer Education Techniques, Inc.

CS 11 java track: lecture 1

Networks Programming Engr. Abdul-Rahman Mahmood MS, PMP, MCP, QMR(ISO9001:2000)

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Free your Lambdas Java SE 8

Experiment No: Group B_2

Java Applets, etc. Instructor: Dmitri A. Gusev. Fall Lecture 25, December 5, CS 502: Computers and Communications Technology

Servlets by Example. Joe Howse 7 June 2011

Write for your audience

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

CompSci 125 Lecture 02

16.410: Jump Starting With Java

Learning objectives. The Java Environment. Java timeline (cont d) Java timeline. Understand the basic features of Java

CSE332: Data Abstrac0ons Sec%on 1. Hye In Kim Winter 2014

JDK-WildFly-NetBeans Setup Local

I hate money. Release 1.0

CS 251 Intermediate Programming Java Basics

Section 2.2 Your First Program in Java: Printing a Line of Text

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

public Twix() { calories = 285; ingredients = "chocolate, sugar, cookie, caramel"; }

Java Program Structure and Eclipse. Overview. Eclipse Projects and Project Structure. COMP 210: Object-Oriented Programming Lecture Notes 1

REGEX HELPER USER MANUAL CONTENTS

CS 61B Discussion 5: Inheritance II Fall 2014

Groovy and Grails in Google App Engine

Session 24. Spring Framework Introduction. Reading & Reference. dev.to/lechatthecat/how-to-use-spring-boot-java-web-framework-withintellij-idea-202p

Exceptions and Libraries

Object Model Comparisons

QUIZ Friends class Y;

Kickstart Intro to Java Part I

Managing State. Chapter 13

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

Introduction. Introduction to OOP with Java. Lecture 01: Introduction to OOP with Java - AKF Sep AbuKhleiF -

REST in a Nutshell: A Mini Guide for Python Developers

COMP110 Jump Around. Go ahead and get today s code in Eclipse as shown on next few slides. Kris Jordan

CSCI 201 Lab 1 Environment Setup

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

Review: Array Initializer Lists

Week 2: The Clojure Language. Background Basic structure A few of the most useful facilities. A modernized Lisp. An insider's opinion

Summer Assignment for the School Year

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Java with Eclipse: Setup & Getting Started

Preview from Notesale.co.uk Page 3 of 36

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to Java. Handout-1d. cs402 - Spring

Transcription:

Server-Side Web Programming: Java Copyright 2017 by Robert M. Dondero, Ph.D Princeton University 1

Objectives You will learn about: Server-side web programming in Java, via Servlets The Spark web app framework The Velocity template engine 2

Agenda 1. Servlet Programming 2. The Spark Web Application Framework 3. The Velocity Template Engine 3

Java Web Programming Question: How does one do web programming in Java? 4

CGI with Java Answer 1: Use CGI Possible, but Very inefficient Each request forks a new child process and execs a new JVM! Java standard library provides no CGI classes No real website would use them anyway (I composed some for my own use; see me if you want) 5

Servlets Answer 2: Use Servlets A servlet is a Java technology-based Web component, managed by a container, that generates dynamic content. Servlet specification at: http://download.oracle.com//servlet-3_0-finalspec.pdf 6

Servlets Servlet Container Browser HTTP Server Servlet1 Servlet2 Servlet3 Servlet4 Your app Popular servlet containers: Apache Tomcat Eclipse Jetty 7

Servlets Tomcat or Jetty Browser Servlet1 Servlet2 Servlet3 Servlet4 Your app Tomcat or Jetty can be both HTTP server and servlet container We ll use Jetty 8

WSGI and Servlets Python: WSGI specification connects HTTP server and your Python app Programmers compose Python code to conform to WSGI spec Sys admins deploy Python code with HTTP server 9

WSGI and Servlets Java: Servlet specification connects HTTP server and your Java app Programmers compose Java code to conform to Servlet spec Sys admins deploy Java code with Servlet container and HTTP server 10

PennyServlet App See PennyServlet App runserver runserver.bat Book.java Database.java Common.java IndexServlet.java SearchFormServlet.java SearchResultsServlet.java Penny.java 11

Java Frameworks Answer 3: Use a Java web app framework 12

Agenda 1. Servlet Programming 2. The Spark Web Application Framework 3. The Velocity Template Engine 13

The Spark Web App Framework Who: Per Wendel When: 2011, rewritten for Java 8 in 2014 Descrip: A micro framework for creating web applications in Kotlin and Java 8 with minimal effort Spark website 14

Why Spark? Why study Spark? (Instead of some other framework) Easy to learn Simple ( micro-framework ) Good documentation and tutorial Reasonable to use for Assignments 3 & 4 Installed on CourseLab Easy to install on your personal computer Integrated with Jetty container/server Allows flat directory structure; easy to submit 15

PennySpark1Fund App See PennySpark1Fund App runserver, runserver.bat, Book.java, Database.java Common.java Penny.java Generalizing 16

PennySpark1Fund App Spark separates URL from file name (Unlike CGI) Can use pretty URLs Spark separates URL from method name Can map multiple URLs to same method Can change method name without changing URL, or vice versa 17

PennySpark1Fund App Spark provides utility functions Functions to fetch name=value pairs Functions to fetch/create cookies Function to implement HTTP redirect 18

Aside: Lambda Expressions Lambda expression A nameless function From Alonzo Church, 1930s 19

Aside: Python Lambda Exprs In Python: The keyword lambda (optionally) parameters separated by commas A colon A single expression that uses the parameters 20

Aside: Python Lambda Exprs Without using a lambda expression: Using a lambda expression: def mult(x, y): return x * y prod = mult(5, 6) print prod # prints 30 mult = lambda x, y: x * y prod = mult(5, 6) print prod # prints 30 Using a lambda expression: print (lambda x, y: x * y)(5, 6) # prints 30 21

Aside: Python Lambda Exprs def comparestrlengths(s1, s2): return len(s1) len(s2) strlist.sort(cmp=comparestrlengths) strlist.sort( cmp=lambda s1,s2: len(s1) len(s2) ) 22

Aside: Java Lambda Exprs Java lambda expressions New to Java SE 8 Examples 23

Aside: Java Lambda Exprs class StrLenComparator implements Comparator<String> { public int compare(string s1, String s2) { return s1.length() s2.length(); } } String[] strarray; Arrays.sort(strArray, new StrLenComparator()); String[] strarray; Arrays.sort(strArray, (String s1, String s2) -> s1.length() s2.length() ); 24

Aside: Java Lambda Exprs class StrLenComparator implements Comparator<String> { public int compare(string s1, String s2) { return s1.length() s2.length(); } } String[] array; Arrays.sort(strArray, new StrLenComparator()); String[] strarray; Arrays.sort(strArray, (s1, s2) -> s1.length() s2.length() ); Can omit param types if compiler can infer them 25

Aside: Java Lambda Exprs class StrLenComparator implements Comparator<String> { public int compare(string s1, String s2) { if (s1.length() < s2.length()) return -1; if (s1.length() > s2.length()) return 1; return 0; } } String[] strarray; Arrays.sort(strArray, new StrLenComparator()); 26

Aside: Java Lambda Exprs String[] strarray; Arrays.sort(strArray, (String s1, String s2) -> { if (s1.length() < s2.length()) return -1; if (s1.length() > s2.length()) return 1; return 0; } ); Consequent need not be a single expr Can surround consequent with braces Consequent must evaluate to (return) something 27

Aside: Java Lambda Exprs Generalizing Functional interface An interface with a single method Can use a lambda expression in lieu of an instance of a class that implements a functional interface 28

Java Lambda Expr Commentary It s best to think of a lambda expression as a function, not an object, and to accept that it can be passed to a functional interface. -- Horstmann Function pointers in a language that doesn t have functions! Handy! Inelegant? 29

PennySpark1Fund App Spark uses Java lambda expressions Using a lambda expression: class Penny { private static String index(request req, Response res) {} public static void main(string[] args) { Spark.get("/index", (req, res) -> index(req, res) ); } } 30

PennySpark1Fund App Same code without using a lambda expr: class IndexRoute implements Route { public Object handle(request req, Response res) { return Penny.index(req, res); } } class Penny { public static String index(request req, Response res) {} public static void main(string[] args) { Spark.get("/index", new IndexRoute()); } } 31

Agenda 1. Servlet Programming 2. The Spark Web Application Framework 3. The Velocity Template Engine 32

Toward PennySpark2Templates Problem: Code contains many assignment statements to compose HTML code Bulky; awkward; error prone Solution: Templates In this case via The Apache Velocity template engine 33

PennySpark2Templates App See PennySpark2Templates App runserver, runserver.bat, Book.java, Database.java header.vtl footer.vtl index.vtl searchform.vtl searchresults.vtl Penny.java Generalizing 34

PennySpark2Templates App Template (informally) HTML doc with placeholders Each placeholder is identified by a key hello.vtl Hello <strong>${username}</strong> and welcome 35

PennySpark2Templates App To instantiate a template: Map<String, Object> map = new HashMap<>(); map.put("key1", value1); ModelAndView mv = new ModelAndView(map, "somefile.vtl"); return new VelocityTemplateEngine().render(mv); 36

PennySpark2Templates App Template can contain: Inline expressions ${expr} expr usually is a key in the provided map ${prevauthor} expr can be any expression that evaluates to a String or has a String representation ${book.getauthor()} 37

PennySpark2Templates App Includes of other templates #parse("other.vtl") #parse("header.vtl") 38

PennySpark2Templates App Template cannot contain embedded Java code! Instead use a special purpose (Apache Velocity) language Examples 39

PennySpark2Templates App #if (${errormsg}) <strong>${errormsg}</strong> #end #if (${books.size()} == 0) (None) #else #foreach (${book} in ${books}) ${book.getauthor()}, ${book.gettitle()}, ($${book.getprice()})<br> #end #end 40

MVC Architecture Notes: Bottle encourages use of MVC Bottle encourages separation of concerns But Python code can appear in Bottle views Notes: Spark/Velocity more strongly encourages use of MVC Spark/Velocity more strongly encourages separation of concerns Java code cannot appear in Velocity views 41

More Spark and Velocity! There is much more to Spark and Velocity Spark website: http://sparkjava.com/ Spark documentation: http://spark.screenisland.com/overview-summary.html Velocity documentation: http://velocity.apache.org/engine/1.7/vtl-reference.html Don t confuse Spark (sometimes called SparkJava) with Apache Spark (an open-source cluster-computing framework) 42

Summary We have covered: Server-side web programming in Java, via Servlets The Spark web app framework The Velocity template engine 43