Get rid of first View Controller with Spring 4 and

2019-09-15 03:33发布

问题:

I use RestController to fetch data with AngularJS, but still I need regular controller to load index.html:

@Controller
public final class LayoutController {
    @RequestMapping(value = "/")
    public String getIndexPage() {
        return "/resources/index";
    }
}

Every other controllers are RestControllers. If index file has jsp extension, I don't neeed LayoutController, but when it is html it is needed. This is my dispatcher config:

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

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="1"></property>
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.html</value>
        </property>
    </bean>

</beans>

And this is part of applicationContext:

<mvc:annotation-driven/>
<tx:annotation-driven />

<mvc:resources mapping="/resources/**" location="WEB-INF/resources/" />

Is there a way to get rid of LayoutController when I want to use index.html instead of index.jsp? Thank you in advance for help. Solution based on accepted answer:

<mvc:view-controller path="/" view-name="/resources/index.html"/>

Without LayoutController and InternalResourceViewResolver at all.

回答1:

you can use view-controller,

<mvc:view-controller path="/" view-name="index"/>

I am assuming you already have a InternalResourceViewResolver pointing to the jsp location . If not you also have to include it in application context.

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/resources/" /> <property name="suffix" value=".html" /> </bean>

if you don't wanna include InternalResourceViewResolver you can also directly forward to html.

<mvc:view-controller path="/" view-name="forward:/WEB-INF/resources/index.html"/>

Hope , this is what you was looking for.