【问题标题】:Spring RequestMapping with root path (/{custom})带有根路径的 Spring RequestMapping (/{custom})
【发布时间】:2016-10-20 12:14:34
【问题描述】:

假设我的网站名称是:foo.com

当用户键入 foo.com 时,我想显示 index.html。

当用户键入 foo.com/something 时,我希望服务器在控制器处捕获请求。

这是我在 HomeController 中所做的:

@Controller
public class HomeController {
    @RequestMapping(value={"/"}, method=RequestMethod.GET)
    public String getHome() {
        return "index.html";
    }
}

而且,CustomController 应该捕获请求

@Controller
public class CustomController {
    @RequestMapping(value={"/{custom}"}, method=RequestMethod.GET)
    public String getCustom(@PathVariable String custom) {
        // Do something here..
    }
}

但是,它会抛出一个错误:Circular view path [index.html]: will dispatch back to the current handler URL [/index.html] again. 这是因为 CustomController 捕获了 GET 请求: foo.com/index.html HomeController 返回字符串后:index.html.

我做了一些这样的研究:

public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets"); // My asset
        registry.addResourceHandler("index.html").addResourceLocations("file:/index.html");
    } // It's not working

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/" + FileNames.INDEX);
    } // This also not working
} 

并且在 CustomController 中将注解从 @Controller 更改为 @RestController 不是一种选择。

另外,我的项目中没有 JSP 文件——它们是纯 *.html 文件。

我正在使用 Spring 1.3.3 版本,所以请帮帮我。

【问题讨论】:

    标签: spring spring-mvc spring-boot


    【解决方案1】:

    此解决方案适用于 ui-router(AngularJS 库)。此外,您必须更改 $resourceProvider 设置:

    // In your app module config
    $resourceProvider.defaults.stripTrailingSlashes = false;
    

    然后,在 Spring 服务器代码中,您可以这样做:

    @RequestMapping(value = "/{custom:[^\\.]*}")
    public String redirect(@PathVariable String custom) {
      // Do something here...
      return "forward:/";
    }
    

    在此链接找到解决方案:https://spring.io/blog/2015/05/13/modularizing-the-client-angular-js-and-spring-security-part-vii

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-03
      • 2011-04-10
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      相关资源
      最近更新 更多