Developing Web projects using spring boot

Source: Internet
Author: User
Tags script tag

In the previous two blogs we briefly introduced the Spring Boot project creation, and also with small partners to DIY a spring boot auto-configuration feature, then these things ultimately will return to the web to reflect its greater value, so, Today we'll look at how to use spring boot to develop a Web project. Of course, if the small partner is not familiar with spring boot, you can refer to these two blog posts first:

1. Initial knowledge of Spring boot framework
2. Initial knowledge of Spring boot framework (ii) DIY a spring boot auto-configuration

Spring Boot provides spring-boot-starter-web to support web development, and Spring-boot-starter-web provides us with embedded Tomcat and SPRINGMVC dependencies that are convenient to use. In addition, we use the template engine here, we do the web development of the optional template engine is quite a lot, here I mainly use thymeleaf as a template engine, in fact, Spring boot provides a large number of template engines, including Freemarker, Groovy, Thymeleaf, velocity and mustache, it is recommended to use Thymeleaf in so many offers. Thymeleaf in the process of using the Thymeleafautoconfiguration class to the integration of the required beans are automatically configured through thymeleafproperties to configure the thymeleaf, including the prefix suffix, etc. We can view thymeleafproperties a section of source code:

@ConfigurationProperties ("Spring.thymeleaf")PublicClassthymeleafproperties {PrivateStaticFinal Charset default_encoding = Charset.forname ("UTF-8");PrivateStaticFinal MimeType Default_content_type = mimetype.valueof ("Text/html");Publicstatic final String default_prefix =  "classpath:/templates/"; public static final String Default_suffix =  ". html"; private boolean checktemplate =  True private boolean checktemplatelocation = true; private String prefix =  "classpath:/templates/"; private String suffix = ". html "; private String mode =  "HTML5"; .......}    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

OK, from this section of the source code we can see the default page suffix named. html, prefixed with classpath:/templates/, in fact, we need to put the HTML page in the Resources folder under the Templates folder. At the same time we see how to modify this configuration, in the Application.properties file with Spring.thymeleaf as the prefix to configure the related properties.
About Thymeleaf If the little friends don't know yet, look at the information I found online thymeleaf the latest version of the Chinese document. OK, these are ready for work. Now let's start with the creation of the project.

Create Project

Note that when you create it, you choose Thymeleaf as a dependency, so that successful project creation will automatically include Spring-boot-starter-web, such as:

Create JavaBean

I'm going to pass the data from the backstage to the foreground page, the carrier of the data is this JavaBean, as follows:

PublicClassperson {private String name;Private Integer age;Publicperson () {super ();} public person (String name, Integer age) { super (); this.name = name; this.age = Age;} public String getname () {return Name } public void setName (String name) { this.name = name;} public Integer getage () {return Age ; } public void setAge (Integer age) { Span class= "Hljs-keyword" >this.age = age; }} 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
Background data construction

Add the following code to the entry class, from the background to the foreground page to return two data, a single Person object, and a People object is a list collection, the collection of 3 person objects, then we will directly display the two data on the HTML page, the code is as follows:

@RequestMapping ("/")Public Stringindex (model model) {Person single = new person (" AA ", 11); list<person> people = new arraylist<> (); person P1 = new person ( "Zhangsan",  11); person P2 = new person ( "Lisi", 22); Person p3 = new person ( "Wangwu", 33) ; People.add (p1); People.add (p2); People.add (p3); Model.addattribute ( "Singleperson", single); Model.addattribute (  "people", people); return  "index";}        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

The code here is very simple, do not need me to say more, is to return to the front page two objects, a singleperson, a people, in addition, our front page is called index.html.

Introduction of related static files

Here I use the bootstrap and jquery two libraries, of course this is not necessary, just to let us show the effect more beautiful, static files we have to put in the Src/main/resources/static directory.

1.Bootstrap Downloads

2.jQuery Downloads
After placing the directory as follows:

Front Desk Display page

Just now the small partners have seen, by default, the foreground page to be placed in the Src/main/resources/templates directory, so, we in the directory under the new file is called Index.html, as follows:

