SpringMVC view resolver InternalResourceViewResolver

When we use SpringMVC, surely we know that, for safety reasons, our JSP files are placed in the WEB-INF,

But we are not under direct resources to access / WEB-INF / directory on the outside of it,

Carried forward can only be accessed through the form of an internal server, by forwarding InternalResourceViewResolver underlying form to help us solve this problem!


In order to use InternalResourceViewResolver we will be as follows SpringMVC profile

    <!--  自定义视图解析器  -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/"/>
    <property name="suffix" value=".jsp"/>
</bean>

Then we want to access a file in the WEB-INF directory you can directly enter the name of the file to

E.g:

  view view resolver will help us resolve to the underlying /WEB-INF/view.jsp 

Well, it's the bottom of exactly how to achieve it?


 

InternalResourceViewResolver: It is a subclass of UrlBasedViewResolver, then it means that all the features UrlBasedViewResolver all the support,

  So InternalResourceViewResolver in the end what characteristics do? We from its literal sense, can be understood as an internal resource view resolver, it is the case, it is also the most widely used view resolvers.

 

 

 

To make us look, its underlying source code

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.web.servlet.view;

import org.springframework.util.ClassUtils;

public class InternalResourceViewResolver extends UrlBasedViewResolver {
    private static final boolean jstlPresent = ClassUtils.isPresent("javax.servlet.jsp.jstl.core.Config", InternalResourceViewResolver.class.getClassLoader());
    private Boolean alwaysInclude;

    public InternalResourceViewResolver() {
        Class<?> viewClass = this.requiredViewClass();
        if (viewClass.equals(InternalResourceView.class) && jstlPresent) {
            viewClass = JstlView.class;
        }

        this.setViewClass(viewClass);
    }

    protected Class<?> requiredViewClass() {
        return InternalResourceView.class;
    }

    public void setAlwaysInclude(boolean alwaysInclude) {
        this.alwaysInclude = alwaysInclude;
    }

    protected AbstractUrlBasedView buildView(String viewName) throws Exception {
        InternalResourceView view = (InternalResourceView)super.buildView(viewName);
        if (this.alwaysInclude != null) {
            view.setAlwaysInclude(this.alwaysInclude);
        }

        view.setPreventDispatchLoop(true);
        return view;
    }
}

InternalResourceViewResolver will then call the method by performing buildView vuildView parent's method, we request the return or return of viewname pass in the past, we look at the realization of this method

// the code section has been deleted important 
protected AbstractUrlBasedView buildView (String viewName) throws Exception { AbstractUrlBasedView View = (AbstractUrlBasedView) BeanUtils.instantiateClass ( the this .getViewClass ()); // get a view class inheritance relationship view.setUrl ( the this .getPrefix () + + viewName the this .getSuffix ()); // get our configuration in the configuration file prefix and suffix and passed in viewName String contentType = the this .getContentType (); IF ! (contentType = null ) { view.setContentType (contentType); // view type } return view; // return our view }

We can see by this method, this method creates a preferred view, although we do not know, but they have an indirect inheritance, we can view the inheritance structure itself.

Then there is to get the prefix and suffix viewName name InternalResourceViewResolver we configured in SpringMVC that make up a complete url for example: /WEB-INF/a.jsp, and finally the view of the arrangement constitutes a return

InternalResourceView view. Then InternalResourceView View Controller processor will return all the properties of the model into the HttpServletRequest inside, let's look at the underlying execution

// call the object's methods InternalResourceView 

 protected  void renderMergedOutputModel (the Map <String, Object> Model, the HttpServletRequest request, the HttpServletResponse Response) throws Exception {
         the this .exposeModelAsRequestAttributes (Model, request); // call is then performed by placing this method to the request , see next following code fragment of
         the this .exposeHelpers (Request); 
        String dispatcherPath = the this .prepareForRendering (Request, Response); 
        the RequestDispatcher RD = the this .getRequestDispatcher (Request, dispatcherPath);
         IF (RD == null ) {
             the throw  new new ServletException("Could not get RequestDispatcher for [" + this.getUrl() + "]: Check that the corresponding file exists within your web application archive!");
        } else {
            if (this.useInclude(request, response)) {
                response.setContentType(this.getContentType());
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Including resource [" + this.getUrl() + "] in InternalResourceView '" + this.getBeanName() + "'");
                }

                rd.include(request, response);
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Forwarding to resource [" + this.getUrl() + "] in InternalResourceView '" + this.getBeanName() + "'");
                }

                rd.forward(request, response);
            }

        }
    }

 

//调用的是AbstractView 类

protected void exposeModelAsRequestAttributes(Map<String, Object> model, HttpServletRequest request) throws Exception {
        Iterator var3 = model.entrySet().iterator();

        while(var3.hasNext()) {
            Entry<String, Object> entry = (Entry)var3.next();
            String modelName = (String)entry.getKey();
            Object modelValue = entry.getValue();
            if (modelValue != null) {
                request.setAttribute(modelName, modelValue);//把Controller返回的模型属性值放入
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Added model object '" + modelName + "' of type [" + modelValue.getClass().getName() + "] to request in view with name '" + this.getBeanName() + "'");
                }
            } else {
                request.removeAttribute(modelName);
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Removed model object '" + modelName + "' from request in view with name '" + this.getBeanName() + "'");
                }
            }
        }

    }

RequestDispatcher then the server redirects the request to the target URL forword

These are the InternalResourceViewResolver resolution process

It is coherent

Returns the name will view InternalResourceViewResolver resolve both InternalResourceView objects, InternalResourceView Controller processor will return method to model attributes are stored in the corresponding request attribute, the server then redirects the request to the target URL by forword RequestDispatcher. In the example, the definition in InternalResourceViewResolver prefix = / WEB-INF /, suffix = .jsp, view name Controller processor then requests the method returned to test, then this time the test will InternalResourceViewResolver InternalResourceView resolved to a target, first returned model attributes are stored to corresponding attribute HttpServletRequest, then use the request to the server RequestDispatcher forword to /WEB-INF/a.jsp.

 

Finally, we summarize the overall view resolution process:

1, call the target method, SpringMVC the target method returns a String, View, ModelMap or ModelAndView are converted to a ModelAndView object;

2, and then parses ModelAndView View object by object view resolver (ViewResolver), the object is to resolve the logical view of a physical view View View object;

3, the last call physical view View objects render () method of rendering a view to obtain the response result.

Guess you like

Origin www.cnblogs.com/arebirth/p/springmvcirvr.html