Spring MVC type converter
We know from the previous article that spring MVC framework can automatically encapsulate and bind parameters, but sometimes the data we transmit is not necessarily transformed according to the existing type converter.
As illustrated by the following example, it is necessary to customize the type converter.
public class User { private String username; private String password; private Integer age; private Date date; //setter and getter //toString
@Controller @RequestMapping("/test") public class HelloController { @RequestMapping("/beans") public String beans(User user){ System.out.println("User name:" + user); return "success"; } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="test/beans"> <table border="1px"> <tr> <td>User name:</td> <td><input name="username" type="text"></td> </tr> <tr> <td>Password:</td> <td><input name="password" type="text"></td> </tr> <tr> <td>Birthday:</td> <td><input name="date" type="date"></td> </tr> <tr> <td>Age:</td> <td><input name="age" type="text"></td> </tr> <tr> <td><input type="submit" value="Submission"></td> </tr> </table> </form> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <span id="address"></span> <script type="text/javascript"> var url = document.location; document.getElementById("address").innerHTML=url; </script> </body> </html>
First date format
Second date format
We found that only one date format is supported, so we need to write our own type converter
Preparation steps:
Step 1: define a class to implement the Converter interface, which has two generics.
@FunctionalInterface public interface Converter<S, T> {//S: Indicates the type of acceptance, T: indicates the target /** * Convert the source object of type {@code S} to target type {@code T}. * @param source the source object to convert, which must be an instance of {@code S} (never {@code null}) * @return the converted object, which must be an instance of {@code T} (potentially {@code null}) * @throws IllegalArgumentException if the source cannot be converted to the desired target type */ @Nullable T convert(S source); }
public class StrToDat implements Converter<String, Date> { @Override public Date convert(String source) { System.out.println(source); DateFormat df = null; Date date = null; try { if (StringUtil.isEmpty(source)) { throw new NullPointerException("Please enter the date"); } df = new SimpleDateFormat("YYYY-MM-dd"); date = df.parse(source); return date; } catch (Exception e) { throw new RuntimeException("Incorrect date format"); } } }
public class StringUtil { public static boolean isEmpty(String source) { return source == null || source.equals("")||source.isEmpty(); } }
Of course, we don't mean we can only use this way. We provide a method, a data type conversion method
The source code of this article is as follows:
public class User { private String username; private String password; private Integer age; private Date date; //setter and getter //toString
@Controller @RequestMapping("/test") public class HelloController { @RequestMapping("/beans") public String beans(User user){ System.out.println("User name:" + user); return "success"; } }
public class StringUtil { public static boolean isEmpty(String source) { return source == null || source.equals("")||source.isEmpty(); } }
public class StrToDat implements Converter<String, Date> { @Override public Date convert(String source) { System.out.println(source); DateFormat df = null; Date date = null; try { if (StringUtil.isEmpty(source)) { throw new NullPointerException("Please enter the date"); } df = new SimpleDateFormat("YYYY-MM-dd"); date = df.parse(source); return date; } catch (Exception e) { throw new RuntimeException("Incorrect date format"); } } }
<?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"> <! -- enable annotation scanning, because the XML needs to be loaded into the project, so configure the file to web.xml, and load the file into the project when the core controller loads -- > <context:component-scan base-package="com.toulan"></context:component-scan> <!-- For example, the full path of a request is: http: / / localhost: 8080 / springmvc? Introduction? Demo01? War / WEB-INF / pages / success.jsp Because our project start address is http: / / localhost: 8080 / springmvc? Introduction? Demo01? War prefix: /WEB-INF/pages/ suffix: .jsp When we return the page in the controller layer, we only need to pass the JSP page name: success. If we do not configure suffix here, we need to pass success.jsp return "success. JSP"; If Prefix suffix is not written here, then we need to return / WEB-INF / pages / success. JSP return "/ WEB-INF / pages / success. JSP" in the control layer; --> <! -- configure view parser object -- > <! -- create the InternalResourceViewResolver object through Spring's IOC container, and use -- > <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <! -- the prefix used to view the name when building the URL. In general, it is the prefix of the browser request path -- > <property name="prefix" value="/WEB-INF/pages/"></property> <! -- suffix appended to view name when building URL -- > <property name="suffix" value=".jsp"></property> </bean> <! -- configure custom type converter -- > <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.toulan.utils.StrToDat"></bean> </set> </property> </bean> <! -- enable spring MVC framework annotation support, such as RequestMapping, etc Use < MVC: annotation driven > to automatically load RequestMappingHandlerMapping and RequestMappingHandlerAdapter, which can be used in the spring mvc.xml configuration file < MVC: annotation driven > replaces the configuration of annotation processors and adapters. --> <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven> </beans>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <span id="address"></span> <script type="text/javascript"> var url = document.location; document.getElementById("address").innerHTML=url; </script> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="test/beans"> <table border="1px"> <tr> <td>User name:</td> <td><input name="username" type="text"></td> </tr> <tr> <td>Password:</td> <td><input name="password" type="text"></td> </tr> <tr> <td>Birthday:</td> <td><input name="date" type="text"></td> </tr> <tr> <td>Age:</td> <td><input name="age" type="text"></td> </tr> <tr> <td><input type="submit" value="Submission"></td> </tr> </table> </form> </body> </html>
<!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> <display-name>Archetype Created Web Application</display-name> <!--Create the core controller. All requests will be classed and passed through the servlet,Through this servlet Distribute requests--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!--Set profile springmvc.xml Load into project--> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!--Look at the bottom.--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <!--Block all requests--> <url-pattern>/</url-pattern> </servlet-mapping> <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> </web-app>