Spring Boot Quick Start

Source: Internet
Author: User
Tags sublime text

To introduce you to spring boot MVC today, let's learn how to use spring boot to quickly build a simple Web application.

Environment preparation
    • A hand-called text editor (such as Vim, Emacs, Sublime text) or IDE (Eclipse, Idea Intellij)
    • Java environment (JDK 1.7 or later)
    • Maven 3.0+ (Eclipse and Idea IntelliJ built-in, if you use the IDE and do not use command-line tools can not install
One of the simplest web apps

Using the Spring boot framework can greatly accelerate the development of Web applications, first in the MAVEN project Dependencies spring-boot-starter-web :


<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelversion>4.0.0 </modelVersion> <groupId>com.tianmaying</groupId> <artifactid>spring-web-demo</ artifactid> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name> Spring-web-demo</name> <description>demo Project forSpring webmvc</description> <parent> <groupId>org.springframework.boot</groupId> <artif Actid>spring-boot-starter-parent</artifactid> <version>1.2.5.RELEASE</version> < relativepath/> </parent> <properties> <project.build.sourceencoding>utf-8</ Project.build.sourceencoding> <java.version>1.8</java.version> </properties> < dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactid&gt ;spring-boot-starter-web</artifactid> </dependency> </dependencies> <build> <plugins&gt      ; <plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-maven-p lugin</artifactid> </plugin> </plugins> </build></project>

Next Create src/main/java/Application.java :

1 Importorg.springframework.boot.SpringApplication;2 Importorg.springframework.boot.autoconfigure.SpringBootApplication;3 Importorg.springframework.web.bind.annotation.RequestMapping;4 ImportOrg.springframework.web.bind.annotation.RestController;5 6 @SpringBootApplication7 @RestController8  Public classApplication {9 Ten@RequestMapping ("/") One      PublicString Greeting () { A         return"Hello world!"; -     } -  the      Public Static voidMain (string[] args) { -Springapplication.run (Application.class, args); -     } -}

Run app: mvn spring-boot:run or run Main () method in the IDE, Access http://localhost:8080 in the browser, Hello world! appears on the page. With just more than 10 lines of Java code and a Hello World app running correctly, what exactly does this code do? We are from the entrance of the program Springapplication.run (Application.class, args); Start Analysis:

    1. SpringApplicationIs the class that describes the spring application in the Spring boot framework, and its run() methods create a Spring application context (application context). On the other hand it scans for dependencies on the currently applied classpath, such as found in this example spring-webmvc ( spring-boot-starter-web introduced by delivery) in the classpath, and spring boot will determine that this is a Web application, and launches an inline servlet container (which is Tomcat by default) to handle HTTP requests.

    2. The Spring WEBMVC Framework distributes the HTTP requests received in the Servlet container to the corresponding class for processing according to the path @Controller , which @RestController is a special kind of return value that is @Controller returned directly to the browser as the body part of the HTTP response.

    3. @RequestMappingThe annotations indicate that the method handles HTTP requests for those URLs, which is what we often call URL routing (routing), and the requested distribution work is done in spring. For example, the root path in the code above is http://localhost:8080/ routed to the greeting() method for processing. If accessed http://localhost:8080/hello , an error occurs 404 Not Found because we have not written any method to process the /hello request.

Use @ControllerImplementing URL Routing

Modern Web applications often include many pages, and different pages also correspond to different URLs. For different URLs, it is often necessary to process different methods and return different content.

Match multiple URLs
@RestController  Public class Application {    @RequestMapping ("/")    public  String Index () {          return "Index page";    }    @RequestMapping ("/hello")    public  String Hello () {        return "Hello world!" ;    }}

@RequestMappingYou can annotate a @Controller class:

@RestController @requestmapping ("/classpath")  Public class Application {    @RequestMapping ("/methodpath")    public  String method () {         return "Mapping URL is/classpath/methodpath";    }}

methodThe URL that the method matches is /classPath/methodPath" .


You can define multiple @Controller ways to spread the processing of different URLs in different classes

The variable--pathvariable in the URL

URLs in web apps are usually not immutable, for example, two different users ' profiles for Weibo correspond to two different URLs: http://weibo.com/user1 http://weibo.com/user2 . It is impossible for each user to write an @RequestMapping annotated method to process their requests, Spring MVC provides a mechanism to handle this situation:

@RequestMapping ("/users/{username}") public String userprofile (@PathVariable ("username") String username) {    return String.Format ("User%s", username);} @RequestMapping ("/posts/{id}")publicint  ID) {    return String.Format ("Post%d", id);}

In the above example, the variables in the URL can be {variableName} represented, and in the parameters of the method is added @PathVariable("variableName") , then when the request is forwarded to the method processing, the corresponding URL of the variable will be automatically assigned to the @PathVariable annotated parameters (can automatically be assigned according to the parameter type, such as the above example int).

Support for HTTP methods

For HTTP requests In addition to their URLs, you need to be aware of its methods. For example, we access a page in the browser is usually a Get method, and the form submission is generally the POST method. @ControllerIt is also necessary to differentiate between the following methods:

@RequestMapping (value = "/login", method = requestmethod.get) public String loginget () {     return "Login page"= "/login", method = requestmethod.post) Public String Loginpost () {    return "Login Post Request";}
Template rendering

In the previous methods of all @RequestMapping annotations, the return value string is passed directly to the browser side and displayed to the user. But in order to be able to render more rich and beautiful pages, we need to return the HTML code to the browser, the browser to render the page, display.

A straightforward approach is to return the HTML code directly in the method of processing the request, but the problem is that a complex page HTML code is often very complex, and embedded in Java code is very detrimental to maintenance. A better approach is to write the HTML code of the page in the template file, rendering it back to the user. To be able to render the template, it needs to be @RestController changed to @Controller :

Import Org.springframework.ui.Model; @Controller  Public class Hellocontroller {    @RequestMapping ("/hello/{name}")    public String Hello (@ Pathvariable ("name") String name, model model) {        Model.addattribute ("name", name);         return "Hello"    }}

In the above example, the return value "hello" does not directly return the string to the browser, but instead looks for a template with the name to hello render, and we use the Thymeleaf template engine for template rendering, which requires the introduction of dependencies:

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId> Spring-boot-starter-thymeleaf</artifactid></dependency>

Next you need to src/main/resources/templates/ add a template file under the Default Template folder directory hello.html :

<! DOCTYPE html>

th:text="‘Hello, ‘ + ${name} + ‘!‘"@Controllerthat is, the property that we added to the method before is Model name rendered and placed <p> in the label (because th:text it is a <p> property of the tag). For more usage of template rendering, please refer to thymeleaf official documentation.

Working with static files

The browser page uses HTML as the description language, so it's bound to be out of CSS and JavaScript. In order to enable the browser to load similar /css/style.css , /js/main.js etc resources correctly, by default we only need to src/main/resources/static add css/style.css and file in the directory js/main.js , Spring MVC can automatically publish them, through access /css/style.css , /js/main.js These resources can also be loaded correctly.

Spring Boot Quick Start

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.