Application of spring MVC technology in 06 springboot project?

Time:2020-11-26

Introduction to spring MVC

Background analysis

In the design of large-scale software system, the business will be relatively complex. If all the codes of business implementation are entangled together, there will be problems such as unclear logic, poor readability, difficult maintenance, and so on. In order to better solve this problem, we now often talk about hierarchical architecture design.

What is MVC

MVC is a kind of software architecture design idea. Based on MVC architecture, our application software is designed and implemented in layers. For example, it can be divided into view layer, control layer and model layer. Through this hierarchical design, our program has better flexibility and expansibility, because it can simplify a complex application and realize its own functions, It is suitable for the development of a large application

Overview of spring MVC

Spring MVC is an implementation of MVC design idea in spring framework. Based on this idea, spring framework designs some related objects to better handle requests and responses based on MVC architecture. Its simple architecture is shown in the figure

Application of spring MVC technology in 06 springboot project?

Among them:
1) The dispatcher servlet is the entry of all requests processing of the client, which is responsible for the request forwarding.
2) Requestmapping is responsible for storing the mapping between the request URL and the backend handler object.
3) Handler is used to process the request data forwarded by the dispatcher servlet object.
4) Viewresolver is responsible for processing views in all handler object response results.

Spring MVC quick start

preparation

Step 1: create the project module. The basic information is shown in the figure

Application of spring MVC technology in 06 springboot project?

Step 2: add the project dependency (either when or after the module is created). The code is as follows:

Spring web dependency (provides spring MVC support and embeds a Tomcat)

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

Thymeleaf dependency (provides related objects for parsing and manipulating HTML as a page template)

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

Step 3: start the project to check whether the console startup status is OK

Analysis and application of static directory

Statistics directory is a directory created automatically after web dependency is added when the springboot project is created. HTML, CSS, JS, HTML and other related resources can be stored in this directory. These resources can be accessed directly in the browser after the server is started. For example:
Step 1: create one in the statistics directory index.html Page, code as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   <h1>The First Html Page</h1>
</body>
</html>

Step 2: start the server and test the access directly, as shown in the figure

Application of spring MVC technology in 06 springboot project?

Analysis and application of templates directory

The templates directory is a directory that is automatically created by thymeleaf dependency when the springboot project is created. To store some HTML templates in this directory, the template page cannot be accessed directly through the browser URL. It is necessary to define the page response in the method based on the back-end controller. For example:

Step 1: define the templatecontroller and method. The code is as follows:

package com.cy.pj.health.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TemplateController {
      @RequestMapping("doTemplateUI")
      public String doTemplateUI(){
         return "default";
      }
}

Step 2: define the template page in the templates directory default.html The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>The Default Template page</h1>
</body>
</html>

Among them, if default.html To put it in the templates subdirectory, you also need to configure the prefix of thymeleaf in the configuration file, for example:

spring.thymeleaf.prefix=classpath:/templates/module/

Step 3: start the service for access test, as shown in the figure:

Application of spring MVC technology in 06 springboot project?
Spring MVC response data processing

Modelandview application

We have a business. Now we need to encapsulate the response data into modelandview object, and then respond to the client. How to implement it?

Step 1: define modelandviewcontroller and methods, and return the page and data form

package com.cy.pj.module.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ModelViewController {
    //Method 1
 @RequestMapping("/doModelAndView")
    public String doModelAndView(Model model) {
        model.addAttribute("username", "json");
        model.addAttribute("state", "OK");
        return "view";//viewname
 }
    //Method 2
 @RequestMapping("/doModelAndView01")
    public ModelAndView doModelAndView(ModelAndView mv) {
        //ModelAndView mv = new ModelAndView();
 mv.addObject("username", "jack");
        mv.addObject("state", "yes");
        mv.setViewName("view");
        return mv;
    }
}

Return page form code: in tetemplates.moudle Create under file view.html 。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>View display</h1>
    <div>
        <ul>
            <li>username:[[${username}]]</li>
            <li>state:[[${state}]]</li>
        </ul>
    </div>
</body>
</html>

Step 3: start the project for access test, and test the output results, for example:
Application of spring MVC technology in 06 springboot project?

