[Spring Boot] Web Development - Introduction to Web Development

Introduction to Web Development

First introduce the Web component spring-boot-starter-web provided by Spring Boot , then introduce @Controller and @RestController annotations, and @ResponseBody annotations that control data return, and finally introduce Web configuration, so that readers can use Spring Boot to develop Web systems. initial understanding.

1. Getting Started with the Web

Spring Boot integrates traditional web development frameworks such as mvc, json, validation, and tomcat, and provides the spring-boot-starter-web component, which simplifies the difficulty of web application configuration and development, and frees beginners from complicated configuration items , focusing on the implementation of business logic.

1.1 Introduction to spring-boot-starter-web

The spring-boot-starter-web component that comes with Spring Boot provides support for web application development. Its embedded Tomcat and Spring MVC dependencies are very convenient to use.

It is very simple to create a web application with Spring Boot. First create a common Spring Boot project, then modify the pom.xml file and add the spring-boot-starter-web component to the project to create a web application.

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>

We use the IDEA editor to open the newly created web project. Open Dependencies in Maven to see which dependent JAR packages will be introduced by the spring-boot-starter-web starter (Starters), as shown in the figure.

insert image description here

The spring-boot-starter-web starter mainly includes basic dependent components such as web, webmvc, json, tomcat, etc., and its function is to provide all the underlying dependencies required by the web development scenario. Among them, webmvc is the basic framework for web development, json is the JSON data parsing component, and tomcat is the built-in container dependency. Therefore, you only need to introduce the spring-boot-starter-web starter to realize web application development without additionally introducing Tomcat and other web dependent files.

In addition, template engines may be used to develop web applications. Spring Boot provides a large number of template engines, including FreeMarker, Groovy, Thymeleaf, Velocity, and Mustache. Spring Boot officially recommends using Thymeleaf.

1.2 Web project structure

Spring Boot's web application is basically the same as other Spring Boot applications, except that there are more static static resource directories and templates page template directories in the resources directory.

1.3 Implement a simple web request

Unlike the traditional MVC framework, Spring Boot must inherit a certain basic class to process HTTP requests. It only needs to declare the @Controller annotation on the class, mark this as a controller, and then use the @RequestMapping annotation to map the HTTP request to the corresponding method. That's it. The specific use is as follows:

@RestController
public class HelloController {
    
    
    @RequestMapping("/hello")
    public String hello() {
    
    
        return "hello word";
    }
}

In the above example, the @RequestMapping annotation is used to define the routing address of the request, which can act on both methods and classes.

Start the project, visit the http://localhost:8080/hello address in the browser, and you can see that the page returns "hello world". This shows that a simple Web project was created successfully.

2.@Controller和@RestController

Spring Boot provides @Controller and @RestController annotations to identify this class responsible for receiving and processing HTTP requests. If you are requesting pages and data, you can use the @Controller annotation; if you only request data, you can use the @RestController annotation.

2.1 Usage of @Controller

The @Controller annotation provided by Spring Boot is mainly used for returning pages and data. Let's create a HelloController to respond to the front page request. The sample code is as follows:

@Controller
@RequestMapping("user")
public class UserController {
    
    
    @RequestMapping("/index")
    public String index() {
    
    
        map.addAttribute("name", "thymeleaf-index");
        return "thymeleaf/index";
    }
}

The above example is used to request the /user/index address, and return the specific index page and data of name=thymeleaf-index. In the front-end page, the data returned by the background can be obtained through the ${name} parameter and displayed on the page.

In the @Controller class, if you only return data to the foreground page, you need to use the @ResponseBody annotation, otherwise an error will be reported. The sample code is as follows:

@Controller
public class HelloController {
    
    
    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
    
    
        return "hello word";
    }
}

2.2 Usage of @RestController

The @RestController annotation provided by Spring Boot is used to implement data request processing. By default, the @RestController annotation will convert the returned object data into JSON format. The sample code is as follows:

@RestController
@RequestMapping("/user")
public class UserController {
    
    
    @RequestMapping("/getUser")
    public User getUser() {
    
    
      User u =new User();
      u.setName("lxml.123");
      u.setAge(25);
      u.setPassword("lxml.123");
      return u;
    }
}

