gpt4 book ai didi

java - spring中将@Controller替换为@RestController的效果

转载 作者:行者123 更新时间:2023-12-02 02:00:58 25 4
gpt4 key购买 nike

能否将@Controller替换为@RestController,反之亦然,对应用有何影响。

最佳答案

简单来说,@Controller 是 Spring MVC 注释,在使用 @Controller 时,您需要为每个请求映射添加 @ResponseBody`

示例:

 @Controller
@RequestMapping("employees")
public class EmployeeController {
Employee employee = new Employee();
@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) {
employee.setName(name);
employee.setEmail("employee1@genuitec.com");
return employee;
}
@RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml")
public @ResponseBody Employee getEmployeeInXML(@PathVariable String name) {
employee.setName(name);
employee.setEmail("employee1@genuitec.com");
return employee;
}
}

Spring 4.0引入了@RestController,这是 Controller 的一个特殊版本,它是一个方便的注释,除了添加@Controller@ResponseBody 注释。通过使用@RestController注解来注解 Controller 类,您不再需要在所有请求映射方法中添加@ResponseBody。

示例:

 @RestController
@RequestMapping("employees")
public class EmployeeController {
Employee employee = new Employee();
@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
public Employee getEmployeeInJSON(@PathVariable String name) {
employee.setName(name);
employee.setEmail("employee1@genuitec.com");
return employee;
}
@RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml")
public Employee getEmployeeInXML(@PathVariable String name) {
employee.setName(name);
employee.setEmail("employee1@genuitec.com");
return employee;
}
}

所以最后的结论是,如果您想用 @Controller 替换 @RestController ,您需要显式地将 @ResponseBody 添加到所有请求映射中

关于java - spring中将@Controller替换为@RestController的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com