SpringMVC response

Table of contents

One: Environmental preparation

Two: Response page [understand]

Three: return text data [understand]

Four: Respond to JSON data


             After SpringMVC receives the request and data, it performs some processing. Of course, this processing can be forwarded to the Service, and the Service layer calls the Dao layer to complete. In any case, after the processing, the result needs to be notified to the user.

For example: query user information according to user ID, query user list, add new users, etc.

For the response, it mainly includes two parts:

  • response page

  • response data

    • text data

    • json data

Because asynchronous calls are the mainstream method commonly used at present, we need to pay more attention to how to return JSON data, and we only need to know about others.

One: Environmental preparation

  • Create a Web Maven project

  • pom.xml adds Spring dependency

<?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.itheima</groupId>
  <artifactId>springmvc_05_response</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>80</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Create the corresponding configuration class

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //乱码处理
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}

@Configuration
@ComponentScan("com.itheima.controller")
//开启json数据类型自动转换
@EnableWebMvc
public class SpringMvcConfig {
}

Write the model class User

public class User {
    private String name;
    private int age;
    //getter...setter...toString省略
}

Create page.jsp under webapp

<html><body><h2>Hello Spring MVC!</h2></body></html>

Write UserController

@Controller
public class UserController {

    
}

The final created project structure is as follows:

 

Two: Response page [understand]

Step 1: Set up the back page

@Controller
public class UserController {
    
    @RequestMapping("/toJumpPage")
    //注意
    //1.此处不能添加@ResponseBody,如果加了该注入,会直接将page.jsp当字符串返回前端
    //2.方法需要返回String
    public String toJumpPage(){
        System.out.println("跳转页面");
        return "page.jsp";
    }
    
}

Step 2: Start the program test

This involves page jumps, so it is not suitable to use PostMan for testing. Open the browser directly and enter

http://localhost/toJumpPage

Three: return text data [understand]

Step 1: Set the return text content

@Controller
public class UserController {
    
   	@RequestMapping("/toText")
	//注意此处该注解就不能省略,如果省略了,会把response text当前页面名称去查找,如果没有回报404错误
    @ResponseBody
    public String toText(){
        System.out.println("返回纯文本数据");
        return "response text";
    }
    
}

 

Step 2: Start the program test

There is no page jump involved here, because what we are sending now is a post request, you can use a browser or PostMan to test, enter the address to http://localhost/toTextaccess

 

 

Four: Respond to JSON data

Response POJO object

@Controller
public class UserController {
    
    @RequestMapping("/toJsonPOJO")
    @ResponseBody
    public User toJsonPOJO(){
        System.out.println("返回json对象数据");
        User user = new User();
        user.setName("itcast");
        user.setAge(15);
        return user;
    }
    
}

The return value is an entity class object. Set the return value to the entity class type to return the json data of the corresponding object. It needs to rely on the ==@ResponseBody== annotation and ==@EnableWebMvc== annotation

Restart the server, accesshttp://localhost/toJsonPOJO

Response POJO collection object

@Controller
public class UserController {
    
    @RequestMapping("/toJsonList")
    @ResponseBody
    public List<User> toJsonList(){
        System.out.println("返回json集合数据");
        User user1 = new User();
        user1.setName("传智播客");
        user1.setAge(15);

        User user2 = new User();
        user2.setName("黑马程序员");
        user2.setAge(12);

        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);

        return userList;
    }
    
}

Restart the server, accesshttp://localhost/toJsonList

 

Knowledge point 1: @ResponseBody

name @ResponseBody
type ==Method\Class Annotation==
Location Above the SpringMVC controller method definition and on the control class
effect Set the return value of the current controller as the response body, write it on the class, and all methods of this class have this annotation function
related attributes pattern: Specifies the date and time format string

illustrate:

  • This annotation can be written on the class or on the method

  • Written on the class means that all methods under the class have the @ReponseBody function

  • When the method is annotated with @ReponseBody

    • The return value of the method is a string, which will be directly responded to the front end as text content

    • The return value of the method is an object, which will convert the object into a JSON response to the front end

Type conversion is used here again, and it is completed internally through the implementation class of the Converter interface, so in addition to the functions mentioned above, Converter can also implement:

  • Object to Json data (POJO -> json)

  • Collection to Json data (Collection -> json)

Guess you like

Origin blog.csdn.net/qq_61313896/article/details/128862631