spring boot之@Controller和@RestController区别及应用

@Controller和@RestController区别:

在springboot开发中控制层使用注解@Controller时,加有@GetMapping(@PostMapping或@RequestMapping)注解的方法返回值对应的是一个视图,而使用@RestController返回值对应的是json数据,而@Controller+@ResponseBody的作用相当于@RestController。

@Controller的应用

先在application.properties配置文件中配置

spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html

然后在控制层CustomerController类的代码为

@Controller
public class CustomerController {
    @Resource
    CustomerServiceI customerServiceI;
    @GetMapping("/")
    public String index() {
        return "redirect:/list";
    }
    @GetMapping("/list")
    public String list(Model model) {
        List<Customer> users = customerServiceI.getUserList();
        model.addAttribute("users",users);
        return "list";
    }
}

启动程序后在浏览器输入localhost:8080/list访问页面即为templates文件夹下的list.html
这里写图片描述

@RestController的应用

控制层CustomerController类的代码为

@RestController
public class CustomerController {
    @Resource
    CustomerServiceI customerServiceI;
    @GetMapping("/")
    public String index() {
        return "redirect:/list";
    }
    @GetMapping("/list")
    public List<Customer> list(Model model) {
        List<Customer> users = customerServiceI.getUserList();
        model.addAttribute("users",users);
        return users;
    }
}

启动程序后在浏览器输入localhost:8080/list访问效果如下
这里写图片描述

猜你喜欢

转载自blog.csdn.net/chenbingbing111/article/details/81070829
今日推荐