SpringMVC中@RestController和@Controller的区别

在使用SpringMVC时,对于Controller中的注解@RestController和@Controller需要我们区分清楚

@RestController注解相当于@ResponseBody和@Controller的结合

但是在使用@RestController注解的时候需要注意几个问题:

1.如果使用@RestController注解Controller,那么该Controller中的方法就无法返回jsp页面,就是说如果在方法中return "xx",那么它只会返回"xx"的内容,因为@RestController中相当于已经有了@RessponseBody的注解效果,所以它无法返回jsp,html界面,配置的InternalResourceViewResolver不工作,只返回return的内容。

2.根据第一条的规定,如果该Controller中需要返回jsp,html界面,那么就需要使用@Controller注解Controller,不能用@RestController。

3.第一条中说到@RestController注解的Controller只返回return中的内容,所以如果我们在Controller方法中需要返回JSON、XML或者我们自己定义的类型到页面中,那么就需要使用@ResponseBody注解该方法。
 

package geektime.spring.hello.hellospring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
//@RestController
@Controller
public class HelloSpringApplication {

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

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello Spring";
    }

}
package geektime.spring.hello.hellospring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
//@Controller
public class HelloSpringApplication {

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

    @RequestMapping("/hello")
    //@ResponseBody
    public String hello() {
        return "Hello Spring";
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值