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文件里加上

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

此时那个注解才能生效

2、自定义类型转换器

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

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文件里配置日期类型转换器

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

注意在web.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:

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:

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类:

/**
 * 控制器类,处理用户的请求
 */
// 把当前类交给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";
    }
}

日期自定义类型转换器

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 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

<!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

<%@ 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

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>成功页面</title>
</head>
<body>
     <h3>入门成功了...</h3>
</body>
</html>

相关推荐

  1. springMVC前后请求参数传递

    2024-07-19 08:20:04       18 阅读
  2. SpringMVC参数

    2024-07-19 08:20:04       32 阅读
  3. springmvc数据

    2024-07-19 08:20:04       29 阅读
  4. 关于前后参数传递

    2024-07-19 08:20:04       29 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-19 08:20:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-19 08:20:04       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-19 08:20:04       58 阅读
  4. Python语言-面向对象

    2024-07-19 08:20:04       69 阅读

热门阅读

  1. C++中的socket编程常用接口

    2024-07-19 08:20:04       19 阅读
  2. Redis实现打卡功能

    2024-07-19 08:20:04       20 阅读
  3. 探索.NET内存之海:垃圾回收的艺术与实践

    2024-07-19 08:20:04       22 阅读
  4. 【.NET全栈】ASP.NET开发Web应用——Web部件技术

    2024-07-19 08:20:04       18 阅读
  5. 基于Gunicorn、Flask和Docker的高并发部署

    2024-07-19 08:20:04       20 阅读
  6. ArcGIS Pro SDK (九)几何 5 多边形

    2024-07-19 08:20:04       21 阅读
  7. SpringBoot集成EasyExcel实现模板写入多个sheet导出

    2024-07-19 08:20:04       21 阅读
  8. python中excel的读取和写入

    2024-07-19 08:20:04       20 阅读
  9. Python 3 CGI编程

    2024-07-19 08:20:04       19 阅读
  10. 为什么 HashMap 的容量是 2 的整次幂?

    2024-07-19 08:20:04       16 阅读
  11. C++编程逻辑讲解step by step:利用文档类处理数据

    2024-07-19 08:20:04       20 阅读
  12. 【Oracle】Oracle中的LISTAGG函数

    2024-07-19 08:20:04       19 阅读