Monday 7 March 2016

ThymeLeaf Tutorial Part two




ThymeLeaf with Spring Boot

  • SpringFramework is available in global, then you might wither framework Rest assured that feeling of quality manner was, Spring and the function of the sub-project of the Spring can be very wide-ranging.
  • SpringBoot can make easy Web application even if you're not familiar to Spring like me.
  • Information of SpringFramework will lot exists on the Web, but I often confused difficult, such the one is to understand that you can use any version which in the Spring beginner. So, I tried to put together on one page to make it easier to find that you have studied this time.
  • It is pasted a reference to the official site as much as possible. Also, how to find because I thought I may be seen is clue to look also I've been described as much as possible.
  • Where described because it is described in my notes feeling is rough, please forgive me. If it is helpful if you can point out, such as a mistake.

Sample application (2015/8/25 postscript)

  • Because those who looks good there was a sample, tried to make a simple application. Login logout, user registration, a simple example using the iTunesSearchAPI but I think that it would be helpful.
  • https://github.com/uzresk/springboot-example.git

The SpringBoot?

  • I feel that the setting Easy Spring = SpringBoot. Spring will be available without the troublesome setting.
  • The default setting is completed if multiplied by the pom in Maven or Gradle. The combination of recommendations dependent library is determined automatically.
  • The basic configuration of Spring is automatic. web.xml even eliminates.
  • AP server is using EmbededTomcat, the deployment will deploy the jar instead of war. (You can start it from java -jar xx.jar.)
  • If Tomcat is unpleasant is you can also use the Jetty.
  • It is not recommended JSP in the development of the screen. Thymeleaf, make use of, such as Velocity. http://docs.spring.io/spring-boot/docs/1.2.2.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-template-engines
     JSPs should be avoided if possible, there are several known limitations when using them with embedded servlet containers.
    

Premise (environment)

  • Java8
  • Maven3.0.4
  • SpringBoot1.2.1

Reference

What you want to set at the beginning

To change the package to scan the component.

  • For scan package, but by default, the class subordinate to start the SpringBoot will be scanned automatically, you can change the package that you want to scan by setting the annotation.
  • Component is the Web in my case, to create each in Batch, Entity, Repository was set annotations because I wanted to share Web, in Batch.
  • Component 
     @ComponentScan (BasePackages = "org.xxx")
    
  • JpaRepository 
     @EnableJpaRepositories (BasePackages = "org.xxx.repository")
    
  • Entity class 
     @EntityScan (BasePackages = "org.xxx.entity")
    
  • Collectively write and you will like this.
App.java
 @EnableAutoConfiguration
 @ComponentScan (BasePackages = "org.xxx")
 @EnableJpaRepositories (BasePackages = "org.xxx.repository")
 @EntityScan (BasePackages = "org.xxx.entity")
 public class App {
   ...
 }

Configuring the Log

  • To use a slf4j + logback be useful. You should put smoothly since log4j and not much different. In order to suppress sfl4j + logback is here URL it is easy to understand is.
  • Configure the settings of the pom. It plunged the Toka jcl if necessary.
     Since slf4j + logback is available by default, change of pom, you do not need.
    
  • After that place the logback.xml under resource. logback.xml Suitable. Here are the most simple example.
logback.xml
 <? xml version = "1.0" encoding = "UTF-8"?>
 <! DOCTYPE logback>
 <configuration>
     <include resource = "org / springframework / boot / logging / logback / base.xml" />
     <logger name = "com.amazonaws" level = "INFO" />
     <logger name = "org.hibernate" level = "ERROR" />
     <logger name = "org.springframework" level = "INFO" />
     <logger name = "org.thymeleaf" level = "INFO" />
 </ configuration>
  • You'll find the base.xml that import, but you can specify the output location of the file by using the system properties of java.
     -Dlogging.file = / Var / log / my.log
    
  • In addition, please refer to the reference document because some settings, such as log.path.
  • Reference: 66.1 Configure Logback for logging

