Data response of Spring MVC

Keywords: Java Spring Spring MVC mvc

4. Data response of spring MVC

4.1 data response mode of spring MVC

1) Page Jump
 directly return string
 returned by ModelAndView object

2) Write back data
 directly return string
 return object or set

4.2 page Jump

1. Return string form

Directly return string: this method will splice the returned string with the front suffix of the view parser and jump.

Returns a string with a prefix:
forward:/WEB-INF/views/index.jsp
Redirect: redirect:/index.jsp

2. Return ModelAndView object

 @RequestMapping("/quick2")
        public ModelAndView save2(){
            /**
             * Model:Model. Encapsulate data
             * View: View, display data
             */
            ModelAndView modelAndView = new ModelAndView();
            //Set Model data
            modelAndView.addObject("username","zhangsan");
            //Set view name
            modelAndView.setViewName("/success.jsp");
            return modelAndView;
        }

3. Store data to the request field

When forwarding, it is often necessary to store data in the request field and display it in the jsp page. How to forward data to the request in the Controller
What about storing data in the domain?

① The request object injected through the spring MVC framework is set by the setAttribute() method

 @RequestMapping("/quick5")
    public String save5(HttpServletRequest request){
        request.setAttribute("username","Zhang Sanfeng");
        return "success.jsp";
    }

② Set through the addObject() method of ModelAndView

 @RequestMapping("/quick4")
    public String save4(Model model){
        model.addAttribute("username","wangwu");
        return "success.jsp";
    }

4.3 updating data

  1. Returns a string directly

In the Web foundation stage, the client accesses the server. If you want to write back the string directly as the response body, you only need to use
response.getWriter().print("hello world") is all you need, so you can think straight in the Controller
How to write back a string?

① The response object injected through the spring MVC framework uses response.getWriter().print("hello world") to write back the number
It is understood that view jump is not required at this time, and the return value of the business method is void.

  @RequestMapping("/quick6")
    public void save6(HttpServletResponse response) throws IOException {
        response.getWriter().print("hello Spring MVC");
    }

② Return the string that needs to be written back directly, but at this time, you need to inform the spring MVC framework through the @ ResponseBody annotation
The returned string is not a jump, but is returned directly in the http response body.

@RequestMapping("/quick7")
    @ResponseBody //Tell the spring MVC framework that this method does not jump the view, but directly responds to the data
    public String save7() {
        return "hello Spring MVC";
    }

In asynchronous projects, the client and server often interact with json format strings. At this time, we can manually splice json strings to return.

  @RequestMapping("/quick8")
    @ResponseBody //Tell the spring MVC framework that this method does not jump the view, but directly responds to the data
    public String save8() {
        return "{\"username\":\"Zhang San\",\"age\":18}";
    }

It is troublesome to manually splice json format strings in the above way. Complex java objects are often converted into json format strings in development,
We can use the json conversion tool jackson to convert and import jackson coordinates.

 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.4</version>
        </dependency>

Convert json format string through jackson and write back the string.

@RequestMapping("/quick9")
    @ResponseBody //Tell the spring MVC framework that this method does not jump the view, but directly responds to the data
    public String save9() throws JsonProcessingException {
        User user = new User();
        user.setUsername("Li Si");
        user.setAge(20);
        //Use the json conversion tool to convert the object into a json format string and then return it
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        return json;
    }
  1. Returns an object or collection

Spring MVC helps us convert and write back json strings to objects or collections, and configure message conversion parameters for the processor adapter,
Specifies that jackson is used for object or collection conversion. Therefore, the following configuration is required in spring-mvc.xml:

 <!--Configure processor mapper-->
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
            </list>
        </property>
    </bean>

After the processing mapper is configured in the spring MVC configuration file, the return object can be automatically converted to JSON format

 @RequestMapping("/quick10")
    @ResponseBody //Tell the spring MVC framework that this method does not jump the view, but directly responds to the data
    //Expect spring MVC to automatically convert User to
    public User save10(){
        User user = new User();
        user.setUsername("Li Si");
        user.setAge(20);
        return user;
    }

Adding @ ResponseBody to the method can return a string in json format, but this configuration is cumbersome and there are many configured codes,
Therefore, we can use mvc annotation driven instead of the above configuration.

<!--to configure Spring MVC Annotation driven-->
    <mvc:annotation-driven></mvc:annotation-driven>

Among the components of spring MVC, processor mapper, processor adapter and view parser are called the three components of spring MVC.
Use MVC: annotation driven to automatically load requestmapping handler mapping and
RequestMappingHandlerAdapter (processing adapter), which can be used in the Spring-xml.xml configuration file
MVC: annotation driven replaces the configuration of annotation processors and adapters.
At the same time, using MVC: annotation driven, by default, the underlying layer will integrate jackson to convert json format strings of objects or collections.

4.4 key points of knowledge

Data response mode of spring MVC
1) Page Jump
 directly return string
 returned by ModelAndView object
2) Write back data
 directly return string
 return object or set

Posted by vinod79 on Mon, 11 Oct 2021 18:17:53 -0700