Struts类型转换器

我们知道Struts的默认日期类型是yyyy-MM-dd格式的

Struts中为什么要类型转换?

      HTML表单采集数据-->提交表单-->Action

     底层依赖HTTP传递数据,而HTTP协议中 没有 “类型” 的概念. 每一项

     表单输入只可能是一个字符串或一个字符串数组。因此在服务器端Action

     中 必须把 String转换为业务需要的特定的数据类型

Struts2 中如何传递请求参数给 Action?

Struts2框架会将表单的参数以同名的方式设置给对应Action的属性中。

该工作主要是由Parameters拦截器做的。而该拦截器中已经自动的实现了

String到基本数据类型之间的转换工作。类似于: Beanutils工具。

String到基本数据类型之间的转换是自动的,而String到Date类型的转换是有条件的


下面开始使用注册案例进行将日期类型进行转换

结构图如下:


首先写好注册页面register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>日期转换类</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  <body>
  		<form action="${pageContext.request.contextPath }/user_register" method="post">
  		用户名:<input type="text" name="user.name"><br/>
  		密码:<input type="text" name="user.pwd"><br/>
  		年龄:<input type="text" name="user.age"><br/>
  		生日:<input type="text" name="user.birth"><br/>
  		<input type="submit" value="注册">
  	</form>
  </body>
</html>

然后配置type.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
          "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="type" extends="struts-default" namespace="/">
		<action name="user_*" class="cn.qblank.type.UserAction" method="{1}">
			<result name="success">/index.jsp</result>
			<result name="input">/error.jsp</result>			
		</action>
	</package>
</struts>

创建实体类对象User

package cn.qblank.type;

import java.util.Date;
public class User {
	private String name;
	private String pwd;
	private int age;
	private Date birth;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
}

然后对应的写入处理类UserAction

package cn.qblank.type;

import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
	private User user;
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	/**
	 * 注册方法
	 * @return
	 */
	public String register() {
		System.out.println(user.getName());
		System.out.println(user.getPwd());
		System.out.println(user.getAge());
		System.out.println(user.getBirth());
		return "success";
	}
	
}

定义错误页面error.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>错误页面</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  <body>
  	错误页面<br/>
  	<!-- 查看struts框架在运行时期产生的所有错误信息 -->
  	<%@ taglib uri="/struts-tags" prefix="s" %>
  	<s:fielderror></s:fielderror>
  </body>
</html>

注册成功页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>成功页面</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
  	<h3>注册成功</h3>
  </body>
</html>


然后写一个自定义的日期转换类

Struts中如何配置自定义转换器呢?

1)自定义转换器类继承StrutsTypeConverter类

2)重写convertFromString方法和convertToString方法

package cn.qblank.type;

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

import org.apache.struts2.util.StrutsTypeConverter;

public class MyConverter extends StrutsTypeConverter {
	//先定义项目中的转换格式
	DateFormat[] df = {new SimpleDateFormat("yyyy-MM-dd"),
			new SimpleDateFormat("yyyyMMdd"),new SimpleDateFormat("yyyy年MM月dd日")};
	/**
	 * 把String转换为指定的类型 【String To Date】
	 * @param context 当前上下文环境
	 * @param values  jsp表单提交的字符串的值
	 * @param toClass 要转换为的目标类型
	 */
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		//判断参数是否为空
		if (values == null || values.length == 0) {
			return null;
		}
		//判断是否为Date类型
		if (Date.class != toClass) {
			return null;
		}
		// 迭代:转换失败继续下一个格式的转换; 转换成功就直接返回
		for (int i = 0; i < df.length; i++) {
			try {
				//转换
				return df[i].parse(values[0]);
			} catch (ParseException e) {
				continue;
			}
		}
		return null;
	}
	@Override
	public String convertToString(Map context, Object o) {
		return null;
	}
}

3)注册转换器

在Action所在的包下建立Action名(UserAction)-conversion.properties

在文件中写入

对象的属性 = 转换器的完整类名

user.birth=cn.qblank.type.MyConverter


这种方式的转换器与Action的名字是耦合的,因此只能在自己的Action内部使用,称之为局部转换器

那么如何定义全局转换器呢?

实现的接口和继承的类都是相同的,本质上就是配置的方式不同。

全局转换器需要在src目录下建立固定文件

xwork-conversion.properties

配置内容如下:

java.util.Date=cn.qblank.type.MyConverter


该拦截器负责对错误信息进行拦截器<interceptor name="conversionError

      class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/>







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值