Spring MVC
Supplementary Reading
Johnson, Rod et al.: Spring Framework Reference Documentation,
[Link]
w/o author: Spring Guides, [Link]
w/o author: Apache Freemarker,
[Link]
w/o author: Bootstrap 5 Tutorial,
[Link]
w/o author: jQuery, [Link]
w/o auhtor: jQuery Tutorial, [Link]
w/o author: jQuery UI, [Link]
Web Applications V3.1 2
First Example with Spring MVC (1)
functionality
●
Page 1: 2 input fields for first name and last name of person, 1 button
●
Page 2: output “Hello” + data from page 1
needed Software artefacts
●
1 controller class (Java)
●
1 model class (Java)
●
2 views (FreeMarker templates)
Web Applications V3.1 3
First Example with Spring MVC (2)
@GetMapping("/firstExample")
public String editPerson() {
return "firstExample/editPerson";
}
<body>
<h2>Edit Person</h2>
<form method="POST">
<label for="firstName">First
Name:</label>
<input type="text"
name="firstName"/>...
Web Applications V3.1 4
First Example with Spring MVC (3)
@PostMapping("/firstExample")
public ModelAndView showPerson(Person
person) {
ModelAndView mv = new ModelAndView();
[Link](person);
[Link]
("firstExample/showPerson");
return mv;
}
public class Person {
private String firstName;
demo private String lastName;...}
[Link] Hello ${[Link]}
[Link] ${[Link]}!
Web Applications V3.1 5
Servlet (1)
programming API for Java based web applications
abstract class HttpServlet
needs Servlet Engine as runtime environment
●
maps HTTP request to method call and returned object to HTTP
response
●
Servlet Engines: Apache Tomcat, Jetty, JBoss Application Server,
GlassFish Application Server
●
in production: servlet engine is behind web server
●
for testing purposes direct calls possible
– port number 8080 often used
Web Applications V3.1 6
Servlet (2)
Server
Client
Servlet-Engine
Servlet
Browser HTTP Servlet
Servlet
Web-
Server
Web Applications V3.1 7
Servlet (3)
HttpServlet {abstract}
# void doGet (HttpServletRequest req, HttpServletResponse resp)
# void doPost (HttpServletRequest req, HttpServletResponse resp)
….
incoming data (e.g. form data) in HttpServletRequest
outgoing data (HTML elements) in HttpServletResponse
●
HTML elements must be delivered as String objects
●
not very comfortable to program
Web Applications V3.1 8
Model-View-Controller (1)
shows uses
User
changes
reads data
View Controller
Model
informs on state change manipulates
Web Applications V3.1 9
Model-View-Controller (2)
Spring MVC and Vaadin use model-view-controller pattern
Spring MVC
model → JavaBean
view → Freemarker template (other template language
possible)
controller → method in Java class addressed by routing
annotation
Vaadin
model → JavaBean
view → view class
controller → VaadinServlet (generic class), lambda expressions
registered for input fields or buttons
Web Applications V3.1 10
Spring
application development framework for enterprise applications in Java
open source software
divided into modules
applications can choose which modules they need
includes configuration model and dependency injection mechanism
provides foundational support for different application architectures
●
messaging
●
transactional data
●
persistence
●
Spring MVC web framework
– Servlet based
Web Applications V3.1 11
Spring Boot (1)
Spring application uses many libraries, also from third parties
version management of libraries not easy
→ simplified by Spring Boot
easy to create stand-alone Spring based applications
uses predefined dependencies in build tool with minimum of additional
configuration
●
build tool Maven → configuration done in [Link]
Spring Boot projects typically use spring-boot-starter-parent as parent in
[Link]
<parent>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
</parent>
Web Applications V3.1 12
Spring Boot (2)
dependencies in [Link]
●
spring-boot-devtools
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
– makes application development easier
●
switch off caching during testing
●
automatic restart
Web Applications V3.1 13
Spring Boot (3)
dependencies in [Link]
●
develop web application using tomcat and Spring MVC
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
●
use FreeMarker template engine
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
Web Applications V3.1 14
Spring Boot (4)
Spring Boot application main method
@SpringBootApplication
public class App {
public static void main(String[] args) {
[Link]([Link], args);
}
}
annotation @SpringBootApplication does auto configuration
Web Applications V3.1 15
Spring Boot Code Structure
specific code structure not required
●
some best practices help
do not use default package
Java package naming conventions
recommended
●
use reverse domain names,
e.g. [Link]
main application class in root
package above other classes
static content (html, images, css,
js) in folder static in resources
Web Applications V3.1 16
Learning Targets
understand basics of controller in Spring
understand mapping URL to controller
Web Applications V3.1 17
Dispatcher Servlet (1)
Spring Web MVC framework is
●
request-driven
●
designed around central Servlet
– dispatches requests to controllers
using DispatcherServlet is "Front Controller" design pattern
Web Applications V3.1 18
Dispatcher Servlet (2)
Web Applications V3.1 19
Controller
use annotation @Controller at class level
can have several methods handling HTTP-requests
should be in package below root package
→ Spring can find it without additional configuration
annotation @RequestMapping maps URL to controller method
●
usable at class level and at method level
Web Applications V3.1 20
Attributes of RequestMapping (1)
value=”path”: defines mapping for specific URL
when used at class level, URL mapping defined for method is prefixed with
path defined for class (relative path)
→ same part of part for all methods
without class level definition path URL definition in method is absolute
“value=” can be omitted when path is only attribute
Web Applications V3.1 21
Attributes of RequestMapping (2)
method=RequestMethod.<method> (GET, POST, PUT, ...)
●
narrow path to HTTP method
– array of values allowed
●
if used on class level all methods inherit HTTP restriction
●
if used on method level only method is restricted
●
if attribute not present, method will handle all HTTP requests with that
URL
●
example
@RequestMapping(value = "/firstExample", method =
[Link])
Web Applications V3.1 22
Attributes of RequestMapping (3)
@<HTTP method>Mapping can be used instead of @RequestMapping( …,
method=RequestMethod.<method>
●
used at method level only
●
better semantic
●
example
@GetMapping("/firstExample")
demo [Link]
[Link]
[Link]
Web Applications V3.1 23
Parameters for Request Handling Methods
none, one, or several parameters possible
usage of parameter depends on type
form object
●
Java Bean that reflects form data
→ see Model
[Link]
●
validation results for preceding form object parameter
→ see Validation
[Link]
●
session object
[Link]
●
status handle for marking form processing complete
●
triggers clean-up of session attributes which are indicated by annotation
@SessionAttributes at handler class level
Web Applications V3.1 24
Return Types for Request Handling Methods (1)
return types of request handling method
●
ModelAndView
– contains data to be presented in view and name of view
– view represented by String view name
→ resolved by ViewResolver
– model is map
→ allows to attach multiple objects addressed by key
– constructors
●
ModelAndView(): default constructor
●
ModelAndView(String viewName): constructor with view name
Web Applications V3.1 25
Return Types for Request Handling Methods (2)
request handling method can return one of these types
●
ModelAndView
– methods
●
ModelAndView addObject([Link] attributeName,
[Link] attributeValue): adds attribute to model
●
void setStatus(HttpStatus status): sets HTTP status for response
●
void setViewName([Link] viewName): sets view name,
to be resolved by DispatcherServlet via ViewResolver
●
get-methods for reading different values
●
String: represents view name
●
view name for FreeMarker Template: path name relative to folder with
name “templates”, view name without ending .ftlh
– example: return "firstExample/editPerson"; refers to template
/templates/firstExample/[Link]
Web Applications V3.1 26
Redirect (1)
possibilities after receiving request
●
forward to another view
●
redirect to another view
forwarding done by returning new view in return value of request handling
method
●
HTTP response sends new view to browser
forwarding can cause problems in case of POST request
●
if user clicks reload, then POST request will be repeated with same data
– data can be stored twice
– there is confirmation question in browser, but this can be
misunderstood by inexperienced user
●
avoid problem by using redirect message
Web Applications V3.1 27
Redirect (2)
redirect message
●
return “redirect: <URL>”;
●
sends redirect response with <URL> to browser
●
browser sends GET request with <URL> to server
●
2 additional messages between browser and server
●
reload after GET repeats GET request (no harm GET used correctly)
returning redirect in ModelAndView object possible
values in model get lost when using redirect
●
use interface RedirectAttributes as parameter instead of
Web Applications V3.1 28
Interface RedirectAttributes (1)
used to select attributes for redirect scenario
RedirectAttributes model is empty when method is called
never used unless method returns redirect view name
after redirect, flash attributes are automatically added to model of controller
that serves target URL
method
●
addFlashAttribute(String attributeName, Object attributeValue)
Web Applications V3.1 29
Interface RedirectAttributes (2)
example
●
controller
@PostMapping("/redirect")
public String redirectPost(RedirectAttributes redirectAttributes) {
[Link]("text", "This is a flash
attribute");
@GetMapping("/getAfterPost")
public String redirectGetAfterPost(){
return "controller/getafterpost";
●
view
<h3>${text!}</h3>
demo [Link]
[Link]
Web Applications V3.1 30
Web Application Example Study Program
define pages and basics for controller
Web Applications V3.1 31
Layout and Forms
Web Applications V3.1 32
Learning Targets
understand basics of CSS for layout
understand responsive layout with bootstrap
Web Applications V3.1 33
Form Design (1)
goal of form design: fill in form easily
●
which information needed
●
which format
●
is input required
form has interaction elements: text fields, option fields, check boxes, select
lists
input field needs label
●
explains meaning of element and which information should be entered
rules for labels
●
short, meaningful, unique
●
no abbreviations besides well known ones
●
located near corresponding input field
Web Applications V3.1 34
Labels above Input Fields (Register Google
Account)
recommended usage
located near work top
input field down in form
length of
label does capture label
not and input
influence field quickly
layout
several input form is
fields in row larger
when needed
Web Applications V3.1 35
Other Alignments
label in same row as input field less used
●
possible alignments
– labels right aligned
– labels left aligned
Web Applications V3.1 36
Form Design (2)
additional possibility: text of label in input field
●
disadvantage: text disappears when user starts input
– no problem when meaning of field can be derived from
context
input fields like mail address need correct format
→ support user with example data
mark required input fields
●
often (*) used
●
explain meaning of symbol
Web Applications V3.1 37
CSS (1)
CSS – abbreviation for Cascading Stylesheets
separates layout from contents
●
e.g. colours, fonts, border
different layouts for different media possible
replaces HTML elements as font, center
actual version is 3
●
continuously developed by W3C
using CSS in HTML file
●
mostly as separate file with link tag inside header tag
<link href="[Link]" rel="stylesheet">
Web Applications V3.1 38
CSS (2)
structure
selector {
property1 : value1; notice semicolon
property2 : value2;
property3 : value3;
}
selector
●
defines HTML element for which CSS instruction is defined
property
●
defines for what properties values can be defined, taken from predefined
set
value
●
possible values: predefined string or number
Web Applications V3.1 39
Selectors
different selectors possible
combination of selectors allowed
if there are multiple definitions for selector that from file last read is valid
Selector Example Description
.<class> .sm-3 all elements with this value in attribute
class
#<id> #firstname all elements with this value in attribute id
<element> p all elements with this tag name
element, element div, p all div and all p elements
element element div p all p elements inside div elements
element > element div > p all p elements whose parent is a div
element
Web Applications V3.1 40
CSS Properties (1)
link
●
can have any css property
●
make additional states distinguishable
– a:link – unvisited link
– a:visited – visited link
– a:hover – mouse pointer over link
– a:active – link which is clicked actually
●
example
– a:hover { color: hotpink; }
– demo
[Link]
s_link
Web Applications V3.1 41
Box Model
defines width and height of element
total width of element is sum of width, padding, width of border, and margin
similar for height
Web Applications V3.1 42
CSS Properties (2)
properties of border
●
border-style: possible values: dotted, dashed, solid, double
●
demo
[Link]
width of border
●
border-width: <n>px | thin | medium | thick
colour of border
●
border-color: name | #012345
all properties together
●
border: 5px solid red;
●
demo
[Link]
Web Applications V3.1 43
CSS Properties (3)
display
●
display: defines whether or how element is shown
●
display: block
– element starts in new line and fills available width
– is default for elements: div, h1 – h6, p, form
– demo
[Link]
block
●
display: inline
– element is in same line and has only as much width as needed
– is default for elements: span, a, img
– demo
[Link]
nline_list
●
display: none
– element not shown
Web Applications V3.1 44
CSS Properties (4)
display
●
display: inline-block
– additional element aside as far as space is sufficient
– demo
[Link]
ock
●
default value for element can be overwritten by value defined in CSS
file
Web Applications V3.1 45
Media Query (1)
checks different facts
●
width and height of viewport
●
width and height of monitor
●
orientation (tablet / smartphone in landscape mode or portrait mode)
●
resolution
consists of media type and one or several expressions which can be true
or false
media type
●
all devices: all
●
special device only: print, screen, speech
Web Applications V3.1 46
Media Query (2)
example
@media screen and (min-width: 480px) {
body {
background-color: lightgreen;
}
}
●
demo
[Link]
aquery
Web Applications V3.1 47
Responsive Web Design (1)
web page presented in readable way on all devices
●
desktop, tablet, smartphone
uses HTML and CSS only
●
no programming or JavaScript needed
information on small devices not omitted but layout adjusted to
size
●
avoid horizontal scrolling
– present elements on top of each other instead of side by
side
●
reduce size of elements if possible
Web Applications V3.1 48
Responsive Web Design (2)
Desktop Tablet Smartphone
Web Applications V3.1 49
Viewport
adjust size to device
<meta name="viewport" content="width=device-width, initial-scale=1.0">
●
width=device-width: width of page adjusted to width of device
●
initial-scale=1.0: initial zoom
without Viewport with Viewport
Web Applications V3.1 50
Layout of Templates
use responsive web design
●
page layout adjusted to screen size (smartphone, tablet, pc monitor)
●
avoid horizontal scrolling (badly readable)
●
switch from horizontal layout to vertical layout
●
adjust size of input fields or tables
CSS file bootstrap (for responsive web design) included in Spring via
WebJar in [Link]
●
WebJar takes concept of JAR and applies it to client-side libraries or
resources
using bootstrap in template
<link href="/webjars/bootstrap/5.1.0/css/[Link]"
rel="stylesheet"/>
demo [Link]
Web Applications V3.1 51
Layout With Bootstrap (1)
Bootstrap allows column layout up to 12 columns
Web Applications V3.1 52
Layout With Bootstrap (2)
CSS classes col-<xy>-<n>
●
<n> number from 1 to 12: corresponding multiple of base column width
●
sum of numbers of elements with class col-... ≤ 12
→ columns displayed side by side
for each number for classes
●
replace <xy> with nothing (for mobile phones), sm (for tablets),
md (for desktops), lg (for large desktops)
columns displayed side by side until pixel number specific for display is
reached, then columns are stacked
Web Applications V3.1 53
Layout With Bootstrap (3)
container contains whole page
<div class="container">: fixed width container
define inside container one or several div areas for rows
●
row contains several columns
<body>
<div class="container">
<div class="row">
<div class="col-sm-4">...</div>
<div class="col-sm-8">...</div>
</div>
</div>
</body>
demo
[Link]
er&stacked=h
Web Applications V3.1 54
Bootstrap Text / Typography
global default font-size is 16px, with line-height of 1.5
●
applied to <body> and all paragraphs (<p>)
<p> elements have have margin-top: 0 and margin-bottom: 1rem (16px by
default)
demo
[Link]
s&stacked=h
Web Applications V3.1 55
Bootstrap Tables and Images
basic table: .table
●
striped rows: .table-striped
●
bordered table: .table-bordered
●
hover rows: .table-hover
●
small table: .table-sm
●
responsive table: .table-responsive
demo [Link]
images
●
responsive image: .img-fluid
demo
[Link]
sive&stacked=h
Web Applications V3.1 56
Bootstrap Background Colors
can be used for success and error messages
●
.bg-success for success messages
– background is green
●
.bg-danger for error messages
– background is red
demo
[Link]
s&stacked=h
Web Applications V3.1 57
Bootstrap Buttons
style
●
basic: .btn
●
primary; btn-primary
size: .btn-lg, .btn-md, .btn-sm, .btn-xs
disabled: .disabled
button classes can be used on <a>, <button>, or <input>
demo
[Link]
es&stacked=h
Web Applications V3.1 58
Bootstrap Menu With Tabs (1)
<ul class="nav nav-tabs">
menu element is <li class="nav-item">
hyperlink <a class="nav-link" href="...">Link</a> inside <li>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link" href="...">Link</a>
</li>
</ul>
demo
[Link]
tacked=h
Web Applications V3.1 59
Bootstrap Menu With Tabs (2)
tab with dropdown
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-bs-toggle="dropdown"
href="#">Dropdown</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Link 1</a></li>
<li><a class="dropdown-item" href="#">Link 2</a></li>
<li><a class="dropdown-item" href="#">Link 3</a></li>
</ul>
</li>
demo
[Link]
ropdown&stacked=h
Web Applications V3.1 60
Bootstrap Navigation Bar (1)
is navigation header placed at top of page
standard navigation bar created with .navbar
<nav class="navbar navbar-default">
followed by responsive collapsing class: .navbar-expand-xxl|xl|lg|md|sm
(stacks the navbar vertically on corresponding size)
demo
[Link]
cked=h
Web Applications V3.1 61
Bootstrap Navigation Bar (2)
hide navigation links and replace them with button that should reveal them
when clicked on → collapsible navigation bar
create collapsible navigation bar
●
button with class="navbar-toggler", data-bs-toggle="collapse" and data-
bs-target="#thetarget"
●
wrap navbar content (links, etc) inside <div> element with
class="collapse navbar-collapse", followed by id that matches data-bs-
target of button: "thetarget"
demo
[Link]
apse
Web Applications V3.1 62
Bootstrap Form
form layout with label above input field
<input> with class .form-control gets proper form styling
<div class="mb-3 mt-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" id="firstName" name="firstName">
</div>
mt-3 and mb-3 set top and bottom margin
demo
[Link]
ed=h
will use Freemarker macros for defining input fields
Web Applications V3.1 63
Bootstrap Inline Form
form elements side by side → use .row and .col
<form>
<div class="row">
<div class="col">
<input type="text" class="form-control" placeholder="Enter email"
name="email">
</div>
<div class="col">
<input type="password" class="form-control" placeholder="Enter
password" name="pswd">
</div>
</div>
</form>
demo
[Link]
stacked=h
Web Applications V3.1 64
Web Application Example Study Program
define layout and menu
Web Applications V3.1 65
FreeMarker
Web Applications V3.1 66
Learning Targets
understand structure of FreeMarker template file
know elements to create FreeMarker template
Web Applications V3.1 67
View
Spring uses template language for view
Spring supports several view technologies
●
JavaServer Pages (JSP) and Java Standard Tag Library (JSTL)
●
Thymeleaf
●
Groovy Markup
●
Velocity
●
FreeMarker
FreeMarker used here
FreeMarker template consists of
●
static text (HTML tags and content, css, images, js)
●
instructions to FreeMarker for dynamic text
– instructions generate HTML tags and content
Web Applications V3.1 68
FreeMarker Template Language
Overview
●
basic principle
●
template
●
directives
●
expressions
●
build-ins
●
handling missing values
Web Applications V3.1 69
Template + Data
template contains static HTML and some instructions to FreeMarker that
makes it dynamic
view is called → FreeMarker replaces instructions with up-to-date content
●
browser receives plain HTML (+ CSS + JavaScript)
template contains
●
interpolations ${…}: replace in output with actual value of expression
inside curly bracket
●
FTL tags (instructions to FreeMarker): not printed to output
data is a map
●
access variables with key
●
sub variable accessed by lookup name
– path from basic key
– different parts of path separated by dot
●
possible data types: scalars (single value), other maps (element
accessed by lookup name)
Web Applications V3.1 70
Example: Template + Data
template
Hello ${[Link]} ${[Link]}!
data
public class Person {
private String firstName;
private String lastName;
// + set- / get- methods
data passed to template in controller
public ModelAndView showPerson(Person person) {
ModelAndView mv = new ModelAndView();
[Link](person).setViewName("firstExample/showPerson");
return mv;
}
Web Applications V3.1 71
Types in FreeMarker
scalar types
●
String: simple text
●
Number: integer numbers and decimal numbers not distinguished
●
Boolean: true or false
●
Date: date or time or date-time → see later for more details
container types
●
Hash: associates unique lookup name with each of its sub variables
– no ordering
●
Sequence: associates integer number with each of its sub variables
– but type of the sub variable values need not be the same
Web Applications V3.1 72
Template – Overall Structure (1)
template is mix of following sections
●
text: printed to output as is
●
interpolation
– replaced with calculated value in output
– delimited by ${ and }
●
FTL tags:
– similar to HTML tags
– instructions to FreeMarker and not printed to output
●
comments:
– similar to HTML comments
– delimited by <#-- and -->
– ignored by FreeMarker
– not written to output
Web Applications V3.1 73
Template – Overall Structure (2)
FreeMarker distinguishes upper case and lower case letters
interpolations can be used in text and in string literal
expressions only
FTL tag can't be inside another FTL tag nor inside an
interpolation
●
but FTL tag can be in content of FTL tag
comments can be placed inside FTL tags and interpolations
Web Applications V3.1 74
Example Template
<html> text
<head><title>Welcome!</title></head>
<body>
comment
<#-- Greet the user with his/her name -->
<h1>Welcome ${user}!</h1>
<p>We have these animals:
<ul> tag
<#list animals as animal>
<li>${[Link]} for ${[Link]} Euros
</#list>
interpolation
</ul>
</body></html>
Web Applications V3.1 75
Expressions
variables or more complex expressions used to supply values for
interpolations or directive parameters
value for interpolation: ${expression} where expression gives value to be
inserted into output as text
●
example: ${(5 + 8)/2} prints “6.5“
value for directive parameter
●
example: <#if expression>...</#if>
●
expression must evaluate to boolean value here
retrieving data from hash: use dot to connect name of subvariable:
[Link]
retrieving data from sequence: use square bracket with expression which
evaluates to number: animals[0].name
arithmetic calculation, comparison, logical operation allowed in expression
superfluous white spaces in expressions ignored
demo [Link]
Web Applications V3.1 76
Built-ins
built-ins similar to methods, added to objects by FreeMarker
syntax: object?built-in
omit “()” when built-in has no parameter
examples
●
user?upper_case: give user in upper cases
●
[Link]?cap_first: first letter to upper case
●
user?length: number of characters
●
animals?size: number of items in sequence
demo [Link]
Web Applications V3.1 77
Built-ins for Date and Time
FreeMarker does not support LocalDate, LocalTime
●
supports class Date only
●
convert LocalDate, LocalTime to Date before using built-ins
●
support of LocalDate, LocalTime possible by using additional libraries
specify which parts of date-like variable are in use
●
?date: date only, no time of the day.
●
?time: time of the day only, no date part
●
?datetime: both date and time
●
?string["format"]: define format string like format =”[Link], HH:mm”
demo [Link]
Web Applications V3.1 78
Built-ins for Sequences
first
●
first sub variable of sequence
●
template processing creates error if sequence is empty
last
●
last sub variable of sequence
●
template processing creates error if sequence is empty
reverse: sequence in reversed order
size: number of sub variables in sequence
demo [Link]
Web Applications V3.1 79
Built-ins for Hashes
keys
●
sequence that contains all lookup keys in hash
values
●
sequence that contains all variables (values in key-value pairs) in hash
example
<#list myHash?keys as key>
${key}
</#list>
demo [Link]
Web Applications V3.1 80
Handling missing values (1)
accessing missing value will create error and abort template processing
special operators suppress errors
default value operator
●
syntax: unsafe_expr!default_expr or unsafe_expr!
●
default value omitted
→ will be empty string and empty sequence and empty hash at same
time
→ cannot omit default value if it should be 0 or false
●
example
${[Link]!} outputs name when available and empty string else
Web Applications V3.1 81
Handling missing values (2)
missing value test operator
●
tells if value is missing or not
●
result is either true or false
●
syntax: unsafe_expr?? or (unsafe_expr)??
●
example
<#if [Link]??>
returns true when [Link] is not null
demo [Link]
Web Applications V3.1 82
Including Images, CSS
images, CSS files, JavaScript files must be placed in folder static or
subfolder of static
●
example static/css contains [Link]
●
example static/images contains [Link]
calling in template
●
start with path /css
●
example
<link rel="stylesheet" href="/css/[Link]"/>
<img src="/images/[Link]">
demo [Link]
Web Applications V3.1 83
Directives
use FTL tags to call directives
two kinds of FTL tags
●
start-tag: <#directivename parameters>
●
end-tag: </#directivename>
example
●
<#list animals as animal> and </#list>
format of parameters depends on name of directive
user-defined directives: use @ instead of #
●
example: directive has no nested content
→ use tag like <@mydirective parameters />
FTL tags must be properly nested
●
inner tag must be closed before outer tag is closed
Web Applications V3.1 84
Directives if, else, elseif
conditionally skip a section of the example
template <#if x == 1>
syntax x is 1
<#if condition>
<#elseif x == 2>
...
x is 2
<#elseif condition2>
... <#elseif x == 3>
<#elseif condition3> x is 3
... </#if>
... demo
<#else> [Link]
... ctiveIf
</#if>
condition, condition2, condition3
evaluate to boolean value
elseif and else are optional
Web Applications V3.1 85
Directive include
syntax <#include path>
insert another FreeMarker template file (specified by path parameter) into
template
output from included template is inserted at point where include tag occurs
included file processed each time when FreeMarker reaches include
directive during template processing
included file shares variables with including template
path parameter can be relative like "[Link]" and "../[Link]", or absolute like
"/[Link]"
●
relative paths are relative to directory of template that contains import
directive
use “/” (slash) to separate path components
example: <#include "/common/[Link]">
demo [Link]
Web Applications V3.1 86
Directive import
syntax: <#import path as hash>
●
path: path of template
– expression that evaluates to string
– may not be fixed string, can be something like [Link] +
"/[Link]"
– can be relative or absolute
●
hash: unquoted name of hash variable
– used to access the namespace
example
<#import "/libs/[Link]" as my>
<@[Link] date="1999-2002"/>
file [Link] delivered with Spring has macros to be used for form
Web Applications V3.1 87
Directives list, else, items, sep, break (1)
syntax
●
simplest form for listing sequence
<#list sequence as item>
Part repeated for each item
</#list>
●
listing hash
<#list hash?keys as key>
Part repeated for each key: ${hash[key]...}
</#list>
Web Applications V3.1 88
Directives list, else, items, sep, break (2)
syntax syntax
●
empty sequence possible ●
output something once
<#list sequence as item> <#list sequence>
Part repeated for each item Part executed once if we
have more than 0 items
<#else>
<#items as item>
Part executed when there Part repeated for each
are 0 items item
</#list> </#items>
Part executed once if we
have more than 0 items
<#else>
Part executed when there
are 0 items
</#list>
Web Applications V3.1 89
Directives list, else, items, sep, break (3)
example
<#list users as user>
<p>${user}
<#else>
<p>No users
</#list>
else directive used when there are 0 items
items directive used to print something before first list item, and after last list
item, as far as there's at least 1 item
sep used to display something between each item (but not before first item
or after last item)
example: <#list users as user>${user}<#sep>, </#list>
break directive: exit iteration at any point
Web Applications V3.1 90
Loop variable built-ins
counter: 1-based index where iteration currently stands
index: 0-based index where the iteration currently stands
has_next: tells if item where the iteration currently stands is not last item
is_first / is_last: tells if item of current iteration is first / last item
example: data is sequence of strings
<ul>
<#list data as dataElem>
<li>${dataElem?counter}</li>
</#list>
</ul>
demo [Link]
Web Applications V3.1 91
Directives macro, return (1)
syntax name: name of macro variable, not an
expression
<#macro name param1
param2 ... paramN>
param1, param2, ...: name of local variables
●
store parameter values (not an
... expression)
<#return>
●
optionally followed by = and default value
(that is an expression)
... ●
parameters without default value must
</#macro> precede parameters with default value
directive return optional
●
can be used anywhere and for any times
between <#macro ...> and </#macro>
Web Applications V3.1 92
Directives macro, return (2)
<#macro ...> creates macro variable
macro variable stores template fragment (macro definition body)
variable also stores name of allowed parameters
all parameters must have values when using macro as directive
●
exception: parameters with default value
variable will be created at beginning of template
●
does not matter where macro directive is placed in template
Web Applications V3.1 93
Directives macro, return (3)
example: macro without example: macro with parameters
parameters
<#macro test foo bar baaz>
<#macro test>
Test text, and the params: ${foo},
Test text ${bar}, ${baaz}
</#macro> </#macro>
<#-- call the macro: --> <#-- call the macro: -->
<@test/> <@test foo="a" bar="b" baaz=5*5-
2/>
what is the output?
what is the output?
Web Applications V3.1 94
Directives macro, return (4)
example: more complex macro
<#macro list title items>
<p>${title?cap_first}:
<ul>
<#list items as x>
<li>${x?cap_first}
</#list>
</ul>
</#macro>
<@list items=["mouse", "elephant", "python"] title="Animals"/>
What is the output?
demo [Link]
Web Applications V3.1 95
Directives macro, return (5)
directive return : leave macro definition body anywhere
example
#macro test>
Test text
<#return>
Will not be printed.
</#macro>
<@test/>
what is the output?
Web Applications V3.1 96
Template Inheritance with Macros
goal: define common parts of template once only
base template
●
defines macro with layout
●
layout macro contains other macros which can be redefined
●
no output outside macros
child template
●
includes base template
●
redefines macros when needed
●
calls layout macro
●
order is important
– first redefine macros, then call layout macro
demo [Link]
Web Applications V3.1 97
Web Application Example Study Program
define template layout with macros
Web Applications V3.1 98
Model in Spring MVC
Web Applications V3.1 99
Model (1)
used to capture form data and transfer data to view
implemented as JavaBean
Spring transfers input value to JavaBean property automatically when
●
JavaBean object is parameter in called controller method
●
attribute name in form element and JavaBean property is identical
●
example
– form
<input type="text" class="form-control" name="firstName">
– controller
@PostMapping("/model/editPerson")
public ModelAndView showPerson(Person person) {…}
– model
public class Person {
public void setFirstName(String firstName) {…}
}
Web Applications V3.1 100
Model (2)
transfer of values also works with linked objects
●
example
– form
<input type="text" class="form-control" name="[Link]">
– controller
@PostMapping("/model/editPerson")
public ModelAndView showPerson(Person person) {…}
– model
public void setAddress(Address address) {…} in class Person and
public void setZipCode(String zipCode) {…} in class Address
demo [Link]
Web Applications V3.1 101
Connecting Form with Model (1)
Spring contains FreeMarker macros for creating form elements in file
[Link]
●
import: <#import "[Link]" as spring>
advantages when using macros
●
reduce redundancy
– same string for different purposes: used in attributes name, id, for
●
input fields filled after update of form
controller for GET must have Model and BindingResult as parameters
show text from [Link]
<@[Link] code/>
●
code is key in file src/main/resources/[Link]
parameter path: name of connected attribute in model
parameter attribute in macros: add further attributes to html tag, e.g. css-
classes
Web Applications V3.1 102
Connecting Form with Model (2)
input text field
<@[Link] path, attributes, fieldType/>
●
path: name of model attribute
●
attributes: additional attributes like CSS classes
●
fieldType: define special field type, e.g. “number”, default is “text”
●
example
<@[Link] "[Link]" "class='form-control'"/>
password text field
<@[Link] path, attributes/>
dropdown list, single select
<@[Link] path, options, attributes/>
●
options
– map containing entries of dropdown list, e.g (key, value)-pairs
– value shown as list entry, key sent to server when selected
Web Applications V3.1 103
Connecting Form with Model (3)
multiple select list
<@[Link] path, options, attributes/>
●
path and options similar to single select list
radio button
<@[Link] path, options separator, attributes/>
●
path and options similar to single select list
●
separator: separates radio buttons
– separator = “<br>”: vertical radio buttons
– separator = “ ”: horizontal radio buttons with space between
elements
●
attributes not required
Web Applications V3.1 104
Connecting Form with Model (4)
several check boxes
<@[Link] path, options, separator, attributes/>
●
attributes similar to radio button
single check box
<@[Link] path, attributes/>
keep in mind: checkbox and radio button don't use "class='form-control'"
show errors (conversion, validation) for input field
<@[Link] separator, classOrStyle/>
●
separator separates several error messages, e.g. “<br>” for writing each
error message in separate line
●
name of input field automatically derived from preceding @[Link]...
macro
demo [Link]
Web Applications V3.1 105
Web Application Example Study Program
create form for adding a course
output list of courses
Web Applications V3.1 106
More about Spring MVC
Web Applications V3.1 107
Learning Targets
understand model part in Spring MVC
●
conversion of data
●
validation of data
Web Applications V3.1 108
Converter (1)
input in form of website is of type String
Spring transforms String into data type used in model
standard converter available for some data types
●
char, int, double, float
– missing value for char creates error in BindingResult
– missing value for int, double, float will be set to 0
●
wrapper classes Integer, Double, Float
– missing value results in null reference
custom converter needed for conversion to other data types
Web Applications V3.1 109
Converter (2)
customize error message
●
entry <key> = <value> in file src/main/resources/[Link]
●
key: typeMismatch.<class name starting with lower case letter>.<field
name> or typeMismatch.<field name>
●
value: error message shown to user
●
example: error message for conversion of field intNumber in class
ConverterModel
[Link] = Enter a valid number.
demo [Link]
Web Applications V3.1 110
Custom Converter for Type (1)
custom converter has to implement interface
[Link]<S,T>
●
S is source type
●
T is target type
●
method T convert(S s)
converter with annotation @Component is registered automatically in Spring
Boot
custom converter used in form only not in interpolation
example
●
converter StringToLocalDateConverter
●
form with <input type=”text”...name=”localdate”>
●
model with property LocalDate localdate
●
controller method showCustomConvertedData(CustomConverterModel
model, BindingResult bindingResult)
Web Applications V3.1 111
Custom Converter for Type (2)
when conversion fails, Spring shows standard error message
customize error message in [Link]
●
structure same as for standard converter
show error in template with macro
<@[Link] separator, classOrStyle/>
Web Applications V3.1 112
Date Converter
class CustomDateEditor
●
parses user-entered number strings into Date properties of beans
●
date format entered as string in class SimpleDateFormat
●
registration in method with annotation @InitBinder("<object name>")
[Link]([Link], "date",
new CustomDateEditor(dateFormatter, true));
●
different formats for different attributes possible
customize error message in [Link]
●
structure same as for standard converter
show error in template with macro
<@[Link] separator, classOrStyle/>
demo [Link]
Web Applications V3.1 113
Validation
Spring supports 2 methods for validation
●
implement Spring Validator interface
●
use JSR303 and JSR349 validation (bean validation)
– annotation based
– recommended for new projects
principles of JSR303 and JSR349 validation
●
add annotation @Valid to model object in controller method
●
add object of type BindingResult as parameter in controller method
– must be directly after model object
– validation error similar to conversion error
●
add validation annotation to attribute of model object
●
use default error message, create error message in file
[Link], or use message attribute in annotation
●
output error message in template
Web Applications V3.1 114
Annotations for Bean Validation (1)
different annotations for different validation tasks
set of predefined annotations available
for special validation tasks custom annotations possible
annotation supported data types use
@AssertFalse Boolean, boolean checks that annotated element is
false
@AssertTrue Boolean, boolean checks that annotated element is
true
@DecimalMax BigDecimal, element must be number whose
(“<value>“) BigInteger, byte, value must be lower or equal to
short, int, long and specified maximum, value is
respective wrappers string representation of max value
of primitive types according to BigDecimal string
representation
Web Applications V3.1 115
Annotations for Bean Validation (2)
annotation supported data types use
@DecimalMin BigDecimal, element must be number whose value
(“<value>“) BigInteger, byte, must be higher or equal to specified
short, int, long and maximum, value is string
respective wrappers representation of min value according
of primitive types to BigDecimal string representation
@Digits(inte- BigDecimal, annotated value must be number
ger=, BigInteger, byte, having up to integer digits and fraction
fraction=) short, int, long and fractional digits
respective wrappers
of primitive types
@Future [Link], annotated date must be in future
[Link]
Web Applications V3.1 116
Annotations for Bean Validation (3)
annotation supported data types use
@Max BigDecimal, value must be less than or equal to
(<value>) BigInteger, byte, specified maximum
short, int, long and
respective wrappers
of primitive types
@Min BigDecimal, value must be higher than or equal to
(<value>) BigInteger, byte, specified minimum
short, int, long and
respective wrappers
of primitive types
@NotBlank String not null and contains at least one non
whitespace character
@NotNull any type value may not be null
Web Applications V3.1 117
Annotations for Bean Validation (4)
annotation supported data types use
@Past [Link], annotated date must be in past
[Link]
@Pattern String string must match regular expression
(regex= reg-exp
“<reg-exp>“)
@Size(min=, String, Collection, size of element is between min and
max=) Map and arrays max (inclusive)
@Valid any non-primitive performs validation recursively on
type associated object
Web Applications V3.1 118
Error Messages (1)
bean annotation has own error message
for individual error messages use file [Link]
entries in [Link] have form key = value
schemes for key
●
<annotation name (without @)>.<class name starting with lower case
letter>.<attribute name>
●
<annotation name (without @)>.<field name>
●
<annotation name (without @)>
value: text of error message
Web Applications V3.1 119
Error Messages (2)
example
●
class ValidationModel
@AssertTrue private boolean checkTrue;
●
[Link]
[Link] = Check True must be marked.
output error message in template
●
use macro @[Link] from file [Link]
demo [Link]
Web Applications V3.1 120
Custom Validation for Field (1)
example: validate Date not at weekend
annotation definition
@Target({METHOD, FIELD, ANNOTATION_TYPE}) implementing class
@Retention(RUNTIME)
@Constraint(validatedBy = [Link])
public @interface NotWeekend {
String message() default "Date on weekend not allowed.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Web Applications V3.1 121
Custom Validation for Field (2)
annotation implementation
public class NotWeekendValidator implements
ConstraintValidator<NotWeekend, Date> {
@Override
public boolean isValid (Date value, ConstraintValidatorContext context) {
if (value != null) {
GregorianCalendar gc = new GregorianCalendar();
[Link](value);
int dayOfWeek = [Link](GregorianCalendar.DAY_OF_WEEK);
if (dayOfWeek == 1 || dayOfWeek == 7)
return false;
}
return true;
}
@Override public void initialize (NotWeekend a) { }
}
Web Applications V3.1 122
Custom Validation for Field (3)
error message in [Link]
[Link] = Date on weekend not allowed
error message displayed in template with macro
@[Link]
Web Applications V3.1 123
Custom Validation for Several Fields (1)
example
●
two time fields: Start Time and End Time
●
validate that Start Time is before End Time
annotation for field not possible
→ create annotation for class
@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = [Link])
public @interface TimeOrder {
String message() default "Start time must be earlier than end time.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Web Applications V3.1 124
Custom Validation for Several Fields (2)
annotation implementation
public class TimeOrderValidator implements
ConstraintValidator<TimeOrder, Appointment> {
@Override public void initialize (TimeOrder constraintAnnotation) { }
@Override
public boolean isValid (Appointment value,
ConstraintValidatorContext context) {
if ([Link]() != null && [Link]() != null) {
return [Link]().before([Link]());
}
return true; // ← no validation for empty fields
}
}
Web Applications V3.1 125
Custom Validation for Several Fields (3)
usage of validators
@TimeOrder
public class Appointment {
@NotWeekend
private Date date;
private Date startTime;
private Date endTime;
…}
Web Applications V3.1 126
Custom Validation for Several Fields (4)
error message in [Link]
[Link] = Start Time must be before End Time.
display error message in template
●
error in BindingResult is not FieldError but GlobalError
●
cannot be displayed with @[Link]
→ create own output
<@[Link] "appointment" />
<#if [Link]>
<#list [Link] as error>
<div class="bg-danger"><@[Link] [Link][0]/></div>
</#list>
</#if>
demo [Link]
Web Applications V3.1 127
Display Errors From Application Logic (1)
communicate error from application logic with RuntimeException or subclass
in controller method
●
catch exception and add ObjectError or FieldError to BindingResult with
method addError
●
ObjectError
ObjectError(String objectName, String[] codes, Object[] arguments,
String defaultMessage)
– objectName: name of affected object
– codes: used to resolve error message in [Link], 1
element suffices
– arguments: variable part for error message, can be null when no
variable parts in error message
– defaultMessage: can be null
Web Applications V3.1 128
Display Errors From Application Logic (2)
in controller method
●
ObjectError
– example
String [ ] codes = {"[Link]"};
ObjectError oe = new ObjectError ("appointment", codes, null, null);
[Link] (oe);
●
error message displayed in template same way as validation errors at
class level
●
no internationalisation needed → pass error message as data to
template
<#if errorMessage??>
<div class="bg-danger" style="margin-bottom: 10px;">
${errorMessage}
</div>
</#if>
Web Applications V3.1 129
Display Errors From Application Logic (3)
in controller method
●
FieldError
FieldError(String objectName, String field, Object rejectedValue,
boolean bindingFailure, String[] codes, Object[] arguments,
String defaultMessage)
– subclass of ObjectError
– objectName: name of affected object
– field: affected field of object
– rejectedValue: must be of same type as field in model
– bindingFailure: false (= validation failure)
– codes → codes in ObjectError
– arguments → see arguments in ObjectError
– defaultMessage → see default message in ObjectError
Web Applications V3.1 130
Display Errors From Application Logic (4)
in controller method
●
FieldError
– example
String [ ] codes = {"[Link]"};
FieldError fe = new FieldError("appointment", "startTime",
[Link](), false, codes, null, null);
[Link](fe);
– error message displayed in template with @[Link]
catch exceptions in controller
●
Spring shows default error page when exception escapes controller
Web Applications V3.1 131
Web Application Example Study Program
add validations
●
course name and lecturer must not be empty
●
course names must be unique
Web Applications V3.1 132
HTTPSession (1)
HTTP is stateless protocol
●
each client request independent from all others
●
not possible to store information across several requests on HTTP level
typical scenarios when information across several request needed
●
user identification
●
shopping cart in online shop
identification of client with IP address to attach some data not secure
possible solutions
●
transport data in each request between client and server → cookie
●
store data on server → session object with session ID
– session ID still exchanged between client and server
→ use session cookie, URL rewriting, hidden form field
Web Applications V3.1 133
HTTPSession (2)
servlet engine manages sessions
●
create object, read object, timeout
●
connection to client via session cookie
– session cookie managed by servlet engine
each browser has its own cookie management
→ different browsers on same computer will be considered as different
clients
→ inside browser only one session cookie per web application
[Link]: interface for session object
injected into controller method when parameter is of type HTTPSession
Web Applications V3.1 134
HTTPSession (3)
method description
String getID() unique identificator for session
long getCreationTime() creation date in milliseconds since
January 1, 1970
long getLastAccessedTime() last access date since January 1,
1970
Enumeration getAttributeNames() returns names of all objects in session
Object getAttribute( String name) returns object with this name in
session
void setAttribute(String name, Object stores object with name in session
value)
void remove Attribute(String name) removes object with name in session
void setMaxInactiveInterval(int sets number of seconds between to
intervall) accesses before session becomes
invalid
Web Applications V3.1 135
HTTPSession (4)
inactive session gets timeout in servlet engine
●
default 30 minutes for Tomcat
set timeout in minutes
●
in [Link]
[Link] = 1
demo [Link]
Web Applications V3.1 136
Annotation @SessionAttributes (1)
use 1 or more objects from session
works inside a controller class only
using @SessionAttributes objects
●
add annotation @SessionAttributes(names={...}, values={...}) to
controller class
●
example
@Controller
@SessionAttributes(names = {"counter1", "conter2"},
types={[Link], [Link]})
public class SessionController {...}
Web Applications V3.1 137
Annotation @SessionAttributes (2)
using @SessionAttributes objects
●
create method with annotation @ModelAttribute(“<...>”) to initialize
session object
●
example
@ModelAttribute("counter1")
public Counter initCounter1() { return new Counter(); }
●
add parameter with annotation @ModelAttribute(“<...>”) to controller
method
●
example
@GetMapping("/session/sessionattribute")
public ModelAndView getWith2Counters (@ModelAttribute("counter1")
Counter counter1, @ModelAttribute("counter2") Counter counter2) {…}
●
objects can be used in controller method then
Web Applications V3.1 138
Annotation @SessionAttributes (3)
remove @SessionAttributes objects
●
add SessionStatus object to controller method
●
call [Link]() in controller method
●
all @SessionAttributes objects which are used as @ModelAttribute
parameters in this controller method are removed from session
●
example
@GetMapping("/session/sessionattributeanddelete")
public ModelAndView getWith2CountersDelete
(@ModelAttribute("counter1")Counter counter1, SessionStatus
seossionStatus, @ModelAttribute("counter2") Counter counter2){...
[Link]();...}
demo [Link]
Web Applications V3.1 139
Session Scoped Bean (1)
create session scoped bean
●
create class with annotations @Component, @Scope
●
example
@Component
@Scope(value = "session", proxyMode =
ScopedProxyMode.TARGET_CLASS)
public class CounterBean {…}
use session scoped bean in controller
●
add attribute with annotation @Autowired
●
bean object created by Spring automatically
●
bean object can be used like any other attribute
Web Applications V3.1 140
Session Scoped Bean (2)
use session scoped bean in controller
●
example
@Autowired
private CounterBean counterBean;
delete session scoped bean
●
use method removeAttribute from class HttpSession
●
name of object in session: “scopedTarget.<class name starting with
lower case letter>
●
example
[Link]("[Link]");
demo [Link]
Web Applications V3.1 141
Internationalisation (1)
internationalisation (i18n): prepare application for usage of different
languages
localisation: provide application for specific locale
principle: no hard coded text in templates
●
use keys that refer to text in message files
name of message file: message_<language>_<country>.properties
●
country is optional
●
use language code from ISO 639
●
use country code from ISO 3166
●
example
– messages_en_GB.properties: English for Great Britain
– messages_en_US.properties: English for United States
– messages_en.properties: English in general
Web Applications V3.1 142
Internationalisation (2)
i18n in Spring Boot MVC
●
replace hard coded text in templates with FreeMarker macro
<@[Link] "<key>"/>
●
provide <key> = <value> entry in messages_....properties
Web Applications V3.1 143
Locale from Browser (1)
Spring determines locale from field Accept-Header in HTTP-request
automatically
criteria for language selection
●
browser sends <language>_<country>
– key in messages_<language>_<country>.properties available
→ value from messages_<language>_<country>.properties taken
– key in messages_<language>_<country>.properties not available
key in messages_<language>.properties available
→ value from messages_<language>.properties taken
Web Applications V3.1 144
Locale from Browser (2)
criteria for language selection
●
browser sends <language>_<country>
– file messages_<language>_<country>.properties not available
file messages_<language>.properties not available
key in messages_<OS-locale>.properties available
→ value from messages_<OS-locale>.properties taken
– file messages_<language>_<country>.properties not available
file messages_<language>.properties not available
key in messages_<OS-locale>.properties not available
key in [Link] available
→ value from [Link] taken
●
behaviour when browser sends <language> similar
demo [Link]
Web Applications V3.1 145
Locale from User Interface (1)
define links or buttons in template
<form action="/internationalisation/switchToGerman" method="POST"
style="display:inline">
<input type="image" src="/images/[Link]" alt="Submit" width="24"
height="14"/>
</form>
implement controller method: parameter for language to URL
@PostMapping("internationalisation/switchToGerman")
public String switchToGerman(Person person, BindingResult
bindingResult) {
return "redirect:/internationalisation/localefromuser?lang=de";
}
Web Applications V3.1 146
Locale from User Interface (2)
implement interceptor for language switch
@SpringBootApplication
public class App implements WebMvcConfigurer {
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
[Link]("lang");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
[Link](localeChangeInterceptor());
}... }
Web Applications V3.1 147
Locale from User Interface (3)
implement LocaleResolver
@SpringBootApplication
public class App implements WebMvcConfigurer {
@Bean
public CookieLocaleResolver localeResolver(){
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
[Link]([Link]);
[Link]("my-locale-cookie");
[Link](3600);
return localeResolver;
}…}
Web Applications V3.1 148
Locale from User Interface (4)
alternatives for LocaleResolver
●
AcceptHeaderLocaleResolver
– uses primary locale specified in "accept-language" header of HTTP
request
●
CookieLocaleResolver
– uses cookie sent back to user in case of custom setting
– fall back to specified default locale or request's accept-header locale
●
SessionLocaleResolver
– uses locale attribute in user's session in case of custom setting
– fallback to specified default locale or request's accept-header locale
– appropriate if application needs user sessions anyway
demo [Link]
Web Applications V3.1 149
Filter (1)
do some checks and redirect to another page when checks not fulfilled
called for all requests or requests with defined URL pattern
example
●
check whether login is valid for some pages
– login check not really needed because Spring has its own security
package
implementation of filter
●
implement interface [Link]
– void init(FilterConfig fc)
– void destroy()
– void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc)
Web Applications V3.1 150
Filter (2)
implementation of filter
●
check implemented in doFilter
– ServletRequest contains incoming message
– has to be cast to HttpServletRequest
– call redirect when check fails
– call [Link] when check is ok
Web Applications V3.1 151
Filter (3)
implementation of filter
●
example
public void doFilter(ServletRequest sr, ServletResponse sr1,
FilterChain fc) throws IOException, ServletException {
String url = ((HttpServletRequest) sr).getRequestURL().toString();
if ([Link]("/filter/secure")) {
User user = (User) ((HttpServletRequest)
sr).getSession().getAttribute("user");
if (user == null || [Link]() == null ||
! [Link]().equals("admin")) {
((HttpServletResponse) sr1).sendRedirect("/filter/login");
return;
}
}
[Link](sr, sr1);
}
Web Applications V3.1 152
Filter (4)
filter registered in Spring Boot automatically for path “/”
●
in principal possible to deregister filter and register for another path but
seems not working
demo [Link]
Web Applications V3.1 153
Using JQuery (1)
JQuery already available in Spring using webjar
●
add <script src="/webjars/jquery/3.3.1-1/[Link]"></script> in
template
call JavaScript functions only when DOM is created
$(document).ready( … );
●
prefer this to [Link](...)
select elements of DOM
●
with ID: $('#<id>')
●
with Tag: $('p')
●
with CSS class: $('.<class>')
selection over several steps possible
●
$('p a'): all tags <a> inside tag <p>
●
$('p>a'): all tags <a> whose parent is <p>
Web Applications V3.1 154
Using JQuery (2)
return value of $(...) is JQuery object
●
JQuery functions can be used for this object
JQuery object contains more than one element
→ function applied to every element in object
register handler for event
●
general form: .on( type, handler )
type: type of event, e.g. 'click'
handler: function which is called when event occurs
●
short version for click: .click(function() { … })
deregister handler: .off('<type>')
Web Applications V3.1 155
Using JQuery (3)
access value of element
●
read: $(...).val()
●
write: $(...).val('<new value>');
access attribute of element: $(...).attr("<name>");
append element as child element: $(...).append(...)
suppress default behaviour: [Link]();
animations
●
show selected elements: $(...).show([speed])
●
hide selected elements: $(...).hide([speed])
●
toggle selected elements: $(...).toggle([speed])
●
show or hide elements with sliding movement
$(...).slideToggle([speed])
Web Applications V3.1 156
Toggle DOM Element (1)
Template
<head>
<meta ...>
<script src="/webjars/jquery/5.1.0/[Link]"></script>
<script src="/js/[Link]"></script>
</head>
<body>
<h2>Using JQuery</h2>
<p><button id="togglePerson" value="Hide">Hide</button></p>
<p id="person">
Name of person<br>
${[Link]} ${[Link]}
</p>
</body>
Web Applications V3.1 157
Toggle DOM Element (2)
JavaScript file
$(document).ready(function () {
$('button').click(function () {
var button = $('#togglePerson');
[Link]() === 'Show' ? [Link]('Hide') : [Link]('Show');
$('#person').slideToggle(1000);
});
});
Web Applications V3.1 158
Asynchronous Read with AJAX (1)
Template
<html>
<head> <meta ...>
<script src="/webjars/jquery/3.3.1-1/[Link]"></script>
<script src="/js/[Link]"></script>
</head>
<body> <h1>AJAX Call</h1>
<p>
<a id="1" href="" data-path="${path}/person/1">Person 1</a>
<a id="2" href="" data-path="${path}/person/2">Person 2</a>
</p>
</body></html>
Web Applications V3.1 159
Asynchronous Read with AJAX (2)
JavaScript
$(document).ready( function(){
$("p a").click(function (event) {
[Link]();
var path = $(this).attr("data-path");
var parent = $(this).parent();
$.ajax({url: path, type: "GET",
success: function (person) { [Link]('<div>' + [Link]
+ ' ' + [Link] + ' ' + [Link] + '</div>');
}});
$(this).off('click');
$(this).click(function (event) { [Link]();
}); });});
Web Applications V3.1 160
Asynchronous Read with AJAX (3)
Controller for /person/{number}
@GetMapping("/javascript/ajaxCall/person/{number}")
public @ResponseBody Person2 getPerson(@PathVariable("number")
int number) {
Person2 person;
if (number == 1) { person = new Person2("Jane", "Doe");
} else { person = new Person2("Peter", "Miller");
}
return person;
}
demo [Link]
Web Applications V3.1 161
Drag & Drop with JQueryUI (1)
add CSS and JavaScript to template
<link href="/webjars/jquery-ui/1.12.1/[Link]" rel="stylesheet"/>
<script src="/webjars/jquery-ui/1.12.1/[Link]"></script>
define target and source area in template
<div class="col-3" style="border-style: solid" id="source">
<h3>Source</h3>
<img src="/images/[Link]" class="..." width="100">
<img src="7images/[Link]" class="..." width="100">
</div>
<div class="offset-3 col-3" style="border-style: solid; height: 270px;
overflow-y:scroll" id="target">
<h3>Target</h3>
</div>
Web Applications V3.1 162
Drag & Drop with JQueryUI (2)
function draggable allows to move elements
$('#target img').draggable({
helper: 'clone',
appendTo: 'body'
});
option helper: move copy only
option appendTo: moved element visible outside containing area
Web Applications V3.1 163
Drag & Drop with JQueryUI (3)
define area to drop draggable element
$('#target').droppable({
drop: handleDropEvent
});
handleDropEvent
●
add element to container
function handleDropEvent(event, ui) {
var draggable = [Link];
var elem = '<img class="img-responsive center-block" src="'
+ [Link]('src') + '" width="' + [Link]('width') + '">';
$(elem).insertAfter('#target h3');
}
demo [Link]
Web Applications V3.1 164
Drag & Drop with JQueryUI (4)
define graphical elements
<div class="row">
<div id="area1" class="col-3 area"></div>
<div class="col-6" >
<div class="img-responsive-parent"><img src="...></div>
</div>
<div id="area2" class="col-3 area"></div>
</div>
<div class="row"> ...
<div class="col-4 "><img src="...> </div>
<div id="area5" class="col-4 area" ><img src="...></div>
<div class="col-4"> <img src="...> </div>
</div>
<div class="row">...</div>
Web Applications V3.1 165
Drag & Drop with JQueryUI (5)
define neighbours
neighbors = {
area1: ["area2", "area3", "area5"],
area2: ["area1", "area4", "area5"],
area3: ["area1", "area4"],
area4: ["area2", "area3"],
area5: ["area1", "area2"]
}; area to drag man
drag man with mouse
$('#person').draggable({
containment: '#content', man in foreground always
stack: '#person',
revert: 'invalid' element returns to old place
}); when not put on droppable area
Web Applications V3.1 166
Drag & Drop with JQueryUI (6)
mark neighbours of current element as droppable
●
$.each(array, callback): function callback called for each element of
array
●
callback is function with parameters index, value
$.each(neighbors[parent], function(index, value) {
$('#'+value).droppable({
drop: handleDropEvent,
hoverClass: 'hovered'
});
});
Web Applications V3.1 167
Drag & Drop with JQueryUI (7)
mark neighbours of actual element as droppable
●
$('selector').droppable has options
– drop: called function if draggable is put on droppables
– signature drop(event, ui): ui is droppable object
– hoverClass: CSS class added to droppable if draggable is on
droppable
put man on new place
●
handleDropEvent(event, ui)
– remove old object
– create new object and make it draggable
– make neighbours of parent of new object droppable
demo [Link]
Web Applications V3.1 168