Log Settings - replacement of logback.xml

  • logback usually -Dlogback.configurationFile = / foo / bar / logback.xml Tosureba but you can replace the configuration file, this system property in SpringBoot is disabled.
  • Such time will be like this.
     -Dlogging.config = / Foo / bar / logback.xml
    

The encoding of the request to UTF-8.

  • Although the setting of the Fiter was originally described, in particular setting is not required because it has become so CharacterEncodingFilter automatically is registered from Spring Boot 1.2.

Session of clustering on AWS

It shall be set at the time of development

To OFF the cache of Thymeleaf.

application.yml
 spring.thymeleaf.cache: false

Hot deploy

  1. You have to download the spring-loaded.
     https://github.com/spring-projects/spring-loaded
    
  2. When the developing in Eclipse, you set the VM arguments run configuration of SpringBoot startup.
     -javaagent: /springloaded-1.2.1.RELEASE.jar -noverify
    
  • spring loaded is still feeling that developing. Version Let's apply the latest version by checking the site to beans because up well.
  • When running in maven lists the pom as follows.
pom.xml
                 <Dependencies>
                     <Dependency>
                         <GroupId> org.springframework </ groupId>
                         <ArtifactId> springloaded </ artifactId>
                         <Version> 1.2.1.RELEASE </ version>
                     </ Dependency>
                 </ Dependencies>

Switch between profiles of the configuration file

  • In my case, local PostgreSQL in the company, AWS of PostgreSQL via SSLVPN at home (RDS). I use them in feeling that.
  • I think I want to change the setting in the Toka development, staging a production even at the time of normal development. When consensus will use the Profile.
  • In application.yml, separated by ---. profiles: lists the profile name to.
application.yml
 spring:
     profiles: dev-aws
     thymeleaf:
         cache: false
     datasource:
         url: jdbc: postgresql: // foobar: 5432 / cmp
         username: foo
         password: bar
     jpa:
         database-platform: org.hibernate.dialect.PostgreSQLDialect
 ---
 spring:
     profiles: production
     thymeleaf:
         cache: true
     datasource:
         url: jdbc: postgresql: // hogehoge: 5432 / cmp
         username: foo
         password: bar
     jpa:
         database-platform: org.hibernate.dialect.PostgreSQLDialect
  • After that you start the SpringBoot wrote a profile name in the VM argument (-Dspring.profiles.active).
command.sh
 java -Dspring.profiles.active = production -jar /home/ec2-user/XXX-0.0.1-SNAPSHOT.jar &

Implementation of screen system

How to set

  • Edit the POM, I'll to be able to use spring mvc and thymeleaf.
pom.xml
         <Dependency>
             <GroupId> org.springframework.boot </ groupId>
             <ArtifactId> spring-boot-starter-web </ artifactId>
         </ Dependency>
         <Dependency>
             <GroupId> org.springframework.boot </ groupId>
             <ArtifactId> spring-boot-starter-thymeleaf </ artifactId>
         </ Dependency>

To display the value

controller.java
 . model addAttribute ( "hoge", hoge);
thymeleaf.template
 <Span th: text = "$ {hoge}"> </ span>

To view the nested value

In the example below, this is necessary Getter that getBar () to foo object.
thymeleaf.template
 <Span th: text = "$ {foo.bar}"> </ span>

To format a date.

