简体   繁体   English

Spring Boot @RestController和@Controller

[英]Spring Boot @RestController and @Controller

I have a @Controller: 我有一个@Controller:

@Controller("/")
public class GreetingController {

  @GetMapping("/greeting")
  public String get() {
    return "greeting";
  }
}

Also a @RestController: 还有一个@RestController:

@RestController("/test")
public class TestRest {

  @RequestMapping()
  public List<TestDTO> get() {
    List<TestDTO> dtos = new ArrayList<>();
    dtos.add(new TestDTO("value1","value2"));
    dtos.add(new TestDTO("value1","value2"));
    return dtos;
  }
}

The @Controller works correctly, and serves a static HTML page at src/main/resources/templates/greeting.html @Controller可以正常工作,并在src/main/resources/templates/greeting.html提供静态HTML页面

But the @RestController does not work, all I get are 404s. 但是@RestController不起作用,我得到的都是404。

If I move the method from the @RestController into the @Controller and add a @ResponseBody annotation, it then starts working. 如果我将方法从@RestController移到@Controller并添加@ResponseBody批注,则它将开始工作。

How can I have the controllers as different classes? 如何将控制器设置为不同的类?

@RestController and @Controller do not take the path to the resource as a parameter. @RestController@Controller不会将资源路径作为参数。 Perhaps try something along the lines of... 也许尝试一些类似...

@RestController
@RequestMapping("/test")
public class TestRest {

  @RequestMapping(method = RequestMethod.GET)
  public List<TestDTO> get() {
    List<TestDTO> dtos = new ArrayList<>();
    dtos.add(new TestDTO("value1","value2"));
    dtos.add(new TestDTO("value1","value2"));
    return dtos;
  }
}

You question itself has the answers, for the RESTController to work, you would need to have a @ResponseBody because, for all REST calls, there needs to be response body to return the data. 您自己想知道答案,要使RESTController正常工作,您将需要有一个@ResponseBody,因为对于所有REST调用,都需要有响应主体才能返回数据。 I hope adding @ResponseBody alone will solve the problem. 我希望单独添加@ResponseBody可以解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM