springMVC前后端不同类型请求参数绑定传递

目录

请求参数的绑定

当绑定参数是基本数据类型和字符串类型时,要注意:

当绑定参数是实体类型(JavaBean)要注意:

给集合属性数据封装,要注意:

绑定参数是日期类型,如何封装:

代码实例:

实体类1:

实体类2:

controller类:

日期自定义类型转换器

springMVC.xml

web.xml

index.jsp

suc.xml


请求参数的绑定

**请求参数的绑定要求:**提交表单的name和参数的名称是相同的

请求参数支持的数据类型:

  • 基本数据类型和字符串类型
  • 实体类型(JavaBean)
  • 集合数据类型(List、map集合等)

当绑定参数是基本数据类型和字符串类型时,要注意:

  1. 提交表单的name和参数的名称是相同的
  2. 区分大小写

当绑定参数是实体类型(JavaBean)要注意:

  1. 提交表单的name和JavaBean中的属性名称需要一致
  2. 如果一个JavaBean类中包含其他的引用类型,那么表单的name属性需要编写成:对象.属性 例如:address.name

给集合属性数据封装,要注意:

JSP页面编写方式:list[0].属性

绑定参数是日期类型,如何封装:

系统默认格式为:2024/7/18,其他格式系统无法识别,所以要进行识别转换:

识别转换的两种方式:

1、要想改变输入日期格式,在实体类相关属性private Date birthday; 上面加注解

@DateTimeFormat(pattern = "yyyy-dd-mm") 指定输入日期的格式

然后在springMVC.xml文件里加上

XML 复制代码
<!--让映射器、适配器和处理器生效(默认不配置也是可以的)-->
<mvc:annotation-driven conversion-service="conversionService"/>

此时那个注解才能生效

2、自定义类型转换器

第一步:可以实现Converter的接口,实现自定义类型转换器