thymeleaf.template
 $ {# Dates.format ([java.util.Date object], 'yyyy / MM / dd')}

I want to display the objects in the List.

controller.java
 List <Image> images = new ArrayList <Image> ();
 . model addAttribute ( "images", images);
thymeleaf.template
 <Tr th: each = "image: $ {images}">
   <Td th: text = "$ {image.name}"> test1 </ td>
   <Td th: text = "$ {image.description}"> test1 </ td>
   <Td th: text = "$ {image.imageId}"> test1 </ td>
   <Td th: text = "$ {image.state}"> test1 </ td>
   <Td th: text = "$ {image.architecture}"> test1 </ td>
   <Td th: text = "$ {image.imageType}"> test1 </ td>
 </ Tr>

I want to display the objects in the Map.

  • This section describes using the example to make the year of the pull-down. In the Map 2014: If you have entered the 2014 and implemented as follows. Such as get and keySet can be used as it is.
thymeleaf.template
 <Select th: field = "* {year}" class = "selectpicker" data-width = "75px">
   <Option th: each = "key: $ {years.keySet ()}"
           th: value = "$ {key}"
           th: text = "$ {years.get (key)}"> pulldown </ option>
 </ Select>

To control the display non-display of the button in the presence or absence of a key in the Session.

  • There is an implicit object as JSP even thymeleaf. To view the "Cancel" link only if the key that foo is present on the session will be implemented as follows.
thymeleaf.template
 <a th:if="${session.containsKey('foo')}" th:href="@{/hoge}">
     <Button type = "button" class = "btn btn-danger"> Cancel </ button>
 </a>

You want to receive, I want to send a parameter

  • Send GET parameters.
thymeleaf.template
 <a th:href="@{/foo/bar(hoge=${hoge},fuga=true)}">
     <Button type = "button" class = "btn btn-success"> button name </ button>
 </a> 
  • Receive a GET parameter in the Controller.
Controller.java
 @RequestMapping (Value = "/ foo / bar", method = RequestMethod. GET)
 String images (@RequestParam String hoge,
               @RequestParam String fuga) {

Use the Form perform the acquisition of the value (POST)

  • In AController leave declare the corresponding Form, and set the initial value.
  • @ModelAttribute Declared method in will be called automatically at runtime. (The name of the method in any, AttoModelAttribute whether marked with is important.))
AController.java
 @ModelAttribute
 HogeForm setUpForm () {
     return new HogeForm ();
 }

 @RequestMapping (Value = "/ hoge", method = RequestMethod. GET)
 String hoge (HogeForm form) {
   // Set the initial value
   . form setName ( 'name');
 }
thymeleaf.template
 <Form class = "form" th: action = "@ {/ hoge / confirm}" th: object = "$ {hogeForm}" method = "POST">
   <Button type = "submit" id = "submit" class = "btn btn-primary"> button name </ button>
 </ Form>
POST values ​​are entered automatically in the argument of the BController.
BController.java
 @RequestMapping (. Value = "/ hoge / confirm", method = RequestMethod POST) String hogeConfirm (HogeForm form) {.. System out println (. Form getName ());} 

Redirect. Deliver a value to the redirect.

  • To redirect, redirect to the prefix of the return value of the Controller: just put a.
     return "redirect: / foo / bar"
    
  • Use RedirectAttributes in to redirect pass a value. It is convenient because there is no need to set again the value to the model in the redirect destination and use it.
Controller.java
     @RequestMapping (Value = "/ to", method = RequestMethod. GET)
     String to (Model model, @RequestParam String foo,
             @RequestParam String bar,
             RedirectAttributes attributes) {
         . attributes addFlashAttribute ( "CompleteMessage", completeMessage);
                 return "redirect: / hoge";
         }

I want to implement a single-item check.

Form.java
 @Data
 @NoArgsConstructor
 public class ReserveForm implements Serializable {

     public static final long serialVersionUID = 1L;

     @NotEmpty
     private String hour;

     @NotEmpty
     private String minutes;
 }
  • In front of the argument of the Form of the method @Validated check will move by appending.
  • Result of the input check will go to BindingResult. In this example, it returns to the input screen When you made an error in the input check.
  • Please note: BindingResult does not work and will not be described in just behind the Form.
Controller.java
 @RequestMapping (Value = "reserveAMI / complete", method = RequestMethod. POST)
 String reserveAMIComplete (@Validated AwsAMIReserveForm form,
 BindingResult result, Model model) {

         // Check the input
         if (result. hasErrors ()) {
             createDropDownList (model);
             return "input";
         }
 }

@ NotNull / @ NotEmpty / AttoNotBlank difference of

  • Parameters there is no value to existence. If such is @NotEmpty make use of.
  • For more information This page has settled in.

We want to implement the correlation check.

  • Since Injection in controller, component ( @Component implement as).
  • validate the method implemented by cast to Form object.
  • The first argument is the field name of the error of rejectValue. The second argument is the message code. The third argument is the message to be displayed if it can not get the message from the message code.
  • Properties that correspond to the field name to be the first argument must be present in the Form.
Correlation check class .java
 @Component
 public class AccountValidator implements Validator {

     @Override
     public boolean supports (Class <?> clazz) {
         .. return AccountCreateForm class isAssignableFrom (clazz);
     }

     @Override
     public void validate (Object target, Errors errors) {

         AccountCreateForm form = (AccountCreateForm) target;

                 // Implement the input check
                 ...

                 // Embed the message
         errors. rejectValue ( "accountId",
                 "AccountValidator.duplicateAccountId", "message");
     }
 }

  • And Injection the Validator to Controller, and then implement the initBinder.
  • By that you add a validator to WebDataBinder, also movement correlation check at the timing of a single item check moves.
  • About way of handling is omitted because it is the same as single-item check.
controller.java
     @Autowired
     AccountValidator accountValidator;

     @InitBinder
     public void initBinder (WebDataBinder binder) {
         . binder addValidators (accountValidator);
     }

You want to display a message

  • To quote from the manual.
  • Use the # to display the message in thymeleaf.
 ! <P th: utext = "# {home.welcome}"> Welcome to our grocery store </ p>
  • With a message of argument
 <P th: utext = "# {home.welcome ($ {session.user.name})}">
   Welcome to our grocery store, Sebastian Pepper!
 </ P>

I want to change the message of the input check.

  • Create the src / main / resuorce / ValidationMessages_ja.properties.
  • To override the message ID.

I want to make the message on the server side.

  • To create a message on the server side we use in case you want to display in the log and screen. The implementation of the Controller will take an example.
  • And injection the MessageSource.
     @Autowired
     MessageSource messageSource;
  • Message key, argument. The default message is the third argument, the fourth argument to set the locale.
 messageSource.getMessage ( "messageId",
              new String [] {argument},
              "DefaultMessage", Locale.JAPAN);

I want to determine the existence of an error

  • If the error has existed want out a common message to the top of the screen. Embed the following when called.
  • If an error occurs in the sample, and displays the string attached message to the message key common.error.
thymeleaf.template
         <Div th: if = "$ {# fields.hasErrors ( 'all')}" class = "alert alert-danger">
            <P th: text = "# {common.error}"> ErrorMessage </ p>
         </ Div>

You want to display an error message next to the field

  • Embed the following next to the text. (There is no separate need to be a span)
  • The sample is a way described in the case of displaying the message stick string to it if there is an error in the field called reserveType.
thymeleaf.template
 <Span th: if = "$ {# fields.hasErrors ( 'reserveType')}" class = "text-danger" th: errors = "* {reserveType}"> Error </ span>

I want to change the style of the field at the time of error

  • The framework of the text box that caused the error would like to red. In some cases, such as to embed the following.
  • In the sample we use the twitter bootstrap. Fields have to change the class name of the form-group in the case of an error that hoge.
thymeleaf.template
       <Div class = "form-group" th: classappend = "? $ {# Fields.hasErrors ( 'hoge')} 'has-error has-feedback'">
         <Label for = "cron"> item name </ label>
         <Input type = "text" id = "hoge" name = "hoge" th: field = "* {hoge}" class = "form-control" style = "width: 75px;" />
       </ Div>

Security

Configuration

  • To implement the authentication and authorization process will use the SpringSecurity.
  • It will be available in just edit the pom. Together with springsecurity, so that you can use the functions of the springsecurity in thymeleaf.
pom.xml
         <Dependency>
             <GroupId> org.springframework.boot </ groupId>
             <ArtifactId> spring-boot-starter-security </ artifactId>
         </ Dependency>
         <Dependency>
             <GroupId> org.thymeleaf.extras </ groupId>
             <ArtifactId> thymeleaf-extras-springsecurity3 </ artifactId>
         </ Dependency>

Authentication

  • Set around the login is all to define the Configuration inherited the WebSecurityConfigurerAdapter.
  • In the following code I am doing such a thing.
  1. Authentication skip to not Once / loginForm have been authenticated by the necessary page.
  2. The login page / loginForm
  3. When the login button is pressed accountId and the password is POST to / login.
  4. Skip to When the login is successful / top.
  5. In the case of login error fly to / loginForm? Error.
  6. Logout process is / logout. After logout successful fly to / loginForm.
  • AuthenticationConfiguration has give pass to create a passwordEncoder during the authentication process.
SecurityConfig.java
 @Configuration
 @EnableWebMvcSecurity
 public class SecurityConfig extends WebSecurityConfigurerAdapter {

     @Override
     protected void configure (HttpSecurity http) throws Exception {
         http. authorizeRequests (). antMatchers ( "/ loginForm"). permitAll ()
                 .. AnyRequest () authenticated ();

         http. formLogin (). loginProcessingUrl ( "/ login"). loginPage ( "/ loginForm")
                 . FailureUrl ( "/ loginForm? Error"). DefaultSuccessUrl ( "/ top", true)
                 . UsernameParameter ( "accountid"). PasswordParameter ( "password")
                 . And ();

         http. logout ()
                 . LogoutRequestMatcher (new AntPathRequestMatcher ( "/ logout **"))
                 . LogoutSuccessUrl ( "/ loginForm");

     }

     @Configuration
     static class AuthenticationConfiguration extends
             GlobalAuthenticationConfigurerAdapter {

         @Autowired
         UserDetailsService userDetailsService;

         @Bean
         PasswordEncoder passwordEncoder () {
             return new BCryptPasswordEncoder ();
         }

         @Override
         public void init (AuthenticationManagerBuilder auth) throws Exception {
             auth. userDetailsService (userDetailsService). passwordEncoder (
                     passwordEncoder ());
         }
     }
 }

Static content you want to exclude from the scope of the authorization

         @Override
         public void configure (WebSecurity web) throws Exception {
             . Web.ignoring () antMatchers ( "/ css / **", "/ js / **", "/ fonts / **", "/ img / **");
         }

I want fill any information to the authentication information

  • But it is like to be able to use from anywhere to get the attached information attached straps to the user after the authentication process.
  1. To create an inherited container the User.
  2. To create a component that extends UserDetailService.
  • Here we return the information that attach straps to the account ID using the Repository as an acquisition after UserDetails
LoginAccountDetails.java
 public class LoginAccountDetails extends User {

     private static final long serialVersionUID = 1L;

     @Getter
     private final Account account;

     @Getter
     private final AccountInfo accountInfo;

     public LoginAccountDetails (Account account, AccountInfo accountInfo) {
         super (account. getAccountId (), account. getPassword (), AuthorityUtils
                 . CreateAuthorityList ( "USER"));
         . this account = account;
         .!? this accountInfo = accountInfo = null accountInfo: new AccountInfo ();
     }
 }

LoginAccountDetailService.java
 @Service
 public class LoginAccountDetailService implements UserDetailsService {

     @Autowired
     AccountRepository accountRepository;

     @Autowired
     AccountInfoRepository accountInfoRepository;

     @Override
     public UserDetails loadUserByUsername (String accountId)
             throws UsernameNotFoundException {
         . Account account = accountRepository findOne (accountId);
         if (account == null) {
             throw new UsernameNotFoundException ( "Account is not found");
         }
         AccountInfo accountInfo = accountInfoRepository
                 . FindOne (new AccountInfoPk (accountId));
         return new LoginAccountDetails (account, accountInfo);
     }
 }

To get the authentication information

  • To get the authentication information in the Controller is @AuthenticationPrincipal only'll give the arguments that were granted.
controller.java
     @RequestMapping (Value = "images", method = RequestMethod. GET)
     String images (@RequestParam String instanceId,
             @AuthenticationPrincipal LoginAccountDetails loginAccountDetails,
             Model model) {

Display control using a roll

  • sec: authorize = "hasRole ( 'roll name')" only to users who have the role and use will no longer be displayed that section.
layout.html
         <div id = "navbar" class = "navbar navbar-inverse" sec: authorize = "hasRole ( 'USER')">
             <div class = "container">
              ...
             </ div>
         </ div>

Session Fixation measures

  • Default session ID after logging in has been changed automatically. Correctly it will not change the session ID takes over the information of the session.
  • To change the session ID does not take over the session information is as follows.
 // Change the session ID, re-create a new session http.sessionManagement () sessionFixation () newSession ()..;

MFA using TOTP in SpringBoot, want to implement the Facebook / Twitter login

Database transactions

Set of connection

  • application.yml of HOST, and set PORT, DATABASE, USERNAME, a PASSWORD. It also set in accordance with Diarect to absorb the Database of dialect. Below is an example of PostgreSQL.
 spring:
     datasource:
         url: jdbc: postgresql: // HOST: PORT / DATABASE
         username: USERNAME
         password: PASSWORD
     jpa:
         database-platform: org.hibernate.dialect.PostgreSQLDialect

Transaction boundaries

  • You can provide a transaction boundary by annotating.
  • By default, when the non-checked exceptions (RuntimeException) does not occur does not roll back. For example, to roll back I'll set the argument to the annotation when all class that inherits from Exception has been throw.
XXXService.java
 @Component
 @Transactional (RollbackOn = Exception. Class)
 public class AwsEbsService extends ReservationService {
  ...
 }

JPA

Official document URL

The initial setting of the JPA

  • It's done postscript to POM.
pom.xml
 <Dependency>
     <GroupId> org.springframework.boot </ groupId>
     <ArtifactId> spring-boot-starter-data-jpa </ artifactId>
 </ Dependency>

CRUD to the database

  • CRUD in the PrimaryKey make → Repository make the Entity. It is complete in. All restrictions such as only then you realized by Entity annotation, Repository also turn off the interface.
  • Because in accordance with the specifications of the JPA Entity made here is available even if implementation has changed. (It works even EclipseLink is a JPA implementation of JavaEE7)
  • Examples of Entity class (using the lombok) is here. Annotations for granted I think that [here] would be helpful. (Http://Otndnld.Oracle.Co.Jp/products/ias/toplink/jpa/resources/toplink-jpa-annotations.Html )
Account.java
 @Data
 @AllArgsConstructor
 @NoArgsConstructor
 @Entity
 @Table (Name = "account")
 public class Account implements Serializable {

     private static final long serialVersionUID = 1L;

     / ** Account ID * /
     @Id
     @Column (Name = "account_id")
     private String accountId;

     / ** Password * /
     @Column (Name = "password")
     private String password;

     /** email address */
     @Column (Name = "mail")
     private String mail;

 }
Repositry.java
 @Repository
 public interface AccountRepository extends JpaRepository <Account, String> {

 }

Server Configuration

To change the start port.

  • You can change the port to start the embedded tomcat.
     server:
     port: 18080
    

To set the context path.

  • When to start the spring boot by default does not set the context path.
  • If you like the following in the context path / app is granted, it will move is granted automatically to the Prefix of RequestMapping annotation.
     server:
     contextPath: / app
    

To set the session timeout.

  • By default, the session time-out is not set. Set because there is no best regards on security. The unit is in seconds.
     server:
     session-timeout: 900
    

I want to implement a health check

pom.xml
         <Dependency>
             <GroupId> org.springframework.boot </ groupId>
             <ArtifactId> spring-boot-starter-actuator </ artifactId>
         </ Dependency>
application.yml
 management:
     contextPath: / management
     port: 8081
     security.enabled: false
  • actuator will be running in the context path that thus set to if port8081 of / management. Try hitting the URL of the health check in this state.
 http: // localhost: 8081 / management / health
 { "Status": "UP", "database": "PostgreSQL", "hello": 1}
  • It sounds good if it is determined whether or not containing the word UP from LB in that.

Start and stop script

  • Start I Well okay to cut process when you want to stop, but the thing that you want to is much multiple start-up control.
  • We have prepared a super-simple sh. Please be modified to your liking is after.
web.sh
 #! / Bin / sh

 APP_NAME = cmp-web
 BASE_DIR = / home / ec2-user / cmp
 JAR_FILE = $ BASE_DIR / cmp-web-spring-0.0.1-SNAPSHOT.jar
 LOG_CONFIG_FILE = $ BASE_DIR / logback-web.xml
 JAVA_HOME = / usr / lib / jvm / jre-1.8.0-openjdk
 PID = / home / ec2-user / cmp / cmp-web.pid
 PROFILE = production

 case "$ 1" in
   "Start")
     if [-f $ {PID}!]; then
       echo "Starting $ APP_NAME"
       $ JAVA_HOME / bin / java -Dspring.profiles.active = $ PROFILE -Dlogging.config = $ LOG_CONFIG_FILE -jar $ JAR_FILE &
       echo $!> $ PID
     else
       echo "$ APP_NAME is Running."
     fi
     ;;
   "Stop")
     echo "Stopping $ APP_NAME"
     kill `cat $ PID`
     RETVAL = $?
     if test $ RETVAL -eq 0; then
         rm -f $ PID
     fi
     ;;
   *)
     echo "Usage: cmp-web.sh {start | stop}"
     exit 1
 esac

