zoukankan      html  css  js  c++  java
  • Struts2日期类型转换

    https://www.cnblogs.com/jingpeipei/p/5945724.html

    针对日期类java.util.Date进行类型转换,要求客户端使用“yyyy-MM-dd”,“yyyy/MM/dd”中的任意一种输入,并以“yyyy-MM-dd”的格式输出,该类型转换应用于全局范围

    先定义一个实体类

    复制代码
    package cn.entity;
    
    import java.util.Date;
    
    public class User { 
        private String username;//名字
    
        private Integer age;//年龄
        
        private Date birthday;//生日
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
        
    
    }
    复制代码

    创建Action

    复制代码
    package cn.action;
    
    import cn.entity.User;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class LoginAction extends ActionSupport{
         private User user;
            public String execute(){
                System.out.println("姓名:"+user.getUsername());
                System.out.println("生日:"+user.getBirthday());
                return SUCCESS;
            }
            public User getUser() {
                return user;
            }
            public void setUser(User user) {
                this.user = user;
            }
    }
    复制代码

    创建类型转换器

    StrutsTypeContentType类是抽象类,定义了两个抽象方法,用于不同的转换方向

      1.public Object convertFromString(Map context, String[] values, Class toType):将一个或多个字符串值转换为指定的类型

      2.public String convertToString(Map context, Object object):将指定对象转化为字符串

    如果继承StrutsTypeContentType类编写自定义类型转换器,需重载以上两个抽象方法。

    复制代码
    package cn.strutstypeconverter;
    
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Map;
    
    import org.apache.struts2.util.StrutsTypeConverter;
    
    import com.opensymphony.xwork2.conversion.TypeConversionException;
    
    public class DateConverter extends StrutsTypeConverter{
        //支持转换的多种日期格式,可增加时间格式
        private final DateFormat[] dfs={
            new SimpleDateFormat("yyyy年MM月dd日"),
            new SimpleDateFormat("yyyy-MM-dd"),
            new SimpleDateFormat("MM/dd/yy"),
            new SimpleDateFormat("yyyy.MM.dd"),
            new SimpleDateFormat("yy.MM.dd"),
            new SimpleDateFormat("yyyy/MM/dd")
        };
    
        
        /**
         * 将指定格式字符串转换为日期类型
         */
        @Override
        public Object convertFromString(Map context, String[] values, Class toType) {
            String dateStr=values[0];       //获取日期的字符串
            for (int i = 0; i < dfs.length; i++) {   //遍历日期支持格式,进行转换
                try {
                    return dfs[i].parse(dateStr);
                } catch (Exception e) {
                    continue;
                }
            }
            //如果遍历完毕后仍没有转换成功,表示出现转换异常
            throw new TypeConversionException();
        }
    
        
        /**
         * 将日期转换为指定的字符串格式
         */
        @Override
        public String convertToString(Map context, Object object) {
            Date date=(Date) object;
            //输出格式是yyyy-MM-dd
            return new SimpleDateFormat("yyyy-MM-dd").format(date);
        }
    
    }
    复制代码

    Struts2提供了两种方式配置转换器

      1.应用于全局范围的类型转换器

      在src目录创建xwork-conversion.properties

          

    java.util.Date=cn.strutstypeconverter.DateConverter

      2.应用于特定类的类型转换器

      在特定类的相同目录下创建一个名为ClassName-conversion.properties的属性文件

        

    user.birthday=cn.strutstypeconverter.DateConverter

    配置struts.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="default" namespace="/" extends="struts-default">
            <!-- login指定的Action -->
            <action name="login" class="cn.action.LoginAction">
                <result name="success">
                    success.jsp
                </result>
                <result name="input">
                    index.jsp
                </result>
            </action>
        </package>
    </struts>
    复制代码

    开发输入与展示页面

    index.jsp

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%@taglib uri="/struts-tags" prefix="s"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
      </head>
      
      <body>
      <!-- 错误信息 -->
      <s:fielderror></s:fielderror>
       <!-- 表单的提交 -->        
            <s:form action="login" method="post" namespace="/">
            <div class="infos">
                        <table class="field">
                        <tr><td>用户名:<s:textfield name="user.username" /></td>
                        </tr>
                        <tr><td>年龄:<s:password  name="user.age"/></td>
                        
                        </tr>
                        <tr><td>生日:<s:textfield name="user.birthday"/> </td>
                        </tr>
                        <tr><td><s:submit type="submit" value="提交"/></td></tr>
                        </table>
            
                
                </div>
            </s:form>
      </body>
    </html>
    复制代码

    success.jsp

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%@taglib uri="/struts-tags" prefix="s"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
      </head>
      
      <body>
            <h1>成功</h1>
            <s:property value="user.birthday"/>
       <s:date name="user.birthday" format="yyyy年MM月dd日"/>
      </body>
    </html>
    复制代码

    效果展示:

  • 相关阅读:
    Simple Automated Backups for MongoDB Replica Sets
    [转] matlab获取时间日期
    Matlab与C++混合编程 编写独立外部应用程序时出现“无法定位序数3906于动态链接库LIBEAY32.dll上”错误
    Visual Studio 控制台应用程序 同时使用OpenCV和matlab mat文件操作
    [转] Matlab与C++混合编程(依赖OpenCV)
    OpenCV 64位时 应用程序无法正常启动0x000007b 问题解决
    LinkedBlockingQueue多线程测试
    rdlc报告vs2008编辑正常,在vs2012在对错误的编辑
    SD3.0四个协议解读
    链队列
  • 原文地址:https://www.cnblogs.com/feifeicui/p/8733036.html
Copyright © 2011-2022 走看看