问题
I have a freemarker viewresolver in my spring application:
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
In my controller methods i can return the name of my freemarker template:
return "timeline";
Works without any problems.
Now i've created a new template language and i want a few controllers to use this custom template language. So i created a CustomViewResolver.
<bean id="viewResolver" class="org.CustomViewResolver">
Now i have 2 view resolvers, a freemarker one and my custom one.
How can i specify which ViewResolver should be used by which controller?
Cause my backend will use freemarker and my frontend the custom one.
回答1:
You could try something along the lines of the following example:
Folder and file structure
webapp
WEB-INF
dispatcher-servlet.xml
jsp
bar
bar-baz.jsp
foo
foo-fro.jsp
dispatcher-servlet.xml
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/bar/" />
<property name="suffix" value=".jsp"/>
<property name="viewNames" value="bar-*"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/foo/" />
<property name="suffix" value=".jsp"/>
<property name="viewNames" value="foo-*"/>
</bean>
Controller
@RequestMapping(value="/bar")
public String bar() { return "bar-baz"; }
@RequestMapping(value="/foo")
public String foo() { return "foo-fro"; }
You will be taking advantage of the view name pattern-matching offered by the framework. If you run into problems, you can try setting an additional order
property for the view resolvers to control the order in which the resolvers should attempt to locate views for a request. You would put your custom view resolver at the top (lowest order) and try others if the custom resolver fails.
来源:https://stackoverflow.com/questions/25339741/specify-which-viewresolver-to-use-per-controller