简体   繁体   English

如何从jsp向Struts2动作输入Date?

[英]How to input Date to a Struts2 action from a jsp?

I am facing a lot of problems here in my jsp page. 我在jsp页面中遇到了很多问题。 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 ? 我应该用什么标签从用户那里获取日期(yyyy-MM-dd)并将其存储在Struts2动作的Date属性中?

The property in my action is declared to be of java.util.Date. 我的操作中的属性声明为java.util.Date。 I want the input from jsp page to land in this property. 我希望jsp页面的输入落在这个属性中。

please help. 请帮忙。

I get Invalid field error (in JSP) if is use as:textfield tag to manyally enter a date in the right format. 我得到无效字段错误(在JSP中),如果用作:textfield标签,以正确的格式输入日期。

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. Struts的默认转换器似乎无法正常工作。 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.properties文件)

     @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. 在我的情况下,我不需要编辑它,但想在jsp中指定格式。 I used an additional hidden field to keep the original value (another alternative would have been the use of Preparable interface): 我使用了一个额外的隐藏字段来保留原始值(另一种替代方法是使用Preparable接口):

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

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 希望这可以帮助

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); 但我希望这个例子有所帮助(顺便说一句,这段代码不会起作用,只是为了让你了解sturts2如何发挥其魔力); 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: 因此,对于表单输入,您需要在java中拥有一个holder类,因此您可以从您的操作类调用您的日期,例如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: 你的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 action class where you call your make sure holder.getdate to get your date getDateAction.java: 您调用的动作类确保holder.getdate获取日期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. 您的jsp表单,您可以让客户端输入日期。 Make sure for input name="holder.date". 确保输入name =“holder.date”。 Here is site.jsp: 这是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: 最后但并非最不重要的是你的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 这里有一个Struts2日期格式的解释: Struts 2 Date Format Examples

But I believe the tag you are looking for in jsp is 但我相信你在jsp中寻找的标签是

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

Where Date_Name is the Date object in Java. 其中Date_Name是Java中的Date对象。

jsp: JSP:

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

?.properties ?的.properties

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

Action.java 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/ 脚本:您可以添加jquery.datepicker(我不建议使用struts datepicker): http//jqueryui.com/datepicker/

$("#date").datepicker({dateFormat: dateFormat});
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>

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. 1)仅在“DATE”数据类型的数据库表中保存要存储日期的列。 2)Use only Textfield tag in JSP page.Dont use Date tag. 2)在JSP页面中仅使用Textfield标签。不要使用Date标签。
Note :Make sure that you make user input date in YYYY-MM-DD format only by placing a placeholder in textfield tag ! 注意 :确保仅通过在textfield标记中放置占位符,使用户输入日期为YYYY-MM-DD格式!
3)Keep the variable for accessing that field of string type only.Dont use DATE data type. 3)保留变量以仅访问字符串类型的字段。不要使用DATE数据类型。
4)Now run Query: Select DATE_FORMAT(datecolumnname,'%d/%m%/Y') as date_two from tablename; 4)现在运行Query: 从tablename中选择DATE_FORMAT(datecolumnname,'%d /%m%/ Y')作为date_two; and you will get date from that columnin dd/mm/yyyy format even if it is stored in YYYY-MM-DD format in table . 即使在表格中以YYYY-MM-DD格式存储,您也将从该列以dd / mm / yyyy格式获取日期。
5)And you can also compare your datecolumn's data with curdate() and related functions as well and it works :) . 5)你也可以比较你的日期列的数据与curdate()和相关的功能,它的工作原理:)。
6)Like i used query: Select id,name,DATE_FORMAT(datecolumnname,'%d/%m/%Y') as datecolumn2 from tablename where datecolumnname >= curdate(); 6)像我使用的查询: 从tablename中选择id,name,DATE_FORMAT(datecolumnname,'%d /%m /%Y')作为datecolumn2,其中datecolumnname> = curdate();

the <s:date /> tag only displays dates - it doesn't provide input. <s:date />标记仅显示日期 - 它不提供输入。

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. 我不相信Struts提供开箱即用的日期输入,除非你使用日期时间选择器,这是一个dojo / javascript标签。 More info on that is here: http://struts.apache.org/2.0.14/docs/datetimepicker.html 有关详细信息,请访问: 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. 如果不沿着那条路走下去,您很可能需要将JSP上的日期映射到字符串,然后在操作类中对其进行格式化。 You can make this easier by getting Struts to validate the value first. 您可以通过让Struts首先验证值来简化这一过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM