SpringMVC框架|自定义转换器


很多时候我们在view层接收到的数据类型和pojo中的类型并不匹配,此时就需要自定义一个转换器来辅助我们完成数据类型转换的工作。例如一个人的生日属性,前端接收到的是String类型,但是pojo中的是Data类型,下面以此为例,写出一个自定义的转换器。

(1)user_pojo

package com.gql.pojo;
import java.util.Date;
/**
 * 类说明:
 *		User_pojo
 * @guoqianliang1998.
 */
public class User {
	private Integer id;
	private String name;
	private Integer age;
	private String sex;
	private Date birthday;
	//省略对应的set和get方法
}

(2)handler处理器

处理器中跳转页面的字符串通过SpringMVC配置中的视图解析器进行了简化。

package com.gql.springmvc03;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.gql.pojo.User;
/**
 * 类说明:
 *		处理器
 * @guoqianliang1998.
 */
@Controller
public class UserController {

	public UserController() {
		super();
		System.out.println("构造函数...");
	}
	//转发到前端addUI.jsp
	@RequestMapping("/test")
	public String addUI(User user){
		return "addUI";
	}
	
	@RequestMapping("/add")
	public String add(User user){
		return "index";
	}
}

(3)前端添加页面

一个简单的前端添加页面,当点击添加用户按钮时跳转到add.do页面,由于在add.do页面又跳转到了index.jsp页面,所以当点击添加用户按钮最终会跳转到index.jsp。

在这里插入图片描述

addUI.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
  <head>
	<meta http-equive="content-type" content="text/html,charset=utf-8"/>
  	<title>用户添加页面</title>
  </head>
  
  <body>
  		
    	<form action='<c:url value="/add.do"/>' method="post">
    		<table border="1">
    			<tr>
    				<td align="center">用户名</td>
    				<td align="center">性别</td>
    				<td align="center">年龄</td>
    				<td align="center">生日</td>
    			</tr>
    			<tr>
    				<td><input type="text" name="name"/></td>
    				<td><input type="text" name="sex"/></td>
    				<td><input type="text" name="age"/></td>
    				<td><input type="text" name="birthday"/></td>
    			</tr>
    			<tr>
    				<td colspan="4" align="center">
    					<input type="submit" value="添加用户" />
    				</td>
    			</tr>
    		</table>
    	</form>
  </body>
</html>

(4)添加用户后跳转到的页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<html>
  <head>
	<meta http-equive="content-type" content="text/html,charset=utf-8"/>

  </head>
  
  <body>
   		添加用户成功
  </body>
</html>

(5)StringtoDate转换器

package com.gql.convertor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;

/**
 * 类说明: 
 * 		转换器
 * @guoqianliang1998.
 */
public class StringtoDate implements Converter<String, Date> {

	@Override
	public Date convert(String source) {
		try {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
		} catch (ParseException e) {
			throw new RuntimeException("日期转换异常");
		}
	}
}

(6)配置SpringMVC

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd 
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
	
	<!-- 处理器(手写) -->
	<context:component-scan base-package="com.gql.springmvc03"></context:component-scan>
	
	<!-- 代替处理器映射器和处理器适配器 -->
	<mvc:annotation-driven conversion-service="conversionService"/>
	
	<!-- 自定义类型转换器 -->
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<bean class="com.gql.convertor.StringtoDate"></bean>
			</set>
		</property>
	</bean>
	
	<!-- 视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

(7)前端控制器

*.do*.action : 请求的url以.do或.action结尾,都会被SpringMVC框架所解析.
/ :所有的请求都会被pringmvc所解析,会造成静态资源无法访问.支持RestFul开发风格.
/* :拦截所有请求,JSP也会被springmvc解析,造成JSP无法访问.不要使用这种方式

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>SpringMVC01</display-name>

	
	<!-- 前端控制器 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 加载SpringMVC配置文件 -->
		<init-param>
				<param-name>contextConfigLocation</param-name>
				<param-value>classpath:springmvc03.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

(8)测试自定义转换器

在Debug模式下运行该程序,可以看到成功将信息加入user对象中。

在这里插入图片描述
在这里插入图片描述
自定义转换器测试成功。

发布了421 篇原创文章 · 获赞 1100 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/weixin_43691058/article/details/104367749