美文网首页
Spring @RestController、@Controll

Spring @RestController、@Controll

作者: KardelShaw | 来源:发表于2018-04-19 18:57 被阅读0次

一、用@Controller,返回的是页面;@Controller加上@ResponseBody,返回的是JSON、XML或其他文本。

@Controller
@RequestMapping("/test")
public class MyController1 {
    
    @ResponseBody
    @GetMapping(path="/get1", produces = "text/plain;charset=utf-8")
    public String getMethod1(String str) {
        return str;
    }

    @GetMapping(path="/get2", produces = "text/plain;charset=utf-8")
    public String getMethod2(String str) {
        return str;
    }
}

访问 /test/get1,并携带参数 str="index" ,返回 index 字符串。
访问 /test/get2,并携带参数 str="index" ,返回名为 index 页面,如index.jsp。

二、用@RestController,意味着这个Controller的所有方法上面都加了@ResponseBody,不论你在每个方法前加、或不加@ResponseBody,都一样。所以这种Controller不会返回页面。

@RestController
@RequestMapping("/test")
public class MyController1 {
    
    @ResponseBody
    @GetMapping(path="/get1", produces = "text/plain;charset=utf-8")
    public String getMethod1(String str) {
        return str;
    }

    @GetMapping(path="/get2", produces = "text/plain;charset=utf-8")
    public String getMethod2(String str) {
        return str;
    }
}

访问 /test/get1,并携带参数 str="index" ,返回 index 字符串。
访问 /test/get2,并携带参数 str="index" ,返回 index 字符串。

参考文章

@Controller和@RestController的区别?

相关文章

网友评论

      本文标题:Spring @RestController、@Controll

      本文链接:https://www.haomeiwen.com/subject/drxgkftx.html