SpringMVC_类型转换器

一:系统提供的类型转换器

从前端页面提交的表单数据,提交到Controller中,Controller会根据我们在方法中定义的参数的类型来将数据类型自动转换

1:编写表单数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/submit.do" method="post">
    用户名:<input type="text" name="username"><br>
    年龄:<input type="text" name="age"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

2:Controller

// Controller中的方法会自动将age转为int类型
// 该转换是通过SpringMvc的默认类型转换器来实现的,但有些类型是无法通过该转换器进行转换的,例如日期类型
@Controller
public class newController{ @RequestMapping("/registUser.do") public ModelAndView addUser(String name,int age) throws Exception{ ModelAndView mv = new ModelAndView(); mv.addObject("name", name); mv.addObject("age", age); mv.setViewName("user"); return mv; } }

...

二:自定义类型转换器

1:创建一个类实现接口Converter,该接口中的是泛型,前面的为待转类型,后面的是转换后的类型

// 将String类型转换为Date类型
public
class DateConverter implements Converter<String, Date> { @Override public Date convert(String s) { // 避免空指针 if (s != null && !"".equals(s)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { return sdf.parse(s); } catch (ParseException e) { e.printStackTrace(); } } return null; } }

2:配置springmvc.xml配置文件

<!--注册注解驱动-->
<mvc:annotation-driven conversion-service="conversionService"/>

<!--注册类型转换器 指定其项目全名-->
<bean id="dateConverter" class="com.doaoao.converter.DateConverter"/>

<!--注册类型转换服务bean-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters" ref="dateConverter"/>
</bean>

3:编写Controller

@Controller
public class UserController{

    @RequestMapping("/registUser.do")
    public ModelAndView addUser(String name,int age,Date birthday) throws Exception{

        ModelAndView mv = new ModelAndView();
        mv.addObject("name", name);
        mv.addObject("age", age);
        mv.addObject("birthday", birthday);
        mv.setViewName("user");
        return mv;
    }
}
三:使用注解 @DateTimeFormat注解

1:引入jar包(jdk8及其以上不必引入jar包)

<dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.9.9</version>
</dependency>

2:编写Controller

@Controller
public class UserController{
    @RequestMapping("/registUser.do")
    public ModelAndView addUser(String name,int age,@DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday) 
        throws Exception{ ModelAndView mv = new ModelAndView(); mv.addObject("name", name); mv.addObject("age", age); mv.addObject("birthday", birthday); mv.setViewName("user"); return mv; } }

 # @DateTimeFormat(pattern = "yyyy-MM-dd") 指定其日期的格式

...

猜你喜欢

转载自www.cnblogs.com/Doaoao/p/10668424.html