Tuesday, September 22, 2020

Thymeleaf Getting started with the Standard dialects in 5 minutes

 

    Thymeleaf  

Getting started with the Standard dialects in 5 minutes

This guide will take you through some of the most important concepts you need to know to understand a Thymeleaf template written in the Standard or SpringStandard dialects. It is not a substitute for the tutorials – which are much more comprehensive – but it will teach you enough for getting the feel of the technology.

Standard dialects?

Thymeleaf is very, very extensible, and it allows you to define your own sets of template attributes (or even tags) with the names you want, evaluating the expressions you want in the syntax you want and applying the logic you want. It’s more like a template engine framework.

Out of the box, nevertheless, it comes with something called the standard dialects (named Standard and SpringStandard) that define a set of features which should be more than enough for most scenarios. You can identify when these standard dialects are being used in a template because it will contain attributes starting with the th prefix, like <span th:text="...">.

Note that the Standard and the SpringStandard dialects are almost identical, except that SpringStandard includes specific features for integrating into Spring MVC applications (like, for example, using Spring Expression Language for expression evaluation instead of OGNL).

Also note we usually refer to features in the Standard dialects when we talk about Thymeleaf without being more specific.

Standard Expression syntax

Most Thymeleaf attributes allow their values to be set as or containing expressions, which we will call Standard Expressions because of the dialects they are used in. These can be of five types:

  • ${...} : Variable expressions.
  • *{...} : Selection expressions.
  • #{...} : Message (i18n) expressions.
  • @{...} : Link (URL) expressions.
  • ~{...} : Fragment expressions.

Variable expressions

Variable expressions are OGNL expressions –or Spring EL if you’re integrating Thymeleaf with Spring– executed on the context variables — also called model attributes in Spring jargon. They look like this:

${session.user.name}

And you will find them as attribute values or as a part of them, depending on the attribute:

<span th:text="${book.author.name}">

The expression above is equivalent (both in OGNL and SpringEL) to:

((Book)context.getVariable("book")).getAuthor().getName()

But we can find variable expressions in scenarios which not only involve output, but more complex processing like conditionalsiteration

<li th:each="book : ${books}">

Here ${books} selects the variable called books from the context, and evaluates it as an iterable to be used at a th:each loop.

Selection expressions

Selection expressions are just like variable expressions, except they will be executed on a previously selected object instead of the whole context variables map. They look like this:

*{customer.name}

The object they act on is specified by a th:object attribute:

<div th:object="${book}">
  ...
  <span th:text="*{title}">...</span>
  ...
</div>

So that would be equivalent to:

{
  // th:object="${book}"
  final Book selection = (Book) context.getVariable("book");
  // th:text="*{title}"
  output(selection.getTitle());
}

Message (i18n) expressions

Message expressions (often called text externalizationinternationalization or i18n) allows us to retrieve locale-specific messages from external sources (.properties files), referencing them by a key and (optionally) applying a set of parameters.

In Spring applications, this will automatically integrate with Spring’s MessageSource mechanism.

#{main.title}
#{message.entrycreated(${entryId})}

You can find them in templates like:

<table>
  ...
  <th th:text="#{header.address.city}">...</th>
  <th th:text="#{header.address.country}">...</th>
  ...
</table>

Note you can use variable expressions inside message expressions if you want the message key to be determined by the value of a context variable, or you want to specify variables as parameters:

#{${config.adminWelcomeKey}(${session.user.name})}

Fragment expressions

Fragment expressions are an easy way to represent fragments of markup and move them around templates. Thanks to these expressions, fragments can be replicated, passed to other templates as arguments, and so on.

The most common use is for fragment insertion using th:insert or th:replace:

<div th:insert="~{commons :: main}">...</div>

But they can be used anywhere, just as any other variable:

<div th:with="frag=~{footer :: #main/text()}">
  <p th:insert="${frag}">
</div>

Fragment expressions can have arguments:

Literals and operations

