02 Web Basics
02 Web Basics
> Thymeleaf
<< service>>
Client Server
> Web application: when the communication over TCP follows the HTTP
protocol
HTTP basics
> Client opens a TCP connection to the server, and sends a request
> The server sends the response back over this connection
> The connection can remain open (since HTTP 1.1), and clients may send
further requests
> HTTP over TCP connection secured with TLS = HTTPS (default port: 443)
> Stateless: the protocol does not keep client-specific state between two
requests
HTTP basics
> Clients use the HTTP “verbs” to express their intent with the addressed
resource
HTTP verbs
> GET: read an existing resource, body of the request is empty
> POST: create a new resource that is described in the body of the request
> PUT: modify an existing resource, with the data sent in request body
> HEAD: similar to GET, but the client requests only the headers of the
response, without body (possible use case: check if a cached resource is
expired)
> TRACE: for diagnostics, the path of fhe request can be traced
> Static content: same response to same request (e.g. a picture stored at
the server)
> Dynamic content: a program code running at the server generates the
response we can get different response to the same request depending
on e.g. time/user/data stored at the server
Fundamentals of web development
Servlet, JSP
> Thymeleaf
> The process during which the web application is installed to a web
container
> The web application is available after deployment
> Context – the environment of the web application, handled by the web
container
> Virtual directory, e.g. newapp.war http://myserver.com/newapp/
> Separate class loader for each context (WEB-INF/classes, WEB-INF/lib)
Fundamentals of web development
> Thymeleaf
> One parameter in the URL, and says hello to that person, e.g.:
http://localhost:8080/hello?user=Peter
> Result:
Hello Peter
HelloWorldController.java
@Controller
public class HelloWorldController {
@GetMapping("/hello")
public String helloWorld(
@RequestParam("user") String user,
Map<String, Object> model) {
model.put("welcome", "Hello " + user);
return "index";
}
}
index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Welcome</title>
</head>
<body>
<h1 th:text="${welcome}">Some welcome</h1>
</body>
</html>
Configuring Spring MVC
Handler methods
> Thymeleaf
> Controller classes can have any number of handler methods, handling
different requests
> The controller class can have a @RequestMaping annotation as well, URL
patterns on the handler methods are meant relative to this
> Since Spring MVC 4.3, @GetMapping, @PostMapping, … can be used instead of
@RequestMapping(method=GET/POST/…)
Controller class: handler methods
> Any type, annotated with @ResponseBody (the returned object will be
serialized into the reponse body, using a HttpMessageConverter)
Thymeleaf
> Thymeleaf
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>
I18N expressions
> Syntax: #{}
> We can reference keys that have localized translations in properties files, e.g.
<h2 th:text="#{welcome}">Welcome</h2>
> We need to configure a MessageSource bean that will be used for the
translation:
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource =
new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:Messages");
return messageSource;
}
> Messages_en.properties on the classpath, containing
welcome=Hello
> Messages_hu.properties on the classpath, containing
welcome=Üdvözöljük
URL expressions
> th:each
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
</tr>
</table>
> Implicit variable for the status of the iteration: prodStat, provides access to:
> index (starting from 0), count (starting from 1), size,
> boolean properties: even, odd, first, last
Conditional expressions
> th:if
> When evaluates to false, the given tag is not rendered
<span th:if="${prod.price lt 100}“ class="offer">
Special offer!
</span>
> Negation:
> not or ! before the expression
> th:unless: not displayed if evaluated to true
> Simplifications:
> null means false
> considered true (truthy):
> Number or character differing from 0
> String, except: "false", "off", "no"
> Any other non-null object except for boolean, number, character,
String
Conditional expressions
> Thymeleaf
> With Thymeleaf we generate full web pages at the server side
> Data mixed with presentation
> Different approach: server returns only data, client side (browser, mobile
application) is responsible for presenting them
> RESTful service (REST API): a service accessible through HTTP, addressed
with URIs, defined by
> URI of the service
> Data format supported by the service
> The HTTP methods (usually GET/POST/PUT/DELETE) supported by the
service
> http://example.com/books/
> GET: returns the list of books (possibly read from a database)
> POST: inserts a new book in the list
> Data of the book are sent in the HTTP body
> Identifier is generated at the server
> DELETE: deletes the whole list
> PUT: replaces the whole list
> New data of the book are sent in the HTTP body
> http://example.com/books/xyz
> GET: returns one book, with identifier xyz
> POST: the element with identifier xyz is considered as a list, and adds a
new element to this list (e. g. adds a new chapter in the book)
> DELETE: deletes the book, with identifier xyz
> PUT: modifies the xyz book, or creates a new one with xyz identifier
JSON
{ "firstName": "John",
"lastName": "Smith",
> JavaScript Object Notation "age": 25,
> But can be uses not only in "address": {
"streetAddress": "21 2nd Street",
JavaScript "city": "New York",
> Text based format, briefer than "state": "NY",
XML "postalCode": "10021"
> Object: {} },
"phoneNumber": [
> Can be nested { "type": "home",
> Object properties: "number": "212 555-1234"
> “key”: value, },
> Array: [, , ,] { "type": "fax",
"number": "646 555-4567"
> Base types }
> string ("abc“) ]
> number (5.23) }
> boolean: true or false
> null
Developing REST APIs with Spring MVC
> Add the necessary dependencies to the pom file of the hr application to use
Spring MVC and Thymeleaf
> Develop a web page using Spring MVC and Thymeleaf which enables creating
an Employee, and listing all employees in a tabular form
> Use the existing Employee class
> The employees should be stored only in memory
> Write an EmployeeDto class in the dto subpackage, which contains the same
fields and getters/setters as the Employee class
> Implement a JSON based REST API with the /api/employees base URI, with
endpoints capable of
> Listing all employees
> Return on employee with a given id
> Adding a new employee
> Modifying an existing employee
> Deleting an existing employee
> Listing employees with salary higher than a given value passed as query
parameter
> The employees should be stored only in memory for the RESTS API as well
> Test this REST API with Postman