使用 AngularJS 配置 Spring MVC

2024-03-28

我希望能够使用 Spring MVC 作为 REST 服务器,并在客户端使用 AngularJS。

我有几个 REST 网址:

  • /休息/产品
  • /休息/产品/{id}

我有几个 UI 网址:

  • /商店/产品
  • /商店/产品/{id}

由于 AngularJS 在客户端完成了这个任务,我只是希望能够将所有默认的 ui url(而不是其余的)重定向到 AngularJS 使用的 index.html 文件。

所以,在 Spring MVC 配置中,我希望能够做类似的事情:

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.mypackage.web")
public class WebAppConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/**").setViewName("index");
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

这样,我想将所有 UI url 处理委托给 AngularJS。

我还希望,如果用户在浏览器中写了一个错误的 url,他将被 Spring MVC 在 index.html 文件上重定向,并且 AngularJS 将在错误 ui 页面上执行重定向。我在网上看到过几个项目只有一个index.html 文件,但没有人处理这个错误情况。

我一直在努力尝试这个技巧,但我找不到解决方案。

所以我的问题是:我该怎么做?更一般地说,我对这个 Spring MVC-AngularJS 想要的配置有错吗?

非常重要:我使用 Spring MVC 3.2 和 Tomcat 7.34,没有 web.xml (完整的 Servlet 3.0)

多谢。


也许可以通过以下方式解决$routeProvider http://docs.angularjs.org/api/ng.%24routeProvider:

$routeProvider.when('/redirect/:redirectParams', {templateUrl: 'partials/homePartial', controller: redirectController});
$routeProvider.when('/home', {templateUrl: 'partials/homePartial', controller: homeController});
$routeProvider.when('/someRoute', {templateUrl: 'partials/somePartial', controller: someController});
$routeProvider.when('/error/', {templateUrl: 'partials/errorPartial', controller: errorController});
$routeProvider.when('/error/:errorMessage', {templateUrl: 'partials/errorPartial', controller: errorController});
$routeProvider.otherwise({redirectTo: '/error'})

只要让$routeProvider当找不到路由时重定向到错误页面。

Edit:

我在上面的例子中添加了一个redirectController。该控制器将读取$routeParams, 在这种情况下$routeParams.redirectParams并使用$地点 http://docs.angularjs.org/api/ng.%24location将路线更改为/error.

Spring 只是重定向到http://host:port/index.html/#/redirect/error=blabla。您可以而且应该对此进行微调并支持多个routeParams。

在春天你基本上会有三个请求映射 http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html:

  • REST 请求映射 http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch18s02.html
  • index.html 请求映射
  • 其他url请求映射

重定向所有其他请求:

@RequestMapping(value = "{path}", method = RequestMethod.GET)
public String redirect(@PathVariable String path) {
   String route = null;
   if (path.equals("/") || path.startsWith("/index.html")) {
     // load index.html
   } else {
     route = "redirect:/index.html/#/redirect/" + path; 
   }
   return route;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 AngularJS 配置 Spring MVC 的相关文章

随机推荐