如何从 jsp 输入日期到 Struts2 操作?

发布于 2024-08-23 18:01:51 字数 212 浏览 6 评论 0原文

我的 jsp 页面面临很多问题。我应该使用什么标签从用户获取日期 (yyyy-MM-dd) 并将其存储在 Struts2 操作的 Date 属性中?

我的操作中的属性被声明为 java.util.Date。我希望jsp页面的输入落在这个属性中。

请帮忙。

如果使用 as:textfield 标记以正确的格式多次输入日期,我会收到无效字段错误(在 JSP 中)。

I am facing a lot of problems here in my jsp page. What tag I should use to get a date (yyyy-MM-dd) from user and store it in a Date property of a Struts2 action ?

The property in my action is declared to be of java.util.Date. I want the input from jsp page to land in this property.

please help.

I get Invalid field error (in JSP) if is use a s:textfield tag to manyally enter a date in the right format.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

皓月长歌 2024-08-30 18:01:51

我知道这篇文章有点旧,但解决方案可能对其他人有用。

Struts的默认转换器似乎不能正常工作。字段错误甚至发生在从操作填充的只读字段中。

我通过定义自己的转换器解决了这个问题:

  1. 创建转换器类(使用您需要的日期格式):

    public class StringToDateTimeConverter 扩展了 StrutsTypeConverter {
        // 警告在多线程环境中不安全
        private static Final DateFormat DATETIME_FORMAT = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
    
        公共对象convertFromString(地图上下文,String []字符串,类toClass){     
            if (strings == null || strings.length == 0 || strings[0].trim().length() == 0) {
                返回空值;
            }
    
            尝试 {
                返回 DATETIME_FORMAT.parse(strings[0]);
            } catch (ParseException e) {
                throw new TypeConversionException("无法将给定对象转换为日期:" + strings[0]);
            }
        }
    
        公共字符串convertToString(地图上下文,对象日期){
            if (date != null && date instanceof Date) {         
                返回 DATETIME_FORMAT.format(日期);
            } 别的 {
                返回空值;
            }
        }
    }
    
  2. 将转换注释放在属性设置器上(或使用 conversion.properties 文件)

    <前><代码>@Conversion()
    公共类 MyEditAction {
    // ...

    @TypeConversion(转换器=“my.app.common.converter.StringToDateTimeConverter”)
    公共无效setUploadedDate(上传日期){
    this.uploadedDate = uploadedDate;
    }

在我的例子中,我不需要编辑它,但想在 jsp 中指定格式。
我使用了一个额外的隐藏字段来保留原始值(另一种选择是使用 Preparable 接口):

<s:textfield name="uploadedDateDisplay" value="%{getText('format.datetimesecond',{uploadedDate})}" size="70" disabled="true"/>
<s:hidden name="uploadedDate" />

I know this post is a bit old but a solution may be useful to others.

The default converter of Struts does not seem to work properly. The field error even occurs with readonly fields populated from the action.

I resolved it by defining my own converter:

  1. Create the converter class (using the date format you need):

    public class StringToDateTimeConverter extends StrutsTypeConverter {
        // WARNING not safe in multi-threaded environments
        private static final DateFormat DATETIME_FORMAT = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
    
        public Object convertFromString(Map context, String[] strings, Class toClass) {     
            if (strings == null || strings.length == 0 || strings[0].trim().length() == 0) {
                return null;
            }
    
            try {
                return DATETIME_FORMAT.parse(strings[0]);
            } catch (ParseException e) {
                throw new TypeConversionException("Unable to convert given object to date: " + strings[0]);
            }
        }
    
        public String convertToString(Map context, Object date) {
            if (date != null && date instanceof Date) {         
                return DATETIME_FORMAT.format(date);
            } else {
                return null;
            }
        }
    }
    
  2. Put the conversion annotation on the property setter (or use a conversion.properties file)

    @Conversion()
    public class MyEditAction {
        // ...
    
        @TypeConversion(converter="my.app.common.converter.StringToDateTimeConverter")
        public void setUploadedDate(Date uploadedDate) {
            this.uploadedDate = uploadedDate;
        }
    

In my case I did not need to edit it but wanted to specify the format in the jsp.
I used an additional hidden field to keep the original value (another alternative would have been the use of Preparable interface):

<s:textfield name="uploadedDateDisplay" value="%{getText('format.datetimesecond',{uploadedDate})}" size="70" disabled="true"/>
<s:hidden name="uploadedDate" />
咆哮 2024-08-30 18:01:51

这就是我解决这个问题的方法。

    <s:date name="nameOfInputVal" var="formattedVal"/>
    <s:textfield name="nameOfInputVal" value="%{#formattedVal}" key="labelkey" />

在您的消息属性中,有一个键/值:

struts.date.format=dd/MM/yyyy

它指示默认格式,您不必将其写入每个日期标记中。

希望这有帮助

This is how I solved this.

    <s:date name="nameOfInputVal" var="formattedVal"/>
    <s:textfield name="nameOfInputVal" value="%{#formattedVal}" key="labelkey" />

And in your message properties a key/value:

struts.date.format=dd/MM/yyyy

Which indicates the default format and you don't have to write it in each date tag.

Hope this helps

成熟稳重的好男人 2024-08-30 18:01:51

所以也许我不明白这个问题。但我希望这个例子能有所帮助(顺便说一句,这段代码不会起作用,它只是为了帮助您了解 Sturts2 如何发挥其魔力);因此,对于表单输入,您需要在 java 中拥有一个 Holder 类,这样您就可以从操作类中调用您的日期,例如 Holder.java:

public class Holder{
  pirvate Date date; 
  public getDate(){
     return date; 
  }
  public setDate(Date date){
    this.date = date; 
  }
}

Your Holder.java 验证,以便您可以确保它是一个日期 Holder-validation.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 
1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
    <field name="date">
    <field-validator type="date">
               <message><![CDATA[ Must be a date ]]></message>
    </field-validator>
     </field>
</validators>

Your操作类,您可以在其中调用确保holder.getdate来获取日期 getDateAction.java:

private Holder holder;
    public class getDateAction{
    public String execute(){
     //get your date
      Date date = holder.getDate(); 

       return SUCCESS; 
     }
    }

您的jsp表单,您可以在其中为客户端提供输入日期的能力。确保输入 name="holder.date"。这是 site.jsp:

<s:form id="Form" name="MyForm" action="getDateAction" method="post"  class="form">
<input type="text" name="holder.date" id="date" size="25" value="" class="required text">
</s:form>

最后但并非最不重要的是你的 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="example" extends="struts-default">
<action name="getdate" class="com.location.action.getDateAction">
         <result>example.jsp</result>
</action>
</package>
</struts>

这里有一个关于 Struts2 日期格式的解释: Struts 2 日期格式示例

但我相信您在 jsp 中寻找的标记是

<s:date name="Date_Name" format="yyyy-MM-dd" />

其中 Date_Name 是 Java 中的 Date 对象。

So maybe I don't understand the question. But I hope this example helps (btw this code will not work its just to help give you an idea of how it sturts2 works its magic); So for form input you need to have a holder class in java, so you can call your date from your action class such as Holder.java:

public class Holder{
  pirvate Date date; 
  public getDate(){
     return date; 
  }
  public setDate(Date date){
    this.date = date; 
  }
}

Your Holder.java validation so you can make sure its a date Holder-validation.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 
1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
    <field name="date">
    <field-validator type="date">
               <message><![CDATA[ Must be a date ]]></message>
    </field-validator>
     </field>
</validators>

Your action class where you call your make sure holder.getdate to get your date getDateAction.java:

private Holder holder;
    public class getDateAction{
    public String execute(){
     //get your date
      Date date = holder.getDate(); 

       return SUCCESS; 
     }
    }

Your jsp form where you give the client the ability to input the date. Make sure for input name="holder.date". Here is site.jsp:

<s:form id="Form" name="MyForm" action="getDateAction" method="post"  class="form">
<input type="text" name="holder.date" id="date" size="25" value="" class="required text">
</s:form>

and last but not least your 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="example" extends="struts-default">
<action name="getdate" class="com.location.action.getDateAction">
         <result>example.jsp</result>
</action>
</package>
</struts>

There is an explanation of Struts2 date Format here at: Struts 2 Date Format Examples

But I believe the tag you are looking for in jsp is

<s:date name="Date_Name" format="yyyy-MM-dd" />

Where Date_Name is the Date object in Java.

凉栀 2024-08-30 18:01:51

标记仅显示日期 - 它不提供输入。

我不相信 Struts 提供开箱即用的日期输入,除非您使用日期时间选择器,这是一个 dojo / javascript 标记。有关更多信息,请参见:http://struts.apache.org/2.0。 14/docs/datetimepicker.html

如果您不走这条路,您很可能需要将 JSP 上的日期映射到字符串,然后在操作类中对其进行格式化。您可以通过让 Struts 首先验证该值来简化此操作。

the <s:date /> tag only displays dates - it doesn't provide input.

I don't believe Struts provides out of the box date input, unless you use the date time picker, which is an dojo / javascript tag. More info on that is here: http://struts.apache.org/2.0.14/docs/datetimepicker.html

If you don't go down that route, you will most likely need to map the date on your JSP to a string, then format it in your action class. You can make this easier by getting Struts to validate the value first.

忘羡 2024-08-30 18:01:51

jsp:

<s:textfield name="date" id="date" key="invitation.date" required="true" value="%{getText('format.date',{date})}" size="8"/>

?.properties

format.date={0,date,dd/MM/yyyy}

Action.java

import java.util.Date;
private Date date;
public void setDate(Date date) {
    this.date = date;
}

脚本:
你可以添加jquery.datepicker(我不推荐struts datepicker):
http://jqueryui.com/datepicker/

$("#date").datepicker({dateFormat: dateFormat});

jsp:

<s:textfield name="date" id="date" key="invitation.date" required="true" value="%{getText('format.date',{date})}" size="8"/>

?.properties

format.date={0,date,dd/MM/yyyy}

Action.java

import java.util.Date;
private Date date;
public void setDate(Date date) {
    this.date = date;
}

script:
You can add jquery.datepicker (I don't recommend struts datepicker):
http://jqueryui.com/datepicker/

$("#date").datepicker({dateFormat: dateFormat});
反话 2024-08-30 18:01:51
private Date date;

public void setDate(String date) {
//setter method param type is String
    try {
        this.date=new SimpleDateFormat("yyyy-MM-dd").parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}


<form action="target.do">
    <input name="date" value="2015-5-28">
    <button type="submit">submit</button>
</form>
private Date date;

public void setDate(String date) {
//setter method param type is String
    try {
        this.date=new SimpleDateFormat("yyyy-MM-dd").parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}


<form action="target.do">
    <input name="date" value="2015-5-28">
    <button type="submit">submit</button>
</form>
一抹苦笑 2024-08-30 18:01:51

我尝试过一种解决方案并且有效:)
1)仅将数据库表中要存储日期的列保留为“DATE”数据类型。
2)在JSP页面中只使用Textfield标签,不要使用Date标签。
注意:确保仅通过在文本字段标记中放置占位符来使用户输入 YYYY-MM-DD 格式的日期!
3)保留变量仅用于访问字符串类型的字段。不要使用DATE数据类型。
4)现在运行查询:Select DATE_FORMAT(datecolumnname,'%d/%m%/Y') as date_two from tablename;,您将从该列中获取 dd/mm/yyyy 格式的日期,即使它以 YYYY-MM-DD 格式存储在表中。
5)您还可以将 datecolumn 的数据与 curdate() 和相关函数进行比较,并且它可以工作:)。
6)就像我使用的查询一样:从表名中选择 id,name,DATE_FORMAT(datecolumnname,'%d/%m/%Y') 作为 datecolumn2,其中 datecolumnname >= curdate();

There is one solution which i tried and it worked :)
1)Keep the column in which you want to store date in database's table in "DATE" data type only.
2)Use only Textfield tag in JSP page.Dont use Date tag.
Note:Make sure that you make user input date in YYYY-MM-DD format only by placing a placeholder in textfield tag !
3)Keep the variable for accessing that field of string type only.Dont use DATE data type.
4)Now run Query: Select DATE_FORMAT(datecolumnname,'%d/%m%/Y') as date_two from tablename; and you will get date from that columnin dd/mm/yyyy format even if it is stored in YYYY-MM-DD format in table .
5)And you can also compare your datecolumn's data with curdate() and related functions as well and it works :) .
6)Like i used query: Select id,name,DATE_FORMAT(datecolumnname,'%d/%m/%Y') as datecolumn2 from tablename where datecolumnname >= curdate();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文