java 复制代码
public class StringToDate implements Converter<String,Date> {
    /**
     * 进行类型转换的方法
     * @param s     用户输入的内容
     * @return
     */
//    @Override
    public Date convert(String s) {
        // 判断
        if(s == null){
            throw new RuntimeException("请输入内容");
        }
        // 进行转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        try {
            // 进行转换
            return sdf.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

第二步:在springMVC.xml文件里配置日期类型转换器

XML 复制代码
<!--配置日期类型转换器,类型转换器的组件,把日期类型转换注入到组件对象中-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.qcby.controller.StringToDate" />
        </set>
    </property>
</bean>

注意在web.xml里面添加过滤器 设置编码,使从前端传递过来的数据经过过滤器,以指定编码显示在后端(解决中文乱码问题)

还要注意:过滤器一定要放在拦截器的前面才能起效果

XML 复制代码
<!--过滤器,解决中文乱码问题-->
<filter>
  <filter-name>characterEncodingFilter</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>
</filter>
<filter-mapping>
  <filter-name>characterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

代码实例:

下面我们来看代码实例:

实体类1:

java 复制代码
public class User {
    private String username;

    private String password;

    private  Car car;

//    @DateTimeFormat(pattern = "yyyy-dd-mm")
    private Date birthday;

    List<String> list;


    public User() {
    }

    public User(String username, String password, Car car, Date birthday, List<String> list) {
        this.username = username;
        this.password = password;
        this.car = car;
        this.birthday = birthday;
        this.list = list;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", car=" + car +
                ", birthday=" + birthday +
                ", list=" + list +
                '}';
    }
}

实体类2:

java 复制代码
public class Car {
    private double money;

    public Car() {
    }

    public Car(double money) {
        this.money = money;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Car{" +
                "money=" + money +
                '}';
    }
}

controller类:

java 复制代码
/**
 * 控制器类,处理用户的请求
 */
// 把当前类交给IOC容器进行管理
@Controller
//@RequestMapping("/hello")  一级
public class HellomvcController {
    /**
     * 处理超链接发送出来的请求
     * @return
     * 注解的属性  如果是value 可以省略不写  其它不行
     */
    // 配置映射的配置  二级
//    @RequestMapping(path = "/hello.do",method = {RequestMethod.GET},params = "username")
    @RequestMapping("/hello.do")
    public String sayHello(){
        System.out.println("入门方法执行了2...");
        // 跳转的JSP页面的路径,默认使用的是请求的转发
        // return "/WEB-INF/pages/suc.jsp";
        // 配置了视图解析器后,写法
        return "suc";
    }
    /**
     * 前端传过来的参数过多,用实体类接收
     * 前提:form表单的name要和实体类的属性名称一致,才能通过实体类属性来获取参数
     * @param user
     * @return
     */
    @RequestMapping("/usersave1")
    public String userSave1(User user){
        System.out.println(user.getUsername()+":"+user.getPassword());
        return "suc";
    }
    @RequestMapping("/usersave2")
    public String userSave2(User user){
        System.out.println(user);
        return "suc";
    }
}

日期自定义类型转换器

java 复制代码
public class StringToDate implements Converter<String,Date> {
    /**
     * 进行类型转换的方法
     * @param s     用户输入的内容
     * @return
     */
//    @Override
    public Date convert(String s) {
        // 判断
        if(s == null){
            throw new RuntimeException("请输入内容");
        }
        // 进行转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        try {
            // 进行转换
            return sdf.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

springMVC.xml

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.qcby"/>

    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


    <!--这里对应@DateTimeFormat(pattern = "yyyy-dd-mm")注解-->
    <!--<mvc:annotation-driven/>-->


    <!--配置日期类型转换器,类型转换器的组件,把日期类型转换注入到组件对象中-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.qcby.controller.StringToDate" />
            </set>
        </property>
    </bean>

    <!--让映射器、适配器和处理器生效(默认不配置也是可以的)-->
    <mvc:annotation-driven conversion-service="conversionService"/>
</beans>

web.xml

XML 复制代码
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

  <!--过滤器-->
  <filter>
    <filter-name>characterEncodingFilter</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>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--统一的servlet做拦截-->
  <!--所有的访问请求都会被拦截-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <!--配置启动加载-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--/表示拦截所有请求-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

index.jsp

javascript 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
<%--超链接--%>
​
<h3>入门</h3>
<%--​locahost:8085/hello.do--%>
<h3>演示SpringMVC的前后端交互</h3>
<a href="/hello.do" >入门程序</a>

<h3>演示SpringMVC请求参数传递,请求参数为基本类型或字符串时</h3>
<form method="post" action="/usersave1">
    用户名:<input type="text" name="username" id="username"/>
    密码:<input type="password" name="password"  id="password"/><br/>
    <input type="submit" name="submit" value="提交"/>
</form>

<h3>演示SpringMVC请求参数传递,请求参数为实体类、集合和日期类型</h3>
<form method="post" action="/usersave2">
    用户名:<input type="text" name="username" id="username1"/>
    密码:<input type="password" name="password"  id="password1"/>
    金额:<input type="text" name="Car.money"  id="money"/>

    集合:<input type="text" name="list[0]"/>
    集合:<input type="text" name="list[1]"/>
    日期:<input type="text" name="birthday" id="birthday"/><br/>
    <input type="submit" name="submit" value="提交"/>
</form>
</body>
</html>

suc.xml

javascript 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>成功页面</title>
</head>
<body>
     <h3>入门成功了...</h3>
</body>
</html>
相关推荐
Miketutu6 小时前
Spring MVC消息转换器
java·spring
小小虫码7 小时前
项目中用的网关Gateway及SpringCloud
spring·spring cloud·gateway
带刺的坐椅13 小时前
无耳科技 Solon v3.0.7 发布(2025农历新年版)
java·spring·mvc·solon·aop
精通HelloWorld!16 小时前
使用HttpClient和HttpRequest发送HTTP请求
java·spring boot·网络协议·spring·http
LUCIAZZZ17 小时前
基于Docker以KRaft模式快速部署Kafka
java·运维·spring·docker·容器·kafka
拾忆,想起17 小时前
如何选择Spring AOP的动态代理?JDK与CGLIB的适用场景
spring boot·后端·spring·spring cloud·微服务
鱼骨不是鱼翅18 小时前
Spring Web MVC基础第一篇
前端·spring·mvc
hong_zc20 小时前
Spring MVC (三) —— 实战演练
java·spring·mvc
Future_yzx21 小时前
Spring AOP 入门教程:基础概念与实现
java·开发语言·spring
安清h1 天前
【基于SprintBoot+Mybatis+Mysql】电脑商城项目之用户注册
数据库·后端·mysql·spring·mybatis