Spring MVC Quick Start built on spring boot

Source: Internet
Author: User
Tags sublime text

Original address: Http://tianmaying.com/tutorial/spring-mvc-quickstart 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 using the IDE and not using command-line tools can be installed)
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 :

pom.xml

<?XML version= "1.0" encoding= "UTF-8"?><Projectxmlns= "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 for Spring WEBMVC</Description>  <Parent>    <groupId>Org.springframework.boot</groupId>    <Artifactid>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>Spring-boot-starter-web</Artifactid>    </Dependency>  </Dependencies>  <Build>    <Plugins>      <plugin>        <groupId>Org.springframework.boot</groupId>        <Artifactid>Spring-boot-maven-plugin</Artifactid>      </plugin>    </Plugins>  </Build></Project>

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

Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController, @SpringBootApplication @restcontroller Public classApplication {@RequestMapping ("/")     PublicString Greeting () {return"Hello world!"; }     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" .

Tips

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><HTMLxmlns:th= "http://www.thymeleaf.org"><Head>    <title>Getting started:serving Web Content</title>    <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /></Head><Body>    <PTh:text= "' Hello, ' + ${name} + '! '" /></Body></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 MVC Quick Start built on 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.