Do not resolve view in RESTful Application

2019-04-30 19:09发布

问题:

I am building a web application with RESTful web services using Spring MVC 3. The web services will be used by applications, so should never really resolve any requests to a view. Is there any way to specify in the servlet context that no requests should resolve to any view?

At the moment, I have:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

which I know tries to resolve any request to a correspondingly named view in the jsp folder. However, if I remove this, the application just tries to use a default view resolver.

The reason I am concerned about this is that my application logs are going to be full of the following messages (even though it works fine):

SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with path [/vouchd] threw exception [Circular view path [signup]: would dispatch back to the current handler URL [/vouchd/signup] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause
javax.servlet.ServletException: Circular view path [signup]: would dispatch back to the current handler URL [/vouchd/signup] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

or with the InternalViewResolver:

WARN [http-bio-8080-exec-4] (DispatcherServlet.java:1057) - No mapping found for HTTP request with URI [/app/WEB-INF/jsp/call.jsp] in DispatcherServlet with name 'DispatcherServlet'

which I guess is the better of the two evils. I don't want to turn off logging WARN level.

回答1:

Try with @ResponseStatus. This code returns 204 with no content and view resolving skipped:

@ResponseStatus(NO_CONTENT)
void noView() {
  //...
}

If you want to return raw data and simply serialize it to JSON or XML, use @ResponseBody:

@ResponseBody
MyPojo noView() {
  return new MyPojo();
}