java - 从 Controller 转发到静态 html 页面

标签 java rest spring-mvc

我的 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 使用呈现 {}(空花括号)

非常感谢任何指点。

最佳答案

不要从 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/

相关文章:

Java 正则表达式问题 - 无法匹配同一行中的两个字符串

ruby-on-rails - API 的 URL 设计

java - 具有 Sum 函数的 Spring 规范

java - Spring hibernate : Illegal attempt to associate a collection with two open sessions

java - Java 中分离的前端和后端 - Spring MVC 框架

java - Graphics2D 和 GraphicsContext 之间的互操作性

java - 文件打开时出现 Eclipse NullPointerException

java - 单个 RMI stub 与多个

java - 在wildfly中分别部署JPA和REST包

.net - 使用 .NET 4 客户端配置文件使用 REST 服务