springMVC请求参数绑定代码步骤详解与总结

请求参数绑定(一)简单类型作为参数

分析

举例: http://localhost:8080/user/save.do?id=100&name=jack

servlet中如何获取请求参数: request.getParameter(“id”);

springMVC中:public void save( int id, String name); 处理请求的方法形参名称要与请求参数名称一致。

演示

package com.itheima.controller.c_request_param;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 讲解封装请求参数
 */
@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 请求路径1:http://localhost:8080/user/save.do?id=100&name=jack
     * 访问结果1:100,jack
     *
     * 请求路径2:http://localhost:8080/user/save.do?id=100
     * 访问结果2:100,null
     *
     * 请求路径2:http://localhost:8080/user/save.do
     * 处理方法:public String save(int id,String name){}
     * 访问结果2:报错。 因为int id中的id不能为NULL。
     * 解决: 把参数int,改为Integer
     *        public String save(Integer id,String name){}
     * 注意:
     *    SpringMVC再封装请求数据时候:
     *    1. 请求参数要与方法形参一致(最好)
     *    2. 如果参数为基本类型,最好使用其包装类型。为了避免如果不传参数值为NULL,不能转换为基本类型。
     */
    @RequestMapping("/save")
    public String save(Integer id,String name){
        System.out.println(id + "," + name);
        return "success";
    }
}


请求参数绑定(二)pojo类型作为参数

实现

需求:把请求参数封装到User对象中。

第一步:定义Address对象、User对象添加地址属性、集合属性

1552102200222

在这里插入图片描述

第二步:控制器方法

在这里插入图片描述
第三步:index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>
<body>
    <h3>封装请求数据到对象关联的对象、对象关联的集合对象中</h3>
    <form action="/user/update.do" method="post">
        用户名: <input type="text" name="name">   <br>
        省份:   <input type="text" name="address.province">   <br>
        城市:   <input type="text" name="address.city">   <br>

        省份list:<input type="text" name="list[0].province">   <br>
        城市list:<input type="text" name="list[1].city">   <br>

        省份map:<input type="text" name="map['one'].province">   <br>
        城市map:<input type="text" name="map['one'].city">   <br>

        <input type="submit" value="测试封装请求数据,观察日志">
    </form>
</body>
</html>
  1. springMVC封装请求参数时候,可以把对象类型作为方法参数
  2. 对象中可以有list、map集合属性,也可以关联其他对象。
  3. 注意:如果要把请求数据封装为list、map集合,集合一定要放到对象中。

猜你喜欢

转载自blog.csdn.net/weixin_44594056/article/details/88621983