Java 从控制器转发到静态html页面

Java 从控制器转发到静态html页面,java,rest,spring-mvc,Java,Rest,Spring Mvc,我的spring mvc应用程序只有一个ContentNegotiatingViewResolver,它定义了用于呈现json响应的JsonView: <mvc:annotation-driven/> <context:component-scan base-package="world.domination.test"/> <bean class="org.springframework.web.servlet.view.ContentNegotiatingV

我的spring mvc应用程序只有一个ContentNegotiatingViewResolver,它定义了用于呈现json响应的JsonView:

<mvc:annotation-driven/>

<context:component-scan base-package="world.domination.test"/>

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json"/>
        </map>
    </property>
    <property name="defaultViews">
        <list>
            <bean class="com.secondmarket.connector.springmvc.MappingJacksonJsonViewEx"/>
        </list>
    </property>
</bean>

整个应用程序位于根url“myapp”上。一切按我的需要进行

第一个问题是:访问某个url时如何返回静态html页面?比如说,当访问SpringURI/myapp/test时,我想呈现一个驻留在根webapp文件夹中的html页面/TestStuff.html

我继续写了一个简单的控制器:

@Controller
@RequestMapping("test")
public class TestConnector {

    @Autowired
    private RestTemplate tpl;

    @RequestMapping(method = RequestMethod.GET)
    public String get() {
        return "/TestStuff.html";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String post(@RequestParam("url") String url, @RequestParam("data") String data) {
        return tpl.postForObject(url, data, String.class, new HashMap<String, Object>());
    }
}
@控制器
@请求映射(“测试”)
公共类测试连接器{
@自动连线
私人第三方物流;
@RequestMapping(method=RequestMethod.GET)
公共字符串get(){
返回“/TestStuff.html”;
}
@RequestMapping(method=RequestMethod.POST)
公共字符串post(@RequestParam(“url”)字符串url,@RequestParam(“数据”)字符串数据){
返回tpl.postForObject(url、数据、String.class、new HashMap());
}
}
get()方法应该告诉Spring呈现TestStuff.html,但我得到的是 表示缺少名为“/TestStuff.html”的视图时出错

第二个问题是如何避免对URL进行扩展。在我的示例中,当我使用/myapp/test而不是/myapp/test.html时,我的ContentNegotingViewResolver使用一个json视图来呈现{}(空花括号)

非常感谢任何指针。

请尝试返回“重定向:/TestStuff.html”,而不是从控制器返回“/TestStuff.html”

另一个选项是为静态页面创建并注册视图解析器。也许是这样的:


最好的方法是将InternalResourceViewResolver与mvc:view控制器标记结合使用(有关详细信息,请参阅相应的Spring参考手册)。只需在应用程序上下文XML文件中包含以下内容(在本例中,静态文件TestStuff.html将位于/WEB-INF/static pages目录中):


tutorialPoint提供了一个很好的完整示例:

从您的
ContentNegotiatingViewResolver
配置来看,我不明白您想要实现什么。当同一资源可能以不同的表示形式呈现时,此冲突解决程序适用。如果一些资源是用JSON呈现的,而另一些是HTML呈现的,则需要另一种解析程序配置。这个“redirect:/TestStuff.HTML”可以正常工作(至少在Spring MVC 3.1.1中是这样)。。。这比添加viewResolver更简单,因为我已经为所有JSP页面定义了一个viewResolver。
<bean>
    <bean id="staticPagesViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/static-pages/"/>
    <property name="suffix" value=".html"/>
</bean>

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