Spring MVC gets parameters and custom parameter type converters and encoding filters

Table of contents

1. Use Servlet native objects to obtain parameters

1.1 Controller methods

1.2 Test results

2. Custom parameter type converter

2.1 Write a type converter class

2.2 Register type converter object 

2.3 Test results 

3. Encoding filter

3.1 JSP form

3.2 Controller methods

3.3 Configure filters

3.4 Test results 

Related readings of previous columns & articles 

1. Maven series of columns

2. Mybatis series of columns

3. Spring series of columns 

4. Spring MVC series of columns


1. Use Servlet native objects to obtain parameters

        SpringMVC also supports the use of Servlet native objects, and parameters of types such as HttpServletRequest, HttpServletResponse, and HttpSession can be directly used in the method by defining parameters such as HttpServletRequest and HttpServletResponse in the method parameters.

1.1 Controller methods

// 使用Servlet原生对象
    @RequestMapping("c1/param8")
    public void servletParam(HttpSession session,HttpServletRequest request, HttpServletResponse response){
        // 原生对象获取参数
        System.out.println(request.getParameter("name"));
        System.out.println(response.getCharacterEncoding());
        System.out.println(session.getId());
    }

        This is a very classic use of the request built-in object to obtain parameters. After the request, the parameters and encoding methods are printed on the console, as well as the corresponding sessionId.

Access path: http://localhost:8080/c1/param8?name=LYL

1.2 Test results

        OK, it can be seen that the parameter value, encoding method and sessionId have been successfully queried

        In general, there are alternatives to the methods of Servlet native objects in SpringMVC, and it is recommended to use SpringMVC instead of Servlet native objects.

2. Custom parameter type converter

The parameters from the front end are all of string type, and SpringMVC uses its own converter to convert the string parameters to the required type. like:

// Get simple type parameters
@RequestMapping("/c1/param1")
public void simpleParam(String username,int age){
    System.out.println(username+" "+age);
}

But in some cases, the string cannot be converted to the required type, such as:

// Custom conversion date format string
@RequestMapping("c1/param9")
public void dataParam(Date birthday){     System.out.println(birthday); } Now let's test to see what the result is:


Console output: 

Reason for error:

[WARNING]Resolved[org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core. convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2025-01-01'; nested exception is java.lang.IllegalArgumentException] The
 specific meaning is: [org .springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springfframework.core.covert. ConversionFailedException: Unable to convert value '2025-01-01' from type [java.lang.SString] to type [java.util.Date]; nested exception is java.lang.IllegalArgumentException]

2.1 Write a type converter class

        Since there are many formats of date data, SpringMVC cannot convert strings in all formats into date types. For example, when the parameter format is birthday=2025-01-01, SpringMVC cannot parse the parameter. In this case a custom parameter type converter is required. First, you must define a type converter class and implement the Converter interface. It is written as follows:  

package com.example.converter;

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

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

public class DataConverter implements Converter<String, Date> {

    /**
     * 转换方法
     * @param s 转换前的数据
     * @return 转换后的数据
     */
    @Override
    public Date convert(String s) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        Date date = null;
        try{
            date = sdf.parse(s);
        } catch (ParseException e) {
            System.out.println("转换成日期格式出错了!");
            e.printStackTrace();
        }
        return date;
    }
}

2.2 Register type converter object 

<!-- 配置转换器工厂 -->
    <bean id="dateConverter" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <!-- 转换器集合 -->
        <property name="converters">
            <set>
                <!-- 自定义转换器 -->
                <bean class="com.example.converter.DataConverter"></bean>
            </set>
        </property>
    </bean>
    <!-- 使用转换器工厂 -->
    <mvc:annotation-driven conversion-service="dateConverter"></mvc:annotation-driven>

OK, after adding the above, let's run the test again to see if the control can be successfully received 

2.3 Test results 

 You can see that the 404 error was reported, and this page was not found, instead of 400

OK, the console is also successfully printed out. 

3. Encoding filter

When passing parameters, tomcat8 and above can handle the Chinese garbled characters of the get request, but cannot handle the Chinese garbled characters of the post request

