Spring boot entry

Let me introduce Spring Boot MVC today, let us learn how to use Spring Boot to quickly build a simple web application.

Environmental preparation

1. A hand-written text editor (such as Vim, Emacs, Sublime Text) or IDE (Eclipse, Idea Intellij)

2.Java environment (JDK 1.7 or above)

3.Maven 3.0+ (Eclipse and Idea IntelliJ built-in, if you use IDE and do not use the command line tool you can not install)

One of the simplest web applications

Using the Spring Boot framework can greatly accelerate the development of web applications, first introducing spring-boot-starter-web in the Maven project dependencies:

Pom.xml

"? Xml version=“1.0” encoding=“UTF-8”? 》

"project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=“http://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:

Import org.springframework.boot.SpringApplication;

Import org.springframework.boot.autoconfigure.SpringBootApplication;

Import org.springframework.web.bind.annotation.RequestMapping;

Import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication

@RestController

Public class Application {

@RequestMapping("/")

Public String greeting() {

Return "Hello World!";

}

Public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

Run the application: mvn spring-boot:run or run the main() method in the IDE, and visit http://localhost:8080 in the browser, Hello World! It appears on the page. Using only a dozen lines of Java code, a Hello World application can run correctly, so what exactly does this code do? We start with the program's entry SpringApplication.run(Application.class, args);

SpringApplication is a class that describes Spring applications in the Spring Boot framework. Its run() method creates a Spring Application Context. On the other hand, it scans the dependencies on the current application classpath. For example, in this example, spring-webmvc (introduced by spring-boot-starter-web pass-through) is found in the classpath, then Spring Boot will determine that this is a web application. And launch an embedded servlet container (default is Tomcat) for handling HTTP requests.

The Spring WebMvc framework will distribute the HTTP requests received in the Servlet container to the corresponding @Controller class for processing according to the path. @RestController is a special kind of @Controller, and its return value is directly returned to the browser as the Body part of the HTTP Response. .

The @RequestMapping annotation indicates that the method handles HTTP requests for those URLs, which is what we often call URL routing. The distribution of requests is done by Spring. For example, in the above code, the http://localhost:8080/root path is routed to the greeting() method for processing. If you visit http://localhost:8080/hello, a 404 Not Found error will occur because we have not written any methods to handle the /hello request.

Implement URL routing using @Controller

Modern web applications often include many pages, and different pages also correspond to different URLs. For different URLs, different methods are usually needed to process 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!";

}

}

@RequestMapping can annotate the @Controller class:

@RestController

@RequestMapping("/classPath")

Public class Application {

@RequestMapping("/methodPath")

Public String method() {

Return "mapping url is /classPath/methodPath";

}

}

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

prompt

Multiple @Controllers can be defined to spread the processing of different URLs in different classes.

The variable in the URL - PathVariable

In a web application, the URL is usually not static. For example, the personal homepages of two different users of Weibo correspond to two different URLs: http://weibo.com/user1, http://weibo.com/user2. We can't write a method that is annotated with @RequestMapping for each user to handle its request. 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}")

Public String post(@PathVariable("id") int id) {

Return String.format("post %d", id);

}

In the above example, the variable in the URL can be represented by {variableName}, and @PathVariable("variableName") is added to the method parameter, then the variable in the corresponding URL is processed when the request is forwarded to the method. It will be automatically assigned to the parameter annotated by @PathVariable (which can be automatically assigned based on the parameter type, such as the int in the previous example).

Support HTTP method

For HTTP requests, in addition to their URLs, you need to pay attention to its methods (Method). For example, when we access a page in a browser, it is usually a GET method, and the form submission is generally a POST method. The methods in @Controller also need to be distinguished:

@RequestMapping(value = "/login", method = RequestMethod.GET)

Public String loginGet() {

Return "Login Page";

}

@RequestMapping(value = "/login", method = RequestMethod.POST)

Public String loginPost() {

Return "Login Post Request";

}

Template rendering

In all previous @RequestMapping annotation methods, the return value string is passed directly to the browser and displayed to the user. However, in order to be able to present a richer and more beautiful page, we need to return the HTML code to the browser, and then the browser renders and displays the page.

A very straightforward way to do this is to return the HTML code directly in the method of processing the request, but the problem with this is that a complex page of HTML code is often very complex and embedded in Java code is not conducive to maintenance. A better approach is to write the HTML code of the page in a template file and render it back to the user. In order to be able to render the template, you need to change @RestController 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 hello. We use the Thymeleaf template engine for template rendering, and we need to introduce dependencies:

Dependency

"groupId" org.springframework.boot "/groupId"

"artifactId" spring-boot-starter-thymeleaf "/artifactId"

/dependency

Next you need to add a template file hello.html in the default template folder src/main/resources/templates/:

"! DOCTYPE HTML

Html xmlns:th=”http://”

"head"

"title" Getting Started: Serving Web Content "/title"

"meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /"

/head

"body"

"p th:text=”'Hello, ' + ${name} + '!' " / "

"/body"

"/html"

Th:text=”'Hello, ' + ${name} + '!'” is to render the attribute name we added to the Model in the @Controller method before and put it in the p tag (because th: Text is the attribute of the "p" tag). There are more usages for template rendering, please refer to the official Thymeleaf documentation.

Processing static files

Browser pages use HTML as the description language, so they must not be able to escape CSS and JavaScript. In order to be able to properly load resources like /css/style.css, /js/main.js, etc. by default, we only need to add css/style.css and js/main in the src/main/resources/static directory. After the .js file, Spring MVC can automatically publish them, and they can be loaded correctly by accessing /css/style.css, /js/main.js.

Dispenser

Automatic soap dispenser foam Intelligent Dispenser

Soap Dispenser Holder

Ningbo ATAP Electric Appliance Co.,Ltd , https://www.atap-airfryer.com