A good bunch of types of literals and operations are available:

  • Literals:
    • Text literals: 'one text''Another one!',…
    • Number literals: 0343.012.3,…
    • Boolean literals: truefalse
    • Null literal: null
    • Literal tokens: onesometextmain,…
  • Text operations:
    • String concatenation: +
    • Literal substitutions: |The name is ${name}|
  • Arithmetic operations:
    • Binary operators: +-*/%
    • Minus sign (unary operator): -
  • Boolean operations:
    • Binary operators: andor
    • Boolean negation (unary operator): !not
  • Comparisons and equality:
    • Comparators: ><>=<= (gtltgele)
    • Equality operators: ==!= (eqne)
  • Conditional operators:
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)

Expression preprocessing

One last thing to know about expressions is there is something called expression preprocessing, specified between __, which looks like this:

#{selection.__${sel.code}__}

What we are seeing there is a variable expression (${sel.code}) that will be executed first and which result – let’s say, “ALL” – will be used as a part of the real expression to be executed afterwards, in this case an internationalization one (which would look for the message with key selection.ALL).

Some basic attributes

Let’s have a look at a couple of the most basic attributes in the Standard Dialect. Starting with th:text, which just replaces the body of a tag (notice again the prototyping abilities here):

<p th:text="#{msg.welcome}">Welcome everyone!</p>

Now th:each, which repeats the element it’s in as many times as specified by the array or list returned by its expression, creating also an inner variable for the iteration element with a syntax equivalent to that of a Java foreach expression:

<li th:each="book : ${books}" th:text="${book.title}">En las Orillas del Sar</li>

Lastly, Thymeleaf includes lots of th attributes for specific XHTML and HTML5 attributes which just evaluate their expressions and set the value of these attributes to their result. Their names mimic those of the attributes which values they set:

<form th:action="@{/createOrder}">
<input type="button" th:value="#{form.submit}" />
<a th:href="@{/admin/users}">

Want to know more?

Then the “Using Thymeleaf” tutorial is what you’re looking for!

Saturday, September 12, 2020

Angular : Remove and Add FontAwsome

 


Remove/add Fontawesome

npm uninstall angular-font-awesome ng add @fortawesome/angular-fontawesome@0.6.0

Add Fontawesome to the project

npm install font-awesome --save // in angular.json add the style "styles": [ "node_modules/font-awesome/css/font-awesome.css", "src/styles.css" ],

Thursday, September 10, 2020

Pagination and Sorting With Spring Data JPA

 

Pagination and Sorting With Spring Data JPA

 

Pagination is very useful when we have to deal with large set of data  and we want to present it to the view layer  in smaller data sets.

 We also need to sort that data by some criteria while applying paging.

In this tutorial,

 we will explain how to implement pagination and sort using Spring Data JPA and access throgh the GET request.

Further you can use any view logic to display the data but here we will just use get api

 

Repository:

@Repository

public interface TodoJPARepository extends JpaRepository<Todo, Long>{

      List<Todo> findByUsername(String username);

      Page<Todo> findByUsername(String username, Pageable pageable);

}

 

Suppose I need the sorted and pageable data when get request is sent to below URL:

GET : http://127.0.0.1:8080/jpa/users/dinesh/todos/v2/1/3?sortField=id&sortDirection=desc

 

{

    "currentPage"1,

    "totalPages"4,

    "totalItems"10,

    "sortField""id",

    "sortDirection""asc",

    "todosList": [

        {

            "id"11010,

            "username""dinesh",

            "description""Learn Spring Boot5 D",

            "targetDate""2020-09-10T03:52:05.232+0000",

            "done"false

        },

        {

            "id"11009,

            "username""dinesh",

            "description""Learn Spring Boot4 D",

            "targetDate""2020-09-10T03:52:05.232+0000",

            "done"false

        },

        {

            "id"11008,

            "username""dinesh",

            "description""Learn Spring Boot3 D",

            "targetDate""2020-09-10T03:52:05.232+0000",

            "done"false

        }

    ]

}

 

