Friday, 6 May 2016

ThymeLeaf Tutorial Part 3 (Cheat sheet)

first

  • 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 as much as possible the official site. Also, how to find because I thought that it is good knowing the 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.

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 for the 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
AttoEnableAutoConfiguration 
AttoComponentScan ( BasePackages  =  "Org.Xxx" ) 
AttoEnableJpaRepositories ( BasePackages  =  "Org.Xxx.Repository" ) 
AttoEntityScan ( 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.
  • Configure the settings of the pom.It plunged the Toka jcl if necessary.
    Since slf4j + logback is available by default, change of pom is not required.
    
  • 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 necessary 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
AttoRequestMapping ( Value  =  "/ foo / Bar" ,  Method  =  RequestMethod . GET ) 
String  Images ( AttoRequestParam  String  hoge , 
              AttoRequestParam  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
AttoModelAttribute 
HogeForm  SetUpForm ()  { 
    Return  New  HogeForm (); 
}

AttoRequestMapping ( 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
AttoRequestMapping ( 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
    AttoRequestMapping ( Value  =  "/ To" ,  Method  =  RequestMethod . GET ) 
    String  To ( Model  Model ,  AttoRequestParam  String  foo , 
            AttoRequestParam  String  Bar , 
            RedirectAttributes  Attributes )  { 
        Attributes . AddFlashAttribute ( "CompleteMessage" ,  CompleteMessage ); 
                Return  "Redirect : / hoge " ; 
        }

I want to implement a single-item check.

Form.java
AttoData 
AttoNoArgsConstructor 
Public  Class  ReserveForm  Implements  Serializable  {

    Public  Static  Final  Long  serialVersionUID  =  1L ;

    AttoNotEmpty 
    Private  String  Hour ;

    AttoNotEmpty 
    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
AttoRequestMapping ( Value  =  "ReserveAMI / Complete" ,  Method  =  RequestMethod . POST ) 
String  ReserveAMIComplete ( AttoValidated  AwsAMIReserveForm  Form , 
BindingResult  Result ,  Model  Model )  {

        // Input check 
        If  ( Result . HasErrors ())  { 
            CreateDropDownList ( Model ); 
            Return  "Input" ; 
        } 
}

NotNull Atto / Atto 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 the controller, component ( AttoComponent 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 that becomes the first argument must be present in the Form.
Correlation check class .java
AttoComponent 
Public  Class  AccountValidator  Implements  Validator  {

    AttoOverride 
    Public  Boolean  Supports ( Class <?>  Clazz )  { 
        Return  AccountCreateForm . Class . IsAssignableFrom ( clazz ); 
    }

    AttoOverride 
    Public  Void  Validate ( Object  Target ,  Errors  Errors )  {

        AccountCreateForm  Form  =  ( AccountCreateForm )  Target ;

                // The input check implementation 
                ...

                // Embed the message 
        Errors . RejectValue ( "accountId" , 
                "AccountValidator.DuplicateAccountId" ,  "message" ); 
    } 
}

  • And Injection the Validator to the 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
    AttoAutowired 
    AccountValidator  AccountValidator ;

    AttoInitBinder 
    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 a message attached 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 raised passing making passwordEncoder during the authentication process.
SecurityConfig.java
AttoConfiguration 
AttoEnableWebMvcSecurity 
Public  Class  SecurityConfig  Extends  WebSecurityConfigurerAdapter  {

    AttoOverride 
    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" );

    }

    AttoConfiguration 
    Static  Class  EiyuthenticationConfiguration  Extends 
            JieruobieierueiyutietchiienuticationConfigurerAdapter  {

        AttoAutowired 
        UserDetailsService  UserDetailsService ;

        AttoBean 
        PasswordEncoder  PasswordEncoder ()  { 
            Return  New  BCryptPasswordEncoder (); 
        }

        AttoOverride 
        Public  Void  Init ( EiyutihenticationManagerBuilder  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 ;

    AttoGetter 
    Private  Final  Account  Account ;

    AttoGetter 
    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
AttoService 
Public  Class  LoginAccountDetailService  Implements  UserDetailsService  {

    AttoAutowired 
    AccountRepository  AccountRepository ;

    AttoAutowired 
    AccountInfoRepository  AccountInfoRepository ;

    AttoOverride 
    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
    AttoRequestMapping ( Value  =  "Images" ,  Method  =  RequestMethod . GET ) 
    String  Images ( AttoRequestParam  String  instanceId , 
            AttoAuthenticationPrincipal  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
AttoComponent 
AttoTransactional ( 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
AttoData 
AttoAllArgsConstructor 
AttoNoArgsConstructor 
AttoEntity 
AttoTable ( Name = "Account" ) 
Public  Class  Account  Implements  Serializable  {

    Private  Static  Final  Long  serialVersionUID  =  1L ;

    / ** Account * ID / 
    AttoId 
    AttoColumn ( Name  =  "Account_id" ) 
    Private  String  accountId ;

    / ** Password * / 
    AttoColumn ( Name  =  "Password" ) 
    Private  String  Password ;

    / ** E-mail address * / 
    AttoColumn ( Name  =  "Mail" ) 
    Private  String  Mail ;

}
Repositry.java
AttoRepository 
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 set in this way to and 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  EsupiaruingBootServletInitializer  {

    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 ); 
        } 
    }

    AttoOverride 
    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.