Custom View and Custom View Parser

Sometimes the view resolver provided by the SpringMVC framework doesn't meet our needs, so we can customize the view and view resolver to accomplish custom functions.

There are three main steps:

  • Writing custom view implementation classes
  • Write View Parser
  • Injecting a custom view parser into the ioc container in the configuration file

1. Write custom view implementation classes:

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.View;

// Implement the View interface to let the framework know that this is a view
public class MyView implements View {

	@Override
	public String getContentType() {
		return "text/html";
	}

	@Override
	public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// Write business logic to render view pages
		// Here you can get the data saved in the model
                // Requests and responses can be used for request s and responses
	}

}

2. Write a view parser:

import java.util.Locale;

import org.springframework.core.Ordered;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

// Implement the ViewResolver interface to let the framework know that it is a view resolver and implement the Ordered interface to sort
public class MyViewResolver implements ViewResolver, Ordered {

        // Traversal order of view parser
	private Integer order;

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

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

	@Override
	public View resolveViewName(String viewName, Locale locale) throws Exception {
		
		// Perform business logic for the view parser, render when the view object is returned, and continue traversing the next view parser if null is returned
		if (viewName.startsWith("myView:")) {
			return new MyView();
		}
		
		return null;
	}

}

3. Inject a custom view parser into the ioc container in the configuration file:

	<bean class="com.pudding.view.MyViewResolver">
                // The smaller the value of order, the higher the priority, the higher the order value of InternalResourceViewResolver is the maximum value of Integer.
		<property name="order" value="1"></property>
	</bean>

Tags: Java

Posted on Tue, 05 May 2020 01:53:32 -0700 by insrtsnhere13