Controller Get Method Logic:

@GetMapping("/jpa/users/{username}/todos/v2/{page}/{pagesize}")

               

 public TodoResponse getUserTodos(
                 

@PathVariable(value = "username") String username,

@PathVariable(value = "page") int page

@PathVariable(value = "pagesize") int pagesize,
@RequestParam(value = "sortField", defaultValue = "targetDate") String   sortField,

@RequestParam(value = "sortDirection", defaultValue = "ASC") String  sortDirection

 

                 {

 

                  //Response Object

                                TodoResponse todoResponse = new TodoResponse();

 

            // Sorting

            // Create Sort method based on the request parameter

 Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())                                         ?    Sort.by(sortField).ascending() : Sort.by(sortField).descending();

 

     // Create PageRequest Object and pass page and sorting parameter

                                Pageable pageable = PageRequest.of(page - 1, pagesizesort);

 

                                Page<Todo> pageofTodo = todoService.findByUsername(usernamepageable);

 

                                List<Todo> getTodosList = pageofTodo.getContent();

                                todoResponse.setCurrentPage(page);

                                todoResponse.setTotalItems(pageofTodo.getTotalElements());

                                todoResponse.setTotalPages(pageofTodo.getTotalPages());

                                todoResponse.setSortField(sortField);

                 todoResponse.setSortDirection(sortDirection.equals("asc") ? "desc" : "asc");

                                todoResponse.setTodosList(getTodosList);

 

                                // Return Response

                                return todoResponse;

 

                }

 

 

Supporting  Classes:

public class TodoResponse implements Serializable{

       private static final long serialVersionUID = 1L;

 

       private int currentPage;

       private int totalPages;

       private long totalItems;

       private String sortField;

       private String sortDirection;

       private List<Todo> todosList;

☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝

@Entity

public class Todo {

       @Id

       @GeneratedValue(strategy=GenerationType.AUTO)

       private Long id;

       private String username;

       private String description;

       private Date targetDate;

       private boolean isDone;

✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌

 

 


Sunday, August 23, 2020

Spring Boot - Internationalization working example

 

Add Internationalization in Spring Boot App

 



import java.util.Locale; 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;

import org.springframework.context.support.ResourceBundleMessageSource;

import org.springframework.web.servlet.LocaleResolver;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;

 

@SpringBootApplication

public class RestfulServicesApplication {

 

       public static void main(String[] args) {

              SpringApplication.run(RestfulServicesApplication.class, args);

       }

      

         //Add these two methods for i18n

       @Bean

       public LocaleResolver localeResolver() {

       SessionLocaleResolver localeResolver= new SessionLocaleResolver();

       localeResolver.setDefaultLocale(Locale.US);

       return localeResolver;

       }

      

      

       public ResourceBundleMessageSource messageSource() {

          ResourceBundleMessageSource messageSource= new ResourceBundleMessageSource();

          //message referes to the property file name without extention

          messageSource.setBasename("messages");

          return messageSource;

            

       }

}

 

 

 //Rest Controller class

@RestController

public class HelloWorldController {

 

       @Autowired

       MessageSource messageSource;

      


       @GetMapping(path = "/hello-world-i18n")public String 

         helloWorld(@RequestHeader(name="Accept-Language",required=false) Locale locale) {

             String msg=messageSource.getMessage("my.app.message",null, locale);

             return msg;

       }

      

 

}

 

//Define properties files

messages.properties

 

my.app.message="Hello"

 

messages_fr.properties

 

my.app.message=" Bonjour"

 

 

Call Rest API with Accept-Language Header :

 

Get : http://127.0.0.1:8080/hello-world-i18n

Header:

Accept-Language : fr

Bonjour

 

Get : http://127.0.0.1:8080/hello-world-i18n

Header:

Accept-Language : en

Hello

 

 

 

 

 

 

 

 

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > <...

Followers

Search This Blog

Popular Posts