[英]How Can Spring MVC Handle Requests to URLs Generated by the Angular Router?
I have a Spring (v, 4.3.2 & Java 8) application that serves up an Angular2 single page application front end that has multiple routes (say /foo
, /bar
and /baz
, one of which requires a parameter to render ( /baz/x
where x is the identifier of the resource to retrieve). 我有一个Spring(v,4.3.2和Java 8)应用程序,它为Angular2单页应用程序前端提供服务,该前端具有多个路由(例如/foo
, /bar
和/baz
,其中之一需要一个参数来呈现( /baz/x
,其中x是要检索的资源的标识符)。
The html is served up with a standard Spring MVC @Controller
: html由标准Spring MVC @Controller
:
@RequestMapping(value = {"/", "/foo", "/bar", "/baz/{id}"}, method = RequestMethod.GET)
public String index(@PathVariable Optional<String> id) {
return "index";
}
and views are resolved using: 并使用以下命令解决视图:
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
If the browser reloads from the /
, /foo
or /bar
routes, the controller properly returns the index
page and angular resolves the view for the route as expected. 如果浏览器从/
, /foo
或/bar
路由重新加载,则控制器会正确返回index
页,并且angular会按预期解析该路由的视图。 However, if the browser reloads from one of the baz
routes that contain a paramenter, the server prepends baz
to the resource path (eg /baz/WEB-INF/pages/index.jsp
) which, results in a 404 error. 但是,如果浏览器从包含参数的baz
路由之一重新加载,则服务器会将baz
/baz/WEB-INF/pages/index.jsp
到资源路径(例如/baz/WEB-INF/pages/index.jsp
),这将导致404错误。
I've tried refactoring the baz
request mappings info into an annotation on a distinct (identical) method and using wildcards in the request mapping (eg /**
and baz/*
), but always get the same result. 我尝试将baz
请求映射信息重构为不同(相同)方法上的注释,并在请求映射中使用通配符(例如/**
和baz/*
),但始终得到相同的结果。 Regardless of the request mapping, Spring seems unaware that it is appending baz
into the path, as the logs contain: 不管请求映射如何,Spring似乎都不知道它会将baz
附加到路径中,因为日志包含:
DEBUG: org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.InternalResourceView: name 'index'; URL [WEB-INF/pages/index.jsp]] in DispatcherServlet with name 'dispatcher'
DEBUG: org.springframework.web.servlet.view.InternalResourceView - Forwarding to resource [WEB-INF/pages/index.jsp] in InternalResourceView 'index'
DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request
Any help on this would be appreciated. 任何帮助,将不胜感激。
Solved the problem - omitting the leading slash from the prefix argument string causes the issue. 解决了问题-从前缀参数字符串中省略前导斜杠会导致问题。 For proper configuration the argument should be: 为了正确配置,参数应为:
viewResolver.setPrefix("/WEB-INF/pages/");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.