【问题标题】:How to configure @RestController?如何配置@RestController?
【发布时间】:2016-07-26 10:26:27
【问题描述】:

谁能告诉我如何配置@RestController?

我这样做:

@RestController
@EnableAutoConfiguration
public class Application {

    @RequestMapping("/test.htm")
    @ResponseBody
    String home() {
       return "Hello Worlds!";
    }

    public static void main(String[] args) throws Exception {
       SpringApplication.run(Application.class, args);
    }
}

@Controller
public class MusicControler {

    class Test{
        String name;
        int age;
    }

    @RequestMapping(value = "/MyController")
    public Test MyController() {
        Test test = new Test();
        test.name = "zl.shi";
        test.age = 16;
        return test;
    }
}

当我请求 /test.htm 时,没关系,但我收到 /testController.htm 的响应 404。有人可以帮帮我吗?

【问题讨论】:

  • 您尚未为/testController.htm 定义映射,因此无法找到它。
  • 可以使用@RestController 代替@Controller 注解。 @RestController 意味着您从方法返回的任何对象都将作为响应主体发送给调用它的客户端。 @RestController = @Contoller +@ResponseBody .
  • 你没有到/testController.htm的映射,怎么找到?将/MyController 更改为/testController.htm

标签: java spring spring-mvc spring-boot


【解决方案1】:

使用以下代码创建休息控制器

@RestController
@RequestMapping("/service/")  
public class Application {

@RequestMapping(value = "/getmemberdetail/{id}/{info}", method = RequestMethod.GET,  produces = { "application/json" })
    public ResponseEntity<String> getuserdetail(@PathVariable int portalType,@PathVariable("id") int id,@PathVariable("info") String info) throws JsonProcessingException, ParseException{}

}

【讨论】:

  • 为什么这个答案没有用
  • 谢谢!只需将“@SpringBootApplication”添加到应用程序类。
【解决方案2】:

如果你想知道如何使用它,你应该阅读它 Difference between spring @Controller and @RestController annotation 当您制作启动项目spring时,您应该制作另一个要放置控制器的类,不要忘记RestController注释或控制器注释(作为最佳实践,您不应该使用spring boot的启动类)我希望这会有所帮助你

ps 不要标记 spring-mvc 和 spring-boot 这不是一回事

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 2020-05-30
    • 2020-10-02
    • 2021-06-16
    • 2019-02-15
    • 2018-08-29
    • 2022-07-20
    • 2021-04-12
    相关资源
    最近更新 更多