@Controller和@RestController的区别(Restful风格)

Controller和RestController的联系与区别

一般使用注解开发的情况下,我们都会在Controller层使用Controller相关的注解,目的是标记这是一个控制类,同时讲它注入到spring容器中,此时需要在spring容器中开启扫描包的功能。那么@Controller与@RestController的区别如下:
在每个映射方法之后都会有一个返回值,@Controller是跳转到返回值对应的页面,而@RestController则是向请求页面返回数据。举个例子来说:
首先写一个hello页面显示后台传过来的数据:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${name}
</body>
</html>

使用@COntroller注解标识controller:

@Controller
public class RestfulController{
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("name","张三");
        return "hello";
    }
}

结果页面显示的是张三:
@Controller和@RestController的区别(Restful风格)_第1张图片

然后使用@RestController:

@RestController
public class RestfulController{
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("name","张三");
        return "hello";
    }
}

结果是这样的:
@Controller和@RestController的区别(Restful风格)_第2张图片
你悟了吗?
当然RestController也有方法可以实现页面跳转,将返回值由String改为ModelAndView,跳转到请求页面,写法如下:

@RestController
class testModelAndView{
    @RequestMapping("/hello2")
    public ModelAndView hello(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("name","张三");
        return modelAndView;
    }
}

②RestController使用Restful风格;
以前我们在页面传参数时url地址栏是这样显示的:
localhost://8080/hello?id=123&name=张三
而Restful风格是这样的
localhost://8080/hello/id/123/name/张三
通过下面的方式可获取到前端的参数值:

@RestController
public class RestfulController {
        @RequestMapping("/hello/{a}/{b}")           //默认以get方式提交
        public String getSum(@PathVariable int a, @PathVariable("b") int b){
            return "sum: "+(a+b);
        }
        @PostMapping("hello/{a}/{b}")
        public String getDe(@PathVariable int a,@PathVariable int b){
            return "de: "+(a-b);
        }
}

可以看到这两个映射方法的请求路径是一样的,由于请求方式的不同,可以将他们区别开来,也就是当前端请求是post请求是执行@PostMapping对应的方法,默认是get请求。
在方法参数前加上@PathVariable无参注解说明方法参数与请求的参数同名,如不同名需要在@PathVariable注解中加上参数指定该方法参数使用的是哪个请求参数。

你可能感兴趣的:(SSM,springmvc,restful)