Spring Boot注解

来源:互联网 发布:如何开淘宝童装店 编辑:程序博客网 时间:2024/06/14 10:38

1.@responseBody
将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。在使用此注解之后直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
例如:

@RequestMapping("/login")@ResponseBodypublic User login(User user){    return user;}

User字段:userName、pwd
那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}'
效果等同于如下代码:

@RequestMapping("/login")public void login(User user, HttpServletResponse response){    response.getWriter.write(JSONObject.fromObject(user).toString());}

2.@RequestBody
将HTTP请求正文转换为适合的HttpMessageConverter对象。

  • GET、POST方式
    根据request header Content-Type的值来判断:
    application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
    multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
    其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

  • PUT方式提交时。
    根据request header Content-Type的值来判断:
    application/x-www-form-urlencoded, 必须;
    multipart/form-data, 不能处理;
    其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定。


3.@Param
使用时:
当以下面的方式进行写SQL语句时:

    @Select("select column from table where userid = #{userid} ")    public int selectColumn(int userid);

使用@Param注解来声明参数时,如果使用 #{} 或 ${} 的方式都可以。

    @Select("select column from table where userid = ${userid} ")    public int selectColumn(@Param("userid") int userid);

不使用@Param注解时,必须使用使用 #{}方式。如果使用 ${} 的方式,会报错。

    @Select("select column from table where userid = ${userid} ")    public int selectColumn(@Param("userid") int userid);

不使用时:
参数只能有一个,并且是Javabean。在SQL语句里可以引用JavaBean的属性,而且只能引用JavaBean的属性。
// 这里id是user的属性

    @Select("SELECT * from Table where id = ${id}")    Enchashment selectUserById(User user);
原创粉丝点击