我的 spring mvc 应用程序有一个 ContentNegotiatingViewResolver,它定义了 JsonView 以呈现 json 响应:
<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 :
@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”的 View 丢失。
第二个问题是如何避免对 URL 进行扩展。在我的示例中,当我使用 /myapp/test 而不是 /myapp/test.html 时,我的 ContentNegotiatingViewResolver 使用呈现 {}(空花括号)的 json View p>
非常感谢任何指点。
最佳答案
不要从 Controller 返回“/TestStuff.html”,而是尝试返回“redirect:/TestStuff.html”。
另一种选择是为您的静态页面创建并注册一个 View 解析器。也许是这样的:
<bean id="staticViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="prefix" value="/WEB-INF/static/"/>
<property name="suffix" value=".html"/>
</bean>
关于java - 从 Controller 转发到静态 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4052384/