Strusts2笔记4--类型转换器

类型转换器:

  Struts2默认情况下可以将表单中输入的文本数据转换为相应的基本数据类型。这个功能的实现,主要是由于Struts2内置了类型转换器。这些转换器在struts-default.xml中可以看到其定义

  常见的类型,基本均可由String转换为相应的类型。但是注意:Date只能接收 yyyy-MM-dd或yyyy-MM-dd HH:mm:ss 格式的字符串

  自定义转换器:

    1. 代码: 

package com.tongji.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.conversion.TypeConversionException;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

public class MyDateTypeConverter extends DefaultTypeConverter {

    //value是要转换的数据,且它的类型是字符串数组,因为它要兼容前端传过来的数据,是数组,如checkbox的多选项,或者是单个数据,如text。
    //如果是单个数据,在代码中就是取数组中的第一个元素。
    //toType是转换成为的数据类型
    @Override
    public Object convertValue(Object value, Class toType) {
        try {
            if (toType == Date.class) {     //由页面到服务器 是由String到Date类型的转换
                String source = ((String[])value)[0];
                SimpleDateFormat sdf = getSimpleDateFormat(source);
                ActionContext.getContext().getSession().put("sdf", sdf);
                return sdf.parse(source);
            } else if (toType == String.class) {   //数据回显:由服务器到页面 是由Date到String类型的转换
                SimpleDateFormat sdf = (SimpleDateFormat) ActionContext.getContext().getSession().get("sdf");
                return sdf.format((Date)value);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return super.convertValue(value, toType);
    }
    
    private SimpleDateFormat getSimpleDateFormat(String source) {
        SimpleDateFormat sdf = null;
        if (Pattern.matches("^\d{4}/\d{2}/\d{2}$", source)) {
            sdf = new SimpleDateFormat("yyyy/MM/dd");
        } else if (Pattern.matches("^\d{4}-\d{2}-\d{2}$", source)) {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        } else if (Pattern.matches("^\d{4}\d{2}\d{2}$", source)) {
            sdf = new SimpleDateFormat("yyyyMMdd");
        } else {
            throw new TypeConversionException();
        }
        
        return sdf;
    }
    
}

   其中要注意三点:一是value代表的是一个数组,二是数据类型转换是双向的,因为有数据回显的需求;三是因为判断类型转换失败时,要抛出TypeConversionException异常,以便后续处理。

  2.局部类型转换器的配置:

    局部类型转换器,仅仅对指定Action的指定属性起作用。注册方式为,在Action类所在包下放置名称为如下格式的属性文件:ActionClassName-conversion.properties文件。其中ActionClassName是Action类名,-conversion.properties是固定写法。

    该属性文件的内容遵循以下格式:属性名称=类型转换器的全类名。例如:birthday=com.tongji.converter.MyDateTypeConverter

  3. 数据回显的实现:

    (1)表单提交的前端代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
  <head>
    <title>index page</title>
  </head>
  
  <body>
      <s:form action="test/login.action" method="POST">
          <s:textfield name="age" label="年龄"/>
          <s:textfield name="birthday" label="生日"/>
          <s:submit value="提交"/>
      </s:form>
  </body>
</html>

    使用Struts2标签来实现

    (2)struts2.xml 代码:

<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <package name="demo" namespace="/test" extends="struts-default">
        <action name="login" class="com.tongji.actions.LoginAction">
            <result name="success">/welcome.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>

    数据回显实现的关键是,当数据类型转换失败,抛出TypeConversionException 异常后,页面要求跳转到input视图,因此,要配置input视图对应的前端页面。

    (3)类型转换异常提示信息的修改:

      类型转换异常提示信息,是系统定义好的内容,若直接显示到用户页面,会使页面显得不友好。但,类型转换异常提示信息是可以修改的。步骤如下:

        Action所在包中添加名称为ActionClassName.properties的属性文件,其中ActionClassName为Action的类名。在该文件中写入内容:invalid.fieldvalue.变量名=异常提示信息

    (4)数据回显最终页面显示结果:

      

  4. 全局类型转换器配置:

    全局类型转换器,会对所有的Action的指定类型的属性生效。其注册方式为:在src目录下放置名称为 xwork-conversion.properties 属性文件。该文件的内容格式为:待转换的类型=类型转换器的全类名

     java.util.Date=com.tongji.converter.MyDateTypeConverter

原文地址:https://www.cnblogs.com/qjjazry/p/6238047.html