View Controllers

这是一个快捷方式,用于在调用时立即转发到视图的ParameterizableViewController。你可以在静态情况下使用它,当时在视图生成响应之前没有Java控制器逻辑要运行。

This is a shortcut for defining a ParameterizableViewController that immediately forwards to a view when invoked. You can use it in static cases when there is no Java controller logic to run before the view generates the response.

以下示例将对/的请求转发到名为home的视图:

The following example forwards a request for / to a view called home:

  • Java

  • Kotlin

  • Xml

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("home");
	}
}
@Configuration
class WebConfiguration : WebMvcConfigurer {

	override fun addViewControllers(registry: ViewControllerRegistry) {
		registry.addViewController("/").setViewName("home")
	}
}
<mvc:view-controller path="/" view-name="home"/>

如果将一个 @RequestMapping 方法映射到任何 HTTP 方法的 URL,那么就无法使用视图控制器来处理相同的 URL。这是因为,通过 URL 匹配到带有注释的控制器被认为是最终点所有权的足够强烈的指示,因此可以向客户端发送 405(METHOD_NOT_ALLOWED)、415(UNSUPPORTED_MEDIA_TYPE)或类似的响应来帮助调试。因此,建议避免在带有注释的控制器和视图控制器之间拆分 URL 处理。

If an @RequestMapping method is mapped to a URL for any HTTP method then a view controller cannot be used to handle the same URL. This is because a match by URL to an annotated controller is considered a strong enough indication of endpoint ownership so that a 405 (METHOD_NOT_ALLOWED), a 415 (UNSUPPORTED_MEDIA_TYPE), or similar response can be sent to the client to help with debugging. For this reason it is recommended to avoid splitting URL handling across an annotated controller and a view controller.