GET,POST请求,常见的数据编码格式

当前台页面使用GET或POST方式提交数据时,数据编码格式由请求头的ContentType指定。而dataType请求头,则是预期服务器返回的数据格式。

通常可以分为以下几种数据编码格式:

  • application/x-www-form-urlencoded,这种情况下的数据可以使用@RequestParam处理,也可以使用@RequestBody来处理。
  • multipart/form-data ,@RequestBody不能处理这种格式的数据。
  • application/json 或者 application/xml,必须使用@RequestBody来处理

如果客户端发送到服务端的数据格式是一个json对象,即请求的ContentType="application/json",发送的数据类似JSON.stringify({id:1,name:"zhangsan"})这样的数据,(ps:利用ajax可以发送类似的请求),那么,此时,我们可以用@RequestBody注解来很容易的解析里面的数据。

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.df.test.pojo.Customer;
import com.df.test.service.ICustomerService;

@Controller
@SessionAttributes("user")//将Model 中属性名为user的属性,放进HttpSession当中
public class UserController {
    @Resource
    private ICustomerService customerService;

    @RequestMapping("/showUser1")
    public String toIndex(@RequestBody User user, Model model) {
        Customer customer = this.customerService.getUserById(Integer.parseInt(user.getId()));
        model.addAttribute("user", customer);//将user添加到Model当中,用该函数添加的属性,默认进入视图的requestScope作用域中,因为@SessionAttributes注解的缘故,此时视图的sessionScope作用域也存在user对象。
        return "showUser";
    }
}

@RequestBody,可以直接解析出来对象用来用。

你可能感兴趣的:(GET,POST请求,常见的数据编码格式)