在使用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";
}
}