实体类

@Datapublic class Dept {    private Integer deptno;    private String dname;    private String loc;}

后台控制器

@Controller@RequestMapping("/dept")public class DeptController {    @RequestMapping("/add")    void add(HttpServletRequest request){        try {            ServletInputStream is = request.getInputStream();            String result = new BufferedReader(new InputStreamReader(is))                    .lines().collect(Collectors.joining(System.lineSeparator()));            System.out.println(result);        } catch (IOException e) {            e.printStackTrace();        }    }    @PostMapping(value = "/add1")    public ModelAndView add1(HttpServletRequest request) {        String deptno = request.getParameter("deptno");        String dname = request.getParameter("dname");        String loc = request.getParameter("loc");        Dept dept = new Dept(Integer.parseInt(deptno), dname, loc);        return new ModelAndView("/res", "res", dept);    }    @PostMapping("/add2")    public ModelAndView add2(Integer deptno, String dname, String loc) {//前台页面传递过来的数据会自动实例化        Dept dept = new Dept(deptno, dname, loc);        return new ModelAndView("/res", "res", dept);    }    @RequestMapping("/add3")    public ModelAndView add3(Dept dept) {//前台页面传递过来的数据会自动实例化        System.out.println(dept);        return new ModelAndView("/res", "res", dept);    }    @RequestMapping("add4")    public void add4(Dept dept, HttpServletResponse response) throws IOException {// 变量的名称无所谓,不是必须得和前台页面一致,只要类型不错就行了        response.setContentType("application/json");        PrintWriter out = response.getWriter();        ObjectMapper objectMapper = new ObjectMapper();        String json = objectMapper.writeValueAsString(dept);        out.write(json);    }    @ResponseBody    @RequestMapping("add5")    public Dept add5(Dept dept) throws IOException {// 变量的名称无所谓,不是必须得和前台页面一致,只要类型不错就行了        return dept;    }}

普通表单

示例一:后台通过HttpServletRequest获取

示例二:后台通过具体的属性获取

示例三:后台通过具体的对象获取

示例四:后台通过具体的属性获取

前台以JSON方式传递数据

后台通过具体的对象获取

指定contentType

网页通过JSON形式向后台传递数据

网页通过key/value形式向后台传递数据

注:

  • contentType: "application/x-www-form-urlencoded"

    • 如果不指定contentType,后台会将接收到的value值赋给Controller方法的对象参数(或封装后赋给Controller方法的对象参数):
    • 如果指定contentType,后台只能将接收到的value值赋给Controller方法的对应参数
  • contentType: "application/json;charset=UTF-8"
    • 如果不指定contentType,1-5都行
    • 如果指定contentType,只能通过add获取参数的值
    • 若控制器方法对象参数前面加@RequestBody@RequestParam,会报xhr

故:实际项目中,不建议指定contentType,省得为自己找麻烦