My spring 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.
We can use a name such as a redirect: http://localhost:8080/spring-redirect-and-forward/redirectedUrl if we need to redirect to an absolute URL.
@RestController public class RedirectController { @RequestMapping("/redirect") public String redirect() { return "redirect:/other/controller/"; } } and if we will try to access that url curl localhost:8080/redirect we will simply see redirect:/other/controller/ string as result.
@RestController is not meant to be used to return views to be resolved. It is supposed to return data which will be written to the body of the response, hence the inclusion of @ResponseBody .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With