How spring MVC parses views

1, Parse view process

No matter what the return value type of the request processing method is, it will be encapsulated into a ModelAndView return, and then a View object will be obtained through the ViewResolve parser to render the page through the View object.

2, View and view parser

  • After the request processing method is executed, a ModelAndView object is finally returned. For those processing methods that return types such as String, View or ModelMap, spring MVC will also internally assemble them into a ModelAndView object, which contains the logical name and the View of the model object.
  • Spring MVC obtains the final View object with the help of View resolver. The final View can be JSP or views in various forms such as Excel and JFreeChart.
  • The processor doesn't care about which view object is used to render the model data. The processor focuses on the production of model data, so as to realize the full decoupling of MVC.

view

  • The function of view is to render model data and present the data in the model to customers in some form.
  • In order to decouple the View model from the specific implementation technology, Spring springframework. web. A highly abstract View interface is defined in the servlet package
  • The view object is instantiated by the view parser. Because views are stateless, they do not have thread safety issues.

Common view implementation classes

view resolver

  • Spring MVC provides different strategies for parsing logical view names. You can configure one or more parsing strategies in the context of spring web and specify their order. Each mapping strategy corresponds to a specific view parser implementation class.
  • The function of view parser is relatively simple, which is to parse the logical view into a specific view object.
  • All view parsers must implement the ViewResolver interface.

Common view parser implementation classes

3, Custom view

Write a custom view parser and view implementation class

The MyViewResolver view parser needs to implement the ViewResolver interface and the method of returning the view object, as well as the Ordered interface to change the execution priority of the custom view parser

public class MyViewResolver implements ViewResolver,Ordered{

    private Integer order = 0;

    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        //Returns the view object based on the view name
        if (viewName.startsWith("myView:")){
            return new MyView();
        }else {
            //Cannot process return null
            return null;
        }

    }

    @Override
    public int getOrder() {
        return order;
    }

    //Change the execution order of the view parser
    public void setOrder(Integer order){
        this.order = order;
    }
}

The MyView View implementation class needs to implement the View interface and the render() method of rendering the page

public class MyView implements View{

    /**
     * Returns the type of data content
     * @return
     */
    @Override
    public String getContentType() {
        return "text/html";
    }

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("Previously saved data:" + model);
        response.setContentType("text/html");
        List<String> vname = (List<String>)model.get("vname");
        List<String> imgsname = (List<String>)model.get("imgsname");

        for (String s : vname){
            response.getWriter().write(s);
        }
    }
}

With a custom view parser and view implementation class, then write the MyViewResolverController processor to process the custom view

@Controller
public class MyViewResolverController {

    @RequestMapping("/myview")
    public String myView(Model model){
        //Custom processing logic
        List<String> vname = new ArrayList<String>();
        List<String> imgname = new ArrayList<String>();
        vname.add("Naruto");
        vname.add("One Piece");
        vname.add("death");
        imgname.add("Whirlpool Naruto");
        imgname.add("Sasuke");


        model.addAttribute("video",vname);
        model.addAttribute("imgs",imgname);

        return "myview:/success";
    }
}

You also need to put the custom view parser in the IOC container so that spring MVC can recognize the custom view parser

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--Scan all components-->
    <context:component-scan base-package="controller"></context:component-scan>

    <!--Spliced view can help us configure an address-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--Custom view parser-->
    <bean class="view.MyViewResolver">
        <!--set up order Property to change the priority of custom view execution. The smaller the value, the higher the priority-->
        <property name="order" value="1"></property>
    </bean>
</beans>

Output result:

Keywords: Spring MVC

Added by bh on Fri, 18 Feb 2022 19:53:26 +0200