SpringMVC_Parameter binding and custom type conversion_hehe.employment.over.37.2

37.5 Request parameter binding

37.5.1 Binding description of request parameters

  • Binding mechanism
    • The data submitted in the form are all username=haha&password=123 in k=v format
    • The parameter binding process of SpringMVC binds the request parameters submitted by the form as the parameters of the method in the controller.
    • Requirement: The name of the submitted form and the name of the parameter are the same
  • Supported data types
    • Basic data types and string types
    • Entity type (JavaBean)
    • Collection data type (List, map collection, etc.)

37.5.2 Basic data types and string types

  • The name of the submitted form and the name of the parameter are the same
  • case sensitive

37.5.3 Entity Type (JavaBean)

  • The name of the submitted form and the attribute name in the JavaBean need to be consistent
  • If a JavaBean class contains other reference types, then the name attribute of the form needs to be written as: object. Attributes such as address.name

37.5.4 Encapsulate collection attribute data

  • JSP page writing method: list[0]. Attributes
  • Example:
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/4/29
  Time: 22:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--把数据封装Account类中,类中存在list和map的集合--%>
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密码:<input type="text" name="password" /><br/>
        金额:<input type="text" name="money" /><br/>

        用户姓名:<input type="text" name="list[0].uname" /><br/>
        用户年龄:<input type="text" name="list[0].age" /><br/>

        用户姓名:<input type="text" name="map['one'].uname" /><br/>
        用户年龄:<input type="text" name="map['one'].age" /><br/>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

37.5.5 Solve the problem of Chinese garbled characters

  • Configure the filter to solve Chinese garbled in 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>

37.6 Custom type converter

  • Any data types submitted by the form are all string types, but the Integer type is defined in the background, and the data can also be encapsulated, indicating that the Spring framework will perform data type conversion by default.
  • If you want to customize the data type conversion, you can implement the Converter interface
  • Custom type converter
package com.xww.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 把字符串转换日期
 */
public class StringToDateConverter implements Converter<String,Date>{
    
    

    /**
     * String source    传入进来字符串
     * @param source
     * @return
     */
    public Date convert(String source) {
    
    
        // 判断
        if(source == null){
    
    
            throw new RuntimeException("请您传入数据");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
    
    
            // 把字符串转换日期
            return df.parse(source);
        } catch (Exception e) {
    
    
            throw new RuntimeException("数据类型转换出现错误");
        }
    }

}

  • Register a custom type converter and write the configuration in the springmvc.xml configuration file
    <!--配置自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.xww.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>

    <!-- 开启SpringMVC框架注解的支持 -->
    <mvc:annotation-driven conversion-service="conversionService"/>

37.7 Use native ServletAPI objects in the controller

  • Only need to define HttpServletRequest and HttpServletResponse objects in the method parameters of the controller
    /**
     * 原生的API
     * @return
     */
    @RequestMapping("/testServlet")
    public String testServlet(HttpServletRequest request, HttpServletResponse response){
    
    
        System.out.println("执行了...");
        System.out.println(request);

        HttpSession session = request.getSession();
        System.out.println(session);

        ServletContext servletContext = session.getServletContext();
        System.out.println(servletContext);

        System.out.println(response);
        return "success";
    }

Guess you like

Origin blog.csdn.net/qq_44686266/article/details/114835741