@Controller:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";
}
@RestController:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
* @since 4.0.1
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}
@RestController注解是@Controller和@ResponseBody的组合使用
Controller相当于dispatcherServlet(实现servlet接口)+Model(填充了数据的模型/模板类)
@Controller执行过程
控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View ()进行展示。@RequestMapping("/xxx")使得该controller能被外界进行访问,相当于servlet中的url映射,或者@WebServlet注解。用@Controller初始化一个controller,用@RequestMapping给出它的访问路径,或者说触发路径 ,触发条件。
@ResponseBody
@ResponseBody注解会告知Spring,我们将要返回的对象作为资源发送给客户端,这个过程跳过正常的模型/视图流程中视图解析的过程,而是使用Spring自带的各种Http消息转换器将控制器产生的数据转换为客户端需要的表述形式,写入到response对象的body区,通常用来返回JSON数据或者是XML数据,直接将数据写入到输出流(InputStream(字节输入流),或者抽象类Reader(字符输入流),抽象类OutputStream(字节输出流)或者Writer(字符输出流))中,他的效果等同于通过response对象输出指定格式的数据,如:
//实体类User
public class User{private String UserName;private String password;get,set方法}
//伪代码举例
@RequestMapping("/login")
@ResponseBody
public User login(User user){
return user;
}
那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}'
效果等同于如下代码:
@RequestMapping("/login")
public void login(User user, HttpServletResponse response){
response.getWriter.write(JSONObject.fromObject(user).toString());
}
虽然函数有return值,但加了@ResponseBody,可将其当成void型函数来理解
@ResponseBody表示方法的返回值直接以指定的格式写入Http response body中,进而将数据返回给客户端。当方法上面没有写ResponseBody,底层会将方法的返回值封装为ModelAndView对象。
格式的转换是通过HttpMessageConverter中的方法实现的,因为它是一个接口,因此由其实现类完成转换。
如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
如果要求方法返回的是json格式数据,而不是跳转页面,则需要在对应的方法上加上@ResponseBody注解,或可以直接在类上标注@RestController,而不用在每个方法中标注@ResponseBody,简化了开发过程。