Solve the Chinese garbled and custom type converter

First, problem solving maven project created too slow:

    archetypeCatalog       internal

Second, the solution to solve the parameters of Chinese garbled

    Spring filter class configuration provided 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>
Third, custom type converter

    1. Any form submission data type is a string of all types, but the background is defined Interger type, data can also be on the package, the Spring Framework described internal default data type conversion
    2. custom data type conversion, to implement the interface Converter
        custom type converter class

import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDate implements Converter<String, Date> {

    @Override
    public Date convert(String s) {
        if (s==null){
            throw new RuntimeException("请传入数据");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return df.parse(s);
        } catch (Exception e) {
            throw new RuntimeException("传入数据格式有误");
        }
    }
}

        Register a custom type converter, written in springMVC.xml configuration profile

<!--注册自定义类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.ycl.utils.StringToDate"></bean>
        </set>
    </property>
</bean>
<!--开启springMVC框架对注解的支持-->
<mvc:annotation-driven conversion-service="conversionService"/>
Fourth, the use of native ServletAPI objects in the controller

        HttpServletRequest and HttpServletResponse only need to define the parameters in the process controller of the object

Published 21 original articles · won praise 2 · Views 255

Guess you like

Origin blog.csdn.net/weixin_45636641/article/details/104185523