Extra edition

I want to change the tomcat of the version to start in SpringBoot

  • Version of SpringBoot'm not want to change only minor version of tomcat want to change to what has been the response to vulnerability. If that please this article

I want to deploy in the war.

pom.xml
 <Packaging> jar </ packaging>
  • The class to start the SpringBoot to inherit SpringBootServletInitializer, to implement configure.
App.java
 public class App extends SpringBootServletInitializer {

     private static Log logger = new Log (. App class);

     public static void main (String [] args) throws Exception {
         . ApplicationContext ctx = SpringApplication run (. App class, args);

         . String [] beanNames = ctx getBeanDefinitionNames ();
         . Arrays sort (beanNames);
         for (String beanName: beanNames) {
             . logger info (beanName);
         }
     }

     @Override
     protected SpringApplicationBuilder configure (
             SpringApplicationBuilder application) {

         . return application sources (. App class);
     }

 }
  • And the scope of the starter-tomcat to provided.
         <Dependency>
             <GroupId> org.springframework.boot </ groupId>
             <ArtifactId> spring-boot-starter-tomcat </ artifactId>
             <Scope> provided </ scope>
         </ Dependency>
  • This should work just fine but was adding the two steps in my case. 1. Add a set of warplugin, even without the web.xml leave so as not to error.
             <Plugin>
                 <ArtifactId> maven-war-plugin </ artifactId>
                 <Version> 2.4 </ version>
                 <Configuration>
                     <FailOnMissingWebXml> false </ failOnMissingWebXml>
                 </ Configuration>
             </ Plugin>
