当前位置: 首页 > news >正文

Spring MVC 数据绑定教程

一、数据绑定概述

将HTTP请求中的表单数据自动映射到Controller方法的参数中,支持多种数据类型绑定。


二、自动绑定数据类型
2.1 基本数据类型绑定

支持类型

  • 基本类型:int, double
  • 包装类:Integer, Double
  • String 类型

实现步骤

  1. 创建表单(JSP)
<form action="/demo01/demo01" method="post">
  <input type="text" name="id" placeholder="城市ID"/>
  <input type="text" name="cityName" placeholder="城市名称"/>
  <input type="text" name="GDP" placeholder="城市GDP"/>
  <input type="text" name="capital" placeholder="是否是省会"/>
  <input type="submit" value="提交"/>
</form>

  1. 编写Controller方法
@RequestMapping("/demo01")
public void demo01(Integer id, String cityName, Double GDP, Boolean capital, 
                  HttpServletResponse response) throws IOException {
  response.setContentType("text/html;charset=utf-8");
  response.getWriter().write("ID: " + id);
  response.getWriter().write("City: " + cityName);
}

注意事项

  • 表单字段名需与方法参数名一致
  • 空值会绑定为null(包装类允许为空)

2.2 实体类绑定

实体类定义

@Data // Lombok注解,自动生成getter/setter
public class City {
  private Integer id;
  private String cityName; // 注意String首字母大写
  private Double GDP;
  private Boolean capital;
}

Controller实现

@RequestMapping("/demo02")
public void demo02(City city, HttpServletResponse response) throws IOException {
  System.out.println(city); // 自动绑定表单数据到City对象
}

表单要求
字段名需与实体类属性名完全一致。


2.3 集合与数组绑定
2.3.1 数组绑定

Controller方法

@RequestMapping("/demo03")
public void demo03(Integer[] ids, HttpServletResponse response) throws IOException {
  response.getWriter().write(Arrays.toString(ids));
}

表单示例

<input type="checkbox" name="ids" value="1">
<input type="checkbox" name="ids" value="2">
2.3.2 List/Set绑定(需注解)

Controller方法

@RequestMapping("/demo04")
public void demo04(@RequestParam List<Integer> ids, HttpServletResponse response) {
  // 使用@RequestParam强制绑定集合
}

@RequestMapping("/demo05")
public void demo05(@RequestParam Set<Integer> ids, HttpServletResponse response) {
  // Set自动去重
}
2.3.3 Map绑定(需注解)

Controller方法

@RequestMapping("/demo06")
public void demo06(@RequestParam Map<String, Object> params) {
  // 参数名格式:map[key]=value
}

表单示例

<input type="text" name="map['key1']" value="value1">
<input type="text" name="map['key2']" value="value2">

三、内置数据绑定对象
3.1 常用对象
  • Model:接口,数据存储在Request作用域
  • ModelMap:类,功能类似Model
  • ModelAndView:包含数据与视图路径
3.2 使用示例
@RequestMapping("/demo09")
public String demo09(Map<String,Object> map, Model model, ModelMap modelMap) {
  map.put("mapMsg", "Hello Map");
  model.addAttribute("modelMsg", "Hello Model");
  modelMap.addAttribute("modelMapMsg", "Hello ModelMap");
  return "forward:/demo09.jsp";
}

JSP显示数据

${requestScope.mapMsg}
${requestScope.modelMsg}
${requestScope.modelMapMsg}

四、乱码处理方案
4.1 配置过滤器

web.xml中添加:

<filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
    <param-name>forceResponseEncoding</param-name>
    <param-value>true</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

4.2 注意事项
  • 确保过滤器配置在<servlet>标签之前
  • 同时处理请求和响应编码

五、关键问题总结
  1. 集合绑定
    • List/Set必须使用@RequestParam
    • Map需特殊格式参数名
  2. 类型匹配
    • 表单值需能转换为目标类型(如数字转Double)
  3. 命名规范
    • 表单字段名与参数名/属性名严格一致
  4. 乱码处理优先级
    • 推荐使用过滤器而非手动设置request.setCharacterEncoding()

相关文章:

  • nginx配置oss代理
  • [环境配置] 2. 依赖库安装
  • Linux-CentOS-7—— 配置yum源(网络yum源 + 本地yum源)
  • RabbitMQ安装与使用教程(含Spring Boot整合)
  • HTTP Form v.s. Flask-WTF Form v.s. Bootstrap Form
  • Ollama
  • 项目实战--路由权限
  • OpenCV 图形API(20)用于执行标量与矩阵之间的逐元素减法操作函数subRC()
  • Dify的基本功能介绍与界面初识
  • 当实体类中的属性名和表中的字段名不一样 ,怎么办
  • Comfyui 一键下载模型(多线程)
  • COMSOL固体力学接触
  • LLM面试题七
  • 2024年RAG大赛
  • Async 注解原理分析
  • ARK no NIGHTS
  • 25、Python 文件操作与JSON处理:从基础到实战
  • ArkTS语言入门细节之联合类型
  • 数据仓库的核心架构与关键技术(数据仓库系列二)
  • Minio文件系统
  • 个人网站怎么申请/怎样推广一个产品
  • 网站怎么做更新吗/百度推广入口官网
  • 网上购物网站大全/外贸营销
  • wordpress 浏览次数 2/推广网站排名优化seo教程
  • 免费的动态网站建设视频教程/搜索引擎优化结果
  • 58同城网站建设/系统清理优化工具