In the above example, the /user/getUser interface is defined to return User data in JSON format. At the same time, the @RequestMapping annotation can specify the request method through the method parameter. If the request method is incorrect, an error will be reported.

In recent years, the front-end framework has become more and more powerful, and the RESTful architecture with front-end and back-end separation has become the mainstream. Spring Boot also has very complete support for RESTful, and it is very simple to use. Use the @RestController annotation to automatically return data in JSON format, and use @GetMapping, PostMapping and other annotations to implement mapping RESTful interfaces.

2.3 The difference between @RestController and @Controller

Both @Controller and @RestController annotations identify whether the class can handle HTTP requests. It can be said that @RestController is a combination of @Controller and @ResponseBody, which is the effect of the combined use of these two annotations. Although the usage of the two is basically similar, there are still some differences, as follows:

1) @Controller identifies the current class as the Spring MVC Controller processor, while @RestController is only responsible for data return.

2) If the @RestController annotation is used, the method in the Controller cannot return the Web page, and the configured view resolver InternalResourceViewResolver does not work, and the returned content is the data in Return.

3) If you need to return to a specified page, use the @Controller annotation and cooperate with the view parser to return the page and data. If you need to return JSON, XML or custom content to the page, you need to add the @ResponseBody annotation to the corresponding method.

4) When using the @Controller annotation, on the corresponding method, the view parser can parse the returned JSP and HTML pages and jump to the corresponding page. If content such as JSON is returned to the page, the @ResponseBody annotation needs to be added.

5) The @RestController annotation is equivalent to the combination of @Controller and @ResponseBody annotations. It can directly convert the returned data into JSON data format without adding the @ResponseBody annotation before the method. However, JSP and HTML cannot be returned when using the @RestController annotation. page, because the view resolver cannot parse JSP, HTML pages.

In short, @Controller is used more in Web systems, while @RestController annotations are basically used in Web API.

3.@RequestMapping

The @RequestMapping annotation is mainly responsible for URL routing mapping. It can be added to the Controller class or a specific method. If it is added to the Controller class, all route mappings in this Controller will be added with this mapping rule. If it is added to the method, it will only take effect for the current method. The @RequestMapping annotation contains many attribute parameters to define HTTP request mapping rules. Commonly used attribute parameters are as follows:

  • value: The path of the requested URL, which supports URL templates and regular expressions.
  • method: The method of the HTTP request.
  • consumes: Allowed media types, such as consumes="application/json" is the Content-Type of HTTP.
  • produces: the corresponding media type, such as consumes="application/json" is the Accept field of HTTP.
  • params: request parameters.
  • headers: The value of the request header.

The above attributes basically cover all parameter information of an HTTP request. Among them, the value and method attributes are more commonly used.

4 @ResponseBody

The @ResponseBody annotation is mainly used to define the return format of the data. It acts on the method. By default, Jackson is used to serialize it into a JSON string and return it to the client. If it is a string, it will be returned directly.

Sometimes it is necessary to return data in JSON format in the Controller. If you want to return the data body directly instead of the view name, you need to use @ResponseBody on the method. The usage is as follows:

@Controller
@RequestMapping("/user")
public class UserController {
    
    
    @RequestMapping("/getUser")
    @ResponseBody
    public User getUser() {
    
    
      User u =new User();
      u.setName("lxml.123");
      u.setAge(25);
      u.setPassword("lxml.123");
      return u;
    }
}

In the above example, when /user/getUser is requested, User data in JSON format is returned. This is similar to what @RestController does.

It should be noted that when using the @ResponseBody annotation, you need to pay attention to the type and address of the request. If you expect to return JSON, but request a page whose URL ends with html, it will cause Spring Boot to think that the requested resource is of type HTML, and return the type of JSON The resource is inconsistent with the expected type, so the following error is reported:

insert image description here
According to the recommendation of the RESTful specification, in a Spring Boot application, if you expect to return JSON-type resources, use json as the resource suffix for the URL request; if you expect to return a view, use html as the resource suffix for the URL request.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/131779083