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