3.1 JSP form

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>专属页面</title>
</head>
<body>
  <form action="/c1/param3" method="post">
    <table>
      <tr>
        <th>id:</th>
        <td><input name="id"/></td>
      </tr>
      <tr>
        <th>姓名:</th>
        <td><input name="name"/></td>
      </tr>
      <tr>
        <th>性别:</th>
        <td><input name="sex"/></td>
      </tr>
      <tr>
        <th>住址:</th>
        <td><input name="address.info"/></td>
      </tr>
      <tr>
        <th>邮编:</th>
        <td><input name="address.postcode"/></td>
      </tr>
      <tr align="center">
        <td><input type="submit"/></td>
      </tr>
    </table>
  </form>
</body>
</html>

Here is a form submission page

3.2 Controller methods

I will continue to use the previous controller method, as follows: 

    @RequestMapping("c1/param3")
    public void objParam2(Student student){
        System.out.println(student);
    }

3.3 Configure filters

        SpringMVC provides a filter for dealing with Chinese garbled characters. Configuring the filter in web.xml can solve the problem of Chinese garbled characters: add the following configuration:

<!-- SpringMVC中提供的字符编码过滤器,放在所有过滤器的最上方 -->
  <filter>
    <filter-name>encFilter</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>encFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

3.4 Test results 

        Submit the above information to see if there are any garbled characters printed on the console. If there are no garbled characters, it means that the character encoding filter is configured successfully. 

        OK, it shows that it is indeed possible, and if the name attribute submitted in the form corresponds to the Student attribute, it can also be directly assigned to the corresponding parameter.

Related readings of previous columns & articles 

     If you don’t know anything about the content of this issue, you can also go to see the content of previous issues. The following is a series of column articles such as Maven and Mybatis carefully crafted by bloggers in the past. Don’t miss it when you pass by! If it is helpful to you, please like it and bookmark it. Among them, some of the Spring columns are being updated, so they cannot be viewed, but they can be viewed after the bloggers have completed all the updates.

1. Maven series of columns

Maven Series Column Maven project development
Maven aggregation development [example detailed explanation --- 5555 words]

2. Mybatis series of columns

Mybatis series column MyBatis entry configuration
Mybatis entry case [super detailed]
MyBatis configuration file - detailed explanation of related tags
Mybatis fuzzy query - three methods of defining parameters and aggregation query, primary key backfill
Mybatis dynamic SQL query -- (attached actual combat case -- 8888 words -- 88 quality points)
Mybatis paging query - four ways to pass parameters
Mybatis first level cache and second level cache (with test method)
Mybatis decomposition query
Mybatis related query [attached actual combat case]
MyBatis annotation development --- realize addition, deletion, modification and dynamic SQL
MyBatis annotation development --- realize custom mapping relationship and associated query

3. Spring series of columns 

Spring series column Introduction to getting started with Spring IOC [custom container instance]
IOC uses Spring to implement detailed explanation with examples
The creation method, strategy, destruction timing, life cycle and acquisition method of Spring IOC objects
Introduction to Spring DI and Dependency Injection Method and Dependency Injection Type
Application of Spring IOC-related annotations——Part 1
Application of Spring IOC-related annotations——Part 2
Introduction to Spring AOP and related cases
Annotation, native Spring, and SchemaBased implement AOP in three ways [with detailed case]
Introduction to Spring affairs and related cases
Spring transaction management scheme and transaction manager and transaction control API
Spring transaction related configuration, propagation behavior, isolation level and annotation configuration declarative transaction

4. Spring MVC series of columns

SpringMVC series column Introduction to Spring MVC with an introductory case
Spring MVC various parameter acquisition and acquisition methods custom type converter and encoding filter
Spring MVC gets parameters and custom parameter type converters and encoding filters
Spring MVC processing response with detailed case explanation
Application of Spring MVC-related annotations—— Part 1

Application of Spring MVC-related annotations - Part 2

Application of Spring MVC-related annotations——Part 2
File upload in multiple situations of Spring MVC
Spring MVC asynchronous upload, cross-server upload and file download
Spring MVC exception handling [single control exception handler, global exception handler, custom exception handler]
Spring MVC interceptors and cross domain requests
SSM integration case [the case of station C explaining the most detailed process]

Guess you like

Origin blog.csdn.net/qq_53317005/article/details/130375526
Recommended