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
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
- JpaRepository
- Entity class
- Collectively write and you will like this.
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.- After that place the logback.xml under resource. logback.xml Suitable. Here are the most simple example.
- 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.
- 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.
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
- Results Consider how to clustering the session with AWS, I tried because DynamoDB is good.
Block the default error page
- The default error page and change the settings so that it does not appear because it contains information undesirable on security.
- One way to set is to put the error.html directly under the templates directory. This error.html appears any error.
- Finer control is implemented by overriding the ErrorMvcAutoConfiguration.
- Reference: 70.2 Customize the 'Whitelabel' error page
It shall be set at the time of development
To OFF the cache of Thymeleaf.
- Thymeleaf of cache is a not after immediately reflect that change worked. You have to turn OFF the cache at the time of development.
- Reference: Http://Docs.Spring.Io/spring-boot/docs/current/reference/html/howto-hotswapping.Html#howto-reload-thymeleaf-content
Hot deploy
- You can hot deploy of the place referred to in the Seasar even SpringBoot.
- Reference: 72.6 Reload Java classes without Restarting the container
- You have to download the spring-loaded.
- When the developing in Eclipse, you set the VM arguments run configuration of SpringBoot startup.
- 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.
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.
- After that you start the SpringBoot wrote a profile name in the VM argument (-Dspring.profiles.active).
Implementation of screen system
How to set
- Edit the POM, I'll to be able to use spring mvc and thymeleaf.
To display the value
To view the nested value
In the example below, this is necessary Getter that getBar () to foo object.
To format a date.
I want to display the objects in the List.
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.
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.
You want to receive, I want to send a parameter
- Send GET parameters.
- Receive a GET parameter in the Controller.
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.))
POST values are entered automatically in the argument of the BController.
Redirect. Deliver a value to the redirect.
- To redirect, redirect to the prefix of the return value of the Controller: just put a.
- 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.
I want to implement a single-item check.
- Single item check You can accomplish it to annotate in the field of the Form.
- Annotation using the hibernate validator is an implementation of the Bean Validation.
- See below for granted can be annotated
- https://access.redhat.com/documentation/ja-JP/JBoss_Enterprise_Application_Platform/5/html-single/Hibernate_Validator_Reference_Guide/index.html#validator-defineconstraints-builtin
- 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.
@ 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.
- 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.
You want to display a message
- To quote from the manual.
- Use the # to display the message in thymeleaf.
- With a message of argument
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.
- Message key, argument. The default message is the third argument, the fourth argument to set the locale.
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.
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.
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.
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.
Authentication
- Set around the login is all to define the Configuration inherited the WebSecurityConfigurerAdapter.
- In the following code I am doing such a thing.
- Authentication skip to not Once / loginForm have been authenticated by the necessary page.
- The login page / loginForm
- When the login button is pressed accountId and the password is POST to / login.
- Skip to When the login is successful / top.
- In the case of login error fly to / loginForm? Error.
- Logout process is / logout. After logout successful fly to / loginForm.
- AuthenticationConfiguration has give pass to create a passwordEncoder during the authentication process.
Static content you want to exclude from the scope of the authorization
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.
- To create an inherited container the User.
- 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
To get the authentication information
- To get the authentication information in the Controller is @AuthenticationPrincipal only'll give the arguments that were granted.
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.
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.
MFA using TOTP in SpringBoot, want to implement the Facebook / Twitter login
- TOTP in Java (SpringBoot) (Time-based One-time Password), to achieve a twitter / facebook login
- It is mentioned also how to add authentication provider.
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.
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.
JPA
Official document URL
The initial setting of the JPA
- It's done postscript to POM.
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 )
- Repository is an interface that inherits JpaRepository. You can perform the operation of CRUD only by inheritance.
- That people who do not know well the JPA is to keep learning about the operation of a slightly different because the Repository as do Gorigori write SQL yourself read the following document.
- http://terasolunaorg.github.io/guideline/public_review/ArchitectureInDetail/DataAccessJpa.html#repository
Server Configuration
To change the start port.
- You can change the port to start the embedded tomcat.
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.
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.
I want to implement a health check
- Health check from the load balancer was making the application to make sure that you are alive is always a simple database and search engines to make a Servlet. Implementation will be unnecessary if you use the Spring-Actuator.
- Reference: Http://Docs.Spring.Io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-health
- 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.
- 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.
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.
- 74.1 Create a deployable war file there is described in. But it did not go well it just in my environment.
- And the packaging of pom to war.
- The class to start the SpringBoot to inherit SpringBootServletInitializer, to implement configure.
- And the scope of the starter-tomcat to provided.
- 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.
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.
<dependency>
Although you can use from the start without having to define the?CharacterEncodingFilter
because are registered, I think that it is unnecessary setting.Here Is some Cheat Sheat
#{home.welcome}
th:utext
*{name}
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) theHttpSession
object.Expression Utility Objects
#dates
: utility methods forjava.util.Date
objects: formatting, component extraction, etc.#calendars
: analogous to#dates
, but forjava.util.Calendar
objects.#numbers
: utility methods for formatting numeric objects.#strings
: utility methods forString
objects: 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
index
property.count
property.size
property.current
property.even/odd
boolean properties.first
boolean property.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.