【问题标题】:Spring boot @RequestMapping annotationSpring启动@RequestMapping注解
【发布时间】:2017-05-15 21:17:15
【问题描述】:

我正在开发一个 Angular2 + Spring Boot 应用程序,目前我有:
后端:1 个@RestController,带有用@RequestMapping 注释的方法,例如。

@RequestMapping("/main")
public Band[] main(@RequestParam(value="numberOfBands", required=false, defaultValue="3") int numberOfBands) throws ClientProtocolException, IOException {          
    return random(numberOfBands);
}  

前端:app.routing.ts,重定向到'/main'
{ path: '', redirectTo: 'main', pathMatch: 'full' },
初始化后,我的 main.component.ts 向 spring 发送请求并获取对象数组作为响应;组件如下所示:

export class MainComponent  {
  bands: Band[];
  errorMessage: string;
  constructor(private bandService: BandService){
    //this.bands = new Array(3);
    bandService.getRandomBands(3)
    .subscribe(
       bands => this.bands = bands,
       error =>  this.errorMessage = <any>error);
  }
}    

当转到http://localhost:8090/ 时,应用程序会重定向到/main,并且波段会被组件正确传递和解析。但是每当我尝试重新加载页面 http://localhost:8090/main 时,我只会得到纯 JSON,这看起来我的组件没有正确初始化。
我希望 Spring Boot 忽略地址栏中的路径,因此它只与客户端相关。
问题是:这是服务器端的问题,还是我以不适当的方式初始化了我的组件?

更新
我为我的所有@RequestMappings 添加了前缀“/api”并添加了一个过滤器,如下所示('equals' 只是为了测试功能):

if(requestURI.equals("/main")){
        RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher("/");
        requestDispatcher.forward(req, res);
    }
    chain.doFilter(req, res);         

之后,转发过程按预期进行。

【问题讨论】:

    标签: spring spring-mvc angular spring-boot angular2-template


    【解决方案1】:

    刷新总是会向服务器发送请求。将所有 REST API 后端放在特定路径下,例如 /api/...,这样 Angular 应用程序使用的“假” URL 不会与后端的真实 URL 发生冲突。

    然后配置一个过滤器,以便将所有对那些“假”角 URL 的请求转发到/index.html

    因此,对/main 的请求将被您的过滤器拦截,并转发到 index.html。角度应用程序将启动。路由器将转到/main 的路由。该组件将向/api/main 发送一个AJAX 请求。此请求将不会被过滤器转发到 /index.html,因此 Spring REST 控制器将处理它并提供 JSON。

    【讨论】:

    • 不会让spring返回null作为视图,因此客户端不会被初始化吗?
    • 你的意思是,当过滤器转发到 index.html 时?你能澄清你在问什么吗?
    • 我尝试按照您的回答进行操作,但是当 Spring Boot 应用程序将请求重定向到 index.html 时,该值没有 requestMapping。所以我加了那个requestMapping方法,它返回void,但是由于返回的view是null,所以angular app没有初始化。
    • 我从未说过要重定向到 index.html。我说要转发到/index.html。如果您需要更多帮助,请编辑您的问题、发布您的代码并解释问题所在,并提供所有必要的详细信息。
    猜你喜欢
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    相关资源
    最近更新 更多