【问题标题】:Forward to a static html page from Controller从 Controller 转发到静态 html 页面
【发布时间】:2010-10-29 13:37:38
【问题描述】:

我的 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页面?比如说,在访问 Spring uri /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>());
    }
}

get() 方法应该告诉 Spring 渲染一个 TestStuff.html,但我得到了 错误提示名称为“/TestStuff.html”的视图丢失。

第二个问题是如何避免在 URL 中添加扩展名。在我的示例中,当我使用 /myapp/test 而不是 /myapp/test.html 我的 ContentNegotiatingViewResolver 使用呈现 {}(空花括号)的 json 视图 p>

任何指针都非常感谢。

【问题讨论】:

  • 从您对ContentNegotiatingViewResolver 的配置来看,我无法理解您要达到什么目的。当相同的资源可以以不同的表示形式呈现时,此解析器适用。如果一些资源是用 JSON 呈现,而另一些是 HTML,则需要另外配置解析器。

标签: java rest spring-mvc


【解决方案1】:

不要从控制器返回“/TestStuff.html”,而是尝试返回“redirect:/TestStuff.html”。

另一种选择是为您的静态页面创建和注册视图解析器。也许是这样的:

<bean id="staticViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="prefix" value="/WEB-INF/static/"/>
    <property name="suffix" value=".html"/>
</bean>

【讨论】:

  • 这个“redirect:/TestStuff.html”工作得很好(至少在 Spring MVC 3.1.1 中)......它比添加 viewResolver 更简单,因为我已经为我所有的人定义了一个JSP 页面。
【解决方案2】:

tutorialspoint 有一个很好的完整示例: http://www.tutorialspoint.com/spring/spring_static_pages_example.htm

【讨论】:

    【解决方案3】:

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

    <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"/>
    

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2014-05-31
      • 1970-01-01
      • 2018-07-03
      • 2013-09-22
      • 2017-12-16
      • 1970-01-01
      • 2013-05-27
      • 2012-12-05
      相关资源
      最近更新 更多