【发布时间】: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