實(shí)體類

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

后臺(tái)控制器

@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) {//前臺(tái)頁面?zhèn)鬟f過來的數(shù)據(jù)會(huì)自動(dòng)實(shí)例化        Dept dept = new Dept(deptno, dname, loc);        return new ModelAndView("/res", "res", dept);    }    @RequestMapping("/add3")    public ModelAndView add3(Dept dept) {//前臺(tái)頁面?zhèn)鬟f過來的數(shù)據(jù)會(huì)自動(dòng)實(shí)例化        System.out.println(dept);        return new ModelAndView("/res", "res", dept);    }    @RequestMapping("add4")    public void add4(Dept dept, HttpServletResponse response) throws IOException {// 變量的名稱無所謂,不是必須得和前臺(tái)頁面一致,只要類型不錯(cuò)就行了        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 {// 變量的名稱無所謂,不是必須得和前臺(tái)頁面一致,只要類型不錯(cuò)就行了        return dept;    }}

普通表單

示例一:后臺(tái)通過HttpServletRequest獲取

示例二:后臺(tái)通過具體的屬性獲取

示例三:后臺(tái)通過具體的對(duì)象獲取

示例四:后臺(tái)通過具體的屬性獲取

前臺(tái)以JSON方式傳遞數(shù)據(jù)

后臺(tái)通過具體的對(duì)象獲取

指定contentType

網(wǎng)頁通過JSON形式向后臺(tái)傳遞數(shù)據(jù)

網(wǎng)頁通過key/value形式向后臺(tái)傳遞數(shù)據(jù)

注:

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

    • 如果不指定contentType,后臺(tái)會(huì)將接收到的value值賦給Controller方法的對(duì)象參數(shù)(或封裝后賦給Controller方法的對(duì)象參數(shù)):
    • 如果指定contentType,后臺(tái)只能將接收到的value值賦給Controller方法的對(duì)應(yīng)參數(shù)
  • contentType: "application/json;charset=UTF-8"
    • 如果不指定contentType,1-5都行
    • 如果指定contentType,只能通過add獲取參數(shù)的值
    • 若控制器方法對(duì)象參數(shù)前面加@RequestBody@RequestParam,會(huì)報(bào)xhr

故:實(shí)際項(xiàng)目中,不建議指定contentType,省得為自己找麻煩