JSON data response

We have a business that does not need a page, only needs to convert the response data to JSON, and then respond to the client. How to achieve this?
Step 1: define the reponseresult object to encapsulate the response data. For example:

package com.cy.pj.module.pojo;
public class ResponseResult {
    private Integer code;
    private String message;
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

Step 2: define the jsonobjctcontroller and method. The code is as follows:

package com.cy.pj.module.controller;

@RestController
//@[email protected][email protected]
public class JsonObjectController {
@RequestMapping("/doConvertResponseToJson")
//@ResponseBody
    public ResponseResult doConvertResponseToJson(){
        ResponseResult rs=new ResponseResult();
        rs.setCode(200);
        rs.setMessage("OK");
        return rs;
    }
    
    @RequestMapping("/doConvertMapToJson")
    //@ResponseBody
    public Map<String,Object> doConvertMapToJson(){
        Map<String,Object> map=new HashMap<>();
        map.put ("username", "Andy Lau");
        map.put("state",true);
        return map;
    }
    
    @RequestMapping("/doPrintJSON")
    //@ResponseBody
    public void doPrint(HttpServletResponse response)throws Exception{
        Map<String,Object> map=new HashMap<>();
        map.put ("username", "Andy Lau");
        map.put("state",true);
        //Convert the data in the map to a JSON format string
        ObjectMapper om=new ObjectMapper();
        String jsonStr=om.writeValueAsString(map);
        System.out.println("jsonStr="+jsonStr);
        //Respond the string to the client
        //Set the encoding of response data
        response.setCharacterEncoding("utf-8");
        //Tell the client that the data type to respond to it is text / HTML, encoded as UTF-8. Please render the data in this encoding
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw=response.getWriter();
        pw.println(jsonStr);
    }
    
}

Step 3: start the server for access test, and the code is as follows:

Application of spring MVC technology in 06 springboot project?
Anomaly analysis:
The request resource does not exist, the page shows 404
Application of spring MVC technology in 06 springboot project?
Application of spring MVC technology in 06 springboot project?
Template parsing is incorrect or does not exist page display 500
Application of spring MVC technology in 06 springboot project?
Application of spring MVC technology in 06 springboot project?

Spingmvc request parameter data processing

In the process of business execution, we usually pass some request parameters to the server. How does the server get the parameters and inject them into our method parameters?

preparation

Define a controller object to handle client requests, such as:

package com.cy.pj.module.controller;
import com.cy.pj.module.pojo.RequestParameter;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
public class ParamObjectController {}

Direct measurement

Add a method to paramobjectcontroller to accept client request parameters based on direct quantity, for example:

@GetMapping("/doParam01")
public String doMethodParam(String name){
 return "request params "+name;
}

When accessing, you can pass parameters in this way, for example:

http://localhost/doParam01?name=beijing

POJO object mode

Define a POJO object to accept client request parameters, such as:

package com.cy.pj.module.pojo;
public class RequestParameter {
    private String name;
    //......
 public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
 public String toString() {
        return "RequestParam{" +
                "name='" + name + ''' +
                '}';
    }
}

Define the controller method, in which POJO object is used to receive method parameters, for example:

@RequestMapping("/doParam02")
Public string domethodparam (requestparameter param) {// the POJO object receives the request parameters, and the set method matching the parameter name should be provided in the POJO object
 return "request params "+param.toString();
}

Start the service for access test. You can pass parameters in this way, for example:

http://localhost/doParam02?name=beijing

Map object mode

Sometimes we don’t want to use the POJO object to receive the request parameters. We can use the map object to receive the request parameters. How can we implement this?

Define the controller method to receive the request parameters based on the map object, for example:

@GetMapping("/doParam03")
public String doMethodParam(@RequestParam Map<String,Object> param){
 return "request params "+param.toString();
}

The map must use @ requestparam to describe the request parameters

Start the service for access test. You can pass parameters in this way, for example:

http://localhost/doParam03?name=beijing

Summary

This chapter introduces the application of spring MVC technology in springboot project, and explains a basic process of request data acquisition and response data processing in MVC combined with the business application in the actual project