SpringMVC’s data response (page jump, write back data)

Data response of SpringMVC

  • 1. Data response of SpringMVC
    • 01-Data Response of SpringMVC-Data Response Mode
    • 02-SpringMVC’s data response-page jump-return string form
    • 03-SpringMVC data response – page jump – return to ModelAndView form 1
    • 04-Data response of SpringMVC-page jump-return to ModelAndView form 2
    • 05-SpringMVC’s data response – page jump – return to ModelAndView3
    • 06-SpringMVC’s data response – write back data – write back string directly
    • 07-SpringMVC’s data response – write back data – directly write back json format string
    • 08-SpringMVC’s data response – write back data – return object or collection
    • 09-SpringMVC’s data response – write back data – return object or collection 2

1. SpringMVC data response

01-SpringMVC data response – data response method

  • page jump
    ①, directly return the string
    ②, return through the ModelAndView object
  • write back data
    ①, directly return the string
    ②, return object or collection

02-SpringMVC data response-page jump-return string format

  • Return string directly: This method will jump after concatenating the returned string with the prefix and suffix of the view parser.
  • Forward: forward:/WEB-INF/views/index.jsp
  • Redirection: redirect:/index.jsp, the reason why /WEB-INF/views is not written in front is because Redirection, the client visits again, WEB-INF is a protected folder, which cannot be accessed by the outside world.

03-SpringMVC data response-page jump-return to ModelAndView form 1

  • The method in the Controller returns the ModelAndView object, and sets the view name
package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user")
public class UserController {<!-- -->

    @RequestMapping("/quick2")
    public ModelAndView save2(){<!-- -->
        /*
        * Model model: the role is to encapsulate data
        * View view: function to display data
        * */
        ModelAndView modelAndView = new ModelAndView();
        //set view name
        modelAndView.setViewName("index");
        return modelAndView;
    }
}

  • We can set the View above, but the Model is empty, so let’s set the Model next. Set by the addObject() method of ModelAndView
@RequestMapping(value="/quick2")
public ModelAndView save2(){<!-- -->
    ModelAndView modelAndView = new ModelAndView();
    //set model data
    modelAndView.addObject("username","itcast");
    //set view name
    modelAndView.setViewName("success");

    return modelAndView;
}

04-SpringMVC data response-page jump-return to ModelAndView form 2

  • Directly declare ModelAndView on the method parameter in the Controller, instead of creating it yourself in the method, directly use the object to set the view in the method, and you can also jump to the page.
  • The parameters of the method corresponding to SpringMVC can help to perform corresponding injection. When SpringMVC parses the save3() method below, it finds that ModelAndView needs SpringMVC to inject, then SpringMVC will automatically inject.
@RequestMapping(value="/quick3")
public ModelAndView save3(ModelAndView modelAndView){<!-- -->
    modelAndView.addObject("username","itheima");
    modelAndView.setViewName("success");
    return modelAndView;
}

// Separate the Model and View and set them up separately
@RequestMapping("/quick4")
public String save4(Model model){<!-- -->
    //model adds parameters and stores data
    model.addAttribute("username","Hello SpringMVC");
    return "success";//View, will be returned as a string
}

05-SpringMVC data response-page jump-return to ModelAndView3

  • You can directly use the original HttpServeltRequest object on the formal parameter of the Controller method, just declare it; because SpringMVC will automatically inject it.
@RequestMapping(value="/quick5")
public String save5(HttpServletRequest request){<!-- -->
    request.setAttribute("username","Spicy Chicken");
    return "success";
}

06-SpringMVC data response – write back data – write back string directly

  • The response object injected through the SpringMVC framework uses response.getWriter().print(“hello world”) to write back the data. At this time, no view jump is required, and the return value of the business method is void.
@RequestMapping(value="/quick6")
public void save6(HttpServletResponse response) throws IOException {<!-- -->
    response.getWriter().print("hello itcast");
}
  • Return the string that needs to be written back directly, but at this time you need to pass@ResponseBody >The annotation tells the SpringMVC framework that the string returned by the method is not a jump but is returned directly in the http response body
@RequestMapping(value="/quick7")
@ResponseBody // Tell the SpringMVC framework to respond directly to the data without jumping to the view
public String save7() throws IOException {<!-- -->
    return "hello itheima";
}

07-SpringMVC’s data response-write back data-directly write back json format string

@RequestMapping(value="/quick8")
    @ResponseBody
    public String save8() throws IOException {<!-- -->
        return "{"username":"zhangsan","age":18}";
    }
  • ? The way of manually splicing json format strings is very troublesome. During development, complex java objects are often converted into json format strings?, we can use the web stage The learned json conversion tool jackson performs conversion, converts the json format string through jackson, and writes back the string
  • Create the com.iheima.domain package under the src\main\java file. Then create the User class
package com.itheima.domain;
public class User {<!-- -->
    private String name;
    private Integer age;

    public String getName() {<!-- -->
        return name;
    }
    public void setName(String name) {<!-- -->
        this.name = name;
    }
    public Integer getAge() {<!-- -->
        return age;
    }
    public void setAge(Integer age) {<!-- -->
        this. age = age;
    }
    @Override
    public String toString() {<!-- -->
        return "User{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }
}
  • Import json coordinates in the pom.xml file
<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>
@RequestMapping("/quick9")
@ResponseBody
public String save9() throws IOException {<!-- -->
    User user = new User();
    user.setName("lisi");
    user.setAge(30);
    //Use the json conversion tool to convert the object into a json format string and return
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper. writeValueAsString(user);
    return json;
}

08-SpringMVC data response – write back data – return object or collection

  • Using SpringMVC to help us convert and write back json strings for objects or collections, configure message conversion parameters for processor adapters, and specify the use of jackson for object or collection conversion, so you need to configure the following in spring-mvc.xml:
<!--Configure the processor mapper and set internal parameters to tell SpringMVC to automatically use Jackson for conversion -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<!--Add parameters-->
<property name="messageConverters">
       <list>
           <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
       </list>
   </property>
</bean>
@RequestMapping(value="/quick10")
@ResponseBody
//Expect SpringMVC to automatically convert User into a string in json format
public User save10() throws IOException {<!-- -->
    User user = new User();
    user.setUsername("lisi2");
    user.setAge(32);
    return user;
}

09-SpringMVC data response – write back data – return object or collection 2

  • Adding @ResponseBody to the method can return a string in json format, but this configuration is more troublesome, and the configuration code is more, so we can use the mvc annotation driver to replace the above configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <!--annotation driver for mvc-->
    <mvc:annotation-driven/>
</beans>
  • Among the various components of SpringMVC, the processor mapper, processor adapter, and view resolver are called the three major components of SpringMVC.
  • Use to automatically load RequestMappingHandlerMapping (processing mapper) and RequestMappingHandlerAdapter (processing adapter), which can be used in Spring-xml Use in the .xml configuration file to replace the configuration of annotation processors and adapters.
  • Using at the same time, the default bottom layer will integrate jackson to convert the json format string of the object or collection
syntaxbug.com © 2021 All Rights Reserved.