Forward to a static html page from Controller
My spri开发者_运维百科ng mvc application has one single ContentNegotiatingViewResolver that defines JsonView for rendering json resonses:
<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>
The whole application sits on root url "myapp". Everything works as I need.
The first question is: how to return a static html page when accessing a certain url? Say, when accessing Spring uri /myapp/test I would like to render an html page /TestStuff.html that resides in root webapp folder.
I went ahead and wrote a simple 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>());
}
}
The get() method is supposed to tell Spring to render a TestStuff.html, but instead I get an error saying that the view with name "/TestStuff.html" is missing.
The second question is how to avoid the necessity to put extension to the URL. In my example, when I use /myapp/test instead of /myapp/test.html my ContentNegotiatingViewResolver uses a json view that renders {} (empty curly braces)
Any pointers are highly appreciated.
Instead of returning "/TestStuff.html" from your controller, try returning "redirect:/TestStuff.html".
Another option is to create and register a view resolver for your static pages. Perhaps something like this:
<bean id="staticViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="prefix" value="/WEB-INF/static/"/>
<property name="suffix" value=".html"/>
</bean>
tutorialspoint has a good complete example of this: http://www.tutorialspoint.com/spring/spring_static_pages_example.htm
The best way to do this is to use InternalResourceViewResolver combined with mvc:view-controller tag (see appropriate Spring Reference Manual for details). Just include the following into your application context XML file (in this case your static file TestStuff.html will be located in /WEB-INF/static-pages directory):
<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"/>
精彩评论