實體類

@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,省得為自己找麻煩