如何在Spring REST中使用ViewResolver?新手疑问解答
Hey there! Great question—let’s clarify how ViewResolver fits into Spring REST, since it’s a common point of confusion when moving from traditional Spring MVC.
First: Why ViewResolver isn’t the default in Spring REST
Spring REST is all about returning data (like JSON, XML, or plain text) directly in the HTTP response body, rather than rendering a UI page. That’s why we use @RestController (or @Controller + @ResponseBody)—these annotations tell Spring to skip the view resolution step entirely. Instead, Spring uses HTTPMessageConverters to serialize your Java objects into the appropriate format (e.g., JSON via Jackson) and send them straight to the client.
In contrast, traditional Spring MVC uses @Controller without @ResponseBody, where the method returns a view name. ViewResolver then maps that name to a template (like JSP, Thymeleaf) and renders the full HTML page for the client.
When would you use ViewResolver in Spring REST?
You’d typically use ViewResolver in a hybrid scenario where your application needs to handle both REST API requests (returning data) and traditional web requests (returning rendered pages). For example:
- A controller with some methods that return JSON data for mobile apps, and other methods that return HTML pages for a web dashboard.
How to configure ViewResolver in Spring REST
The configuration is actually very similar to traditional Spring MVC—you just need to make sure both ViewResolver and HTTPMessageConverters are set up correctly.
XML Configuration
- Configure your ViewResolver (e.g., for JSPs):
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> - Enable annotation-driven support (which auto-registers default HTTPMessageConverters like Jackson for JSON):
<mvc:annotation-driven/>
Java Configuration
- Define a ViewResolver bean alongside web MVC setup:
The@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } }@EnableWebMvcannotation automatically sets up the default HTTPMessageConverters for you.
Key Notes
- If a method uses
@ResponseBodyor is in a@RestController, Spring will prioritizeHTTPMessageConvertersand won’t trigger ViewResolver. - If you want a REST endpoint to return a rendered HTML page (instead of data), just return a view name as a
Stringfrom a@Controllermethod (without@ResponseBody). ViewResolver will handle rendering the page, and the HTML will be sent as the response body.
内容的提问来源于stack exchange,提问作者K Kishore Kumar Reddy