2. If you are using a spring-boot-starter-actuator is commented out.

I want to find something that can be set in SpringBoot.

  • Configuration is done in application.properties or application.yml just below the class path.
  • It is your choice about which one to use. (Personally, I feel may be easy to see better of YAML)
  • Not described in this cheat sheet, about things that can be set SpringBoot Common application properties will called the google from referring to.

  •  
If logback + slf4j bother <dependency> Although you can use from the start without having to define the?
The encoding of the request to UTF-8.
Automatically, from spring Boot 1.2 CharacterEncodingFilter because are registered, I think that it is unnecessary setting.

Here Is some Cheat Sheat
Variable Injection
${today}
Set any attribute value
th:attr="action=@{/blah}"
I18n Message#{home.welcome}Iteration: each
<tr th:each="prod : ${prods}">
 <td th:text="${prod.name}">Onions</td>
</tr>
I18n Message with Parameter
#{home.welcome(${session.user.name})}
Iteration status object
<tr th:each="prod,i : ${prods}" th:class="${i.odd}? 'odd'">
Object  Selection
th:object="${session.user}"
Unescaped HTML Textth:utext
Object Subselection *{name}Conditional
th:if="${actor.isUser()}"
th:unless="${actor.isAnon()}"
Urls
Page relative @{some/page}
Context relative @{/some/page}
Server relative @{~/othercontext/some/page}
Protocol relative @{//code.jquery.com}
Switch Statment
<div th:switch="${user.role}">
 <p th:case="'admin'">User is an administrator</p>
 <p th:case="#{roles.manager}">User is a manager</p>
</div>

Literals
'Literal string!'
1234 + 5
false || true
null
Inlining text/javascript
<body th:inline="text">
 <p>Hello, [[${session.user.name}]]!</p>
</body>
<script type="text/javascript" th:inline="javascript">
 var i = /*[[${i}]]*/
</script>
Concatenation
th:text="'The name of the user is ' + ${user.name}"
Define Template Fragment
<div th:fragment="copy">
Arithmetic
+, -, *, / (div), % (mod)
Include Template Fragment
 <div th:include="footer :: copy"></div>
 <div th:replace="footer :: copy"></div>
Comparators
gt (>)
lt (<)
ge (>=)
le (<=)
not (!)
eq (==)
neq/ne (!=)
Template Fragment Variables
<div th:fragment="frag (onevar,twovar)">
 <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>
<div th:include="::frag (${value1},${value2})">...</div>
<div th:include="::frag (onevar=${value1},twovar=${value2})">...</div>
Ternary Operator
${row.even}? 'even' : 'odd'
Assertion
<div th:assert="${onevar},(${twovar} != 43)">...</div>
Elvis (Default) Operator
${age}?: '(no age specified)'
Remove content at runtime
<tbody th:remove="all-but-first">
Preprocessing
${__#{article.text('textVar')}__}
Thymeleaf Comment
<!--/* This code will be removed at thymeleaf parsing time! */-->
Attribute Appending
th:[attr]append
Non-outputting element
<th:block th:each="user : ${users}">
  <td colspan="2" th:text="${user.address}">...</td>
 </th:block>
Local Variable
th:with="value='blah'"
Boolean Comparison
th:if="${a} and ${b or c}"
Don't say thankyou please :P
here some more ...........

Basic Expression Objects

  • #ctx: the context object.
  • #vars: the context variables.
  • #locale: the context locale.
  • #httpServletRequest: (only in Web Contexts) theHttpServletRequest object.
  • #httpSession: (only in Web Contexts) the HttpSession object.

Expression Utility Objects

  • #dates: utility methods forjava.util.Date objects: formatting, component extraction, etc.
  • #calendars: analogous to #dates, but for java.util.Calendarobjects.
  • #numbers: utility methods for formatting numeric objects.
  • #strings: utility methods for Stringobjects: contains, startsWith, prepending/appending, etc.
  • #objects: utility methods for objects in general.
  • #bools: utility methods for boolean evaluation.
  • #arrays: utility methods for arrays.
  • #lists: utility methods for lists.
  • #sets: utility methods for sets.
  • #maps: utility methods for maps.
  • #aggregates: utility methods for creating aggregates on arrays or collections.
  • #messages: utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
  • #ids: utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

Iteration Status Properties

  • The current iteration index, starting with 0. This is the index property.
  • The current iteration index, starting with 1. This is the count property.
  • The total amount of elements in the iterated variable. This is the sizeproperty.
  • The iter variable for each iteration. This is the current property.
  • Whether the current iteration is even or odd. These are the even/oddboolean properties.
  • Whether the current iteration is the first one. This is the first boolean property.
  • Whether the current iteration is the last one. This is the last boolean property.

th:remove Options

  • all: Remove both the containing tag and all its children.
  • body: Do not remove the containing tag, but remove all its children.
  • tag: Remove the containing tag, but do not remove its children.
  • all-but-first: Remove all children of the containing tag except the first one.
  • none : Do nothing. This value is useful for dynamic evaluation.