<Htmllang="EN"Xmlns:th="Http://www.thymeleaf.org" ><Head><Metacharset="UTF-8"/><title>test20</Title><Linkth:href="@{bootstrap/css/bootstrap.min.css}"Rel="Stylesheet"/><Linkth:href="@{bootstrap/css/bootstrap-theme.min.css}"Rel="Stylesheet"/></Head><Body><Divclass="Panel Panel-primary" ><Divclass="Panel-heading" ><H3class="Panel-title" > Access model</H3></Div><Divclass="Panel-body" ><Spanth:text="${singleperson.name}" ></Span></Div></Div><Divth:if="${not #lists. IsEmpty (People)}" ><Divclass="Panel Panel-primary" ><Divclass="Panel-heading" ><H3class="Panel-title" > List</H3></Div><Divclass="Panel-body" ><Ulclass="List-group" ><Liclass="List-group-item"Th:each="Person:${people}" ><Spanth:text="${person.name}" ></Span><Spanth:text="${person.age}" ></Span><buttonclass="BTN"th:onclick="' GetName (\ ' +${person.name}+ ' \ '); '" > Get a name</Button></Li></Ul></Div></Div></Div><ScriptTh:src="@{jquery-3.1.1.js}"Type="Text/javascript" ></Script><ScriptTh:src="@{bootstrap/js/bootstrap.min.js}"type= "Text/javascript" ></script>< Script th:inline= "JavaScript" >  var single = [[${singleperson}]]; Console.log (single.name+< Span class= "hljs-string" > "/" +single.age); function getName</script></ body></HTML>    
      1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • Ten
    • one
    • 2
    • (
    • )
    • +
    • +
    • /
    • 0
    • +
    • all
    • +
    • +
    • +
    • -
    • 29
    • +
    • +
    • all
    • +
    • +
    • PNS
    • up
    • i>39
    • (
    • )
    • +

About this section of the HTML file I briefly introduce, first by xmlns:th="http://www.thymeleaf.org" importing the namespace, at a later time, because the HTML itself is a static view, when using the relevant attributes of the TH: prefix can make it into a dynamic view. th:href="@{bootstrap/css/bootstrap.min.css}"represents a reference to a Web static resource. OK, this is the head part. The body part is divided into two chunks, the first one showing my individual person object, and the second part showing the man object in the list collection. div style This has nothing to say, according to Bootstrap's official website written on the line, th:text="${singlePerson.name}" indicating access to the model in the Singleperson Name property, to th:if="${not #lists.isEmpty(people)}" determine whether the people collection in the model is empty, th:each="person:${people}" Represents the traversal of elements in people, which is about the same as in Java, where the person represents an iterative element. th:onclick="‘getName(\‘‘+${person.name}+‘\‘);‘"represents the addition of a click event, and the Click event is handled by JavaScript. th:inline="javascript"This can be added to the script tag by [[${singlePerson}]] accessing the properties in the model.

After that, we can run our own project and then access it in the browser, with the following results:

Clicking the button also allows you to see the log output in the browser console:

ok,perfect!

Tomcat-related configuration

There are few special configurations, most of which use the default configuration provided by Springboot. Sometimes we may need to have some custom configuration, such as the configuration of Tomcat, very simple, and the previous blog said the basic consistent, there are two different configuration methods:

Configuring in Application.properties

Configure directly in the Application.properties, as follows:

server.port=8081#配置服务器端口,默认为8080server.session-timeout=1000000#用户回话session过期时间,以秒为单位server.context-path=/index#配置访问路径,默认为/server.tomcat.uri-encoding=UTF-8#配置Tomcat编码,默认为UTF-8server.tomcat.compression=on#Tomcat是否开启压缩,默认为关闭
    • 1
    • 2
    • 3
    • 4
    • 5
Configuring in Code
@Componentpublic class CustomServletContainer implements EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(8080); container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/404.html")); container.setSessionTimeout(10, TimeUnit.MINUTES); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

Custom class implementations
Embeddedservletcontainercustomizer interface, and then set the port, set the error request page, set the session timeout time, and so on, everyone notice here the 404 pages in the Src/main/resources/static folder, With this, when I visit a nonexistent page, I jump to the 404.html page.

SPRINGMVC Related Configurations

While the spring boot default configuration can meet our project needs in many cases, we may still need a more flexible SPRINGMVC configuration at a time when we only need custom classes to inherit from Webmvcconfigureradapter. Then use the @configuration and @enablewebmvc annotations so that we completely block out the default configuration of spring boot, but under normal circumstances we may just want to Boot has a default configuration to add some configuration that is the default configuration provided by spring boot and my custom configuration coexist, this is also simple, just need to remove the @enablewebmvc annotations on the line. The following code:

@Configuration//@EnableWebMvc//无需使用该注解,否则会覆盖掉SpringBoot的默认配置值public class WebMVCConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hello").setViewName("/hello"); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

As for the other methods in this class I will not repeat, interested in the small partners can view our previous article Springmvc common configuration.

Custom Favicon

To customize the Favicon is simple, just put your favicon.ico file in the Src/main/resources directory, rerun the project, and look at the top left corner of the browser icon will change. As follows:

This case:
This case GitHub address

Developing Web projects using spring boot

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.