Java 如何从jsp向Struts2动作输入日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2397498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to input Date to a Struts2 action from a jsp?
提问by Anand
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 ?
我在我的 jsp 页面中遇到了很多问题。我应该使用什么标签从用户获取日期 (yyyy-MM-dd) 并将其存储在 Struts2 操作的 Date 属性中?
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.
我的操作中的属性被声明为 java.util.Date。我希望来自 jsp 页面的输入落在此属性中。
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.
如果使用 as:textfield 标签以正确的格式输入日期,我会收到无效字段错误(在 JSP 中)。
回答by PJT
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:
所以也许我不明白这个问题。但我希望这个例子有帮助(顺便说一句,这段代码不起作用,只是为了帮助您了解 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 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. Make sure for input name="holder.date". Here is site.jsp:
您的 jsp 表单,您可以在其中让客户端输入日期。确保输入名称=“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>
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 日期格式示例
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 对象。
回答by beatupunit
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. More info on that is here: http://struts.apache.org/2.0.14/docs/datetimepicker.html
我不相信 Struts 提供开箱即用的日期输入,除非您使用日期时间选择器,它是一个 dojo/javascript 标记。更多信息在这里: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.
如果您不走这条路线,您很可能需要将 JSP 上的日期映射到一个字符串,然后在您的操作类中对其进行格式化。您可以通过让 Struts 首先验证值来使这更容易。
回答by Alfredo Osorio
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
希望这可以帮助
回答by Samuel
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.
Struts 的默认转换器似乎无法正常工作。字段错误甚至发生在从操作填充的只读字段中。
I resolved it by defining my own converter:
我通过定义自己的转换器解决了这个问题:
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; } } }
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; }
创建转换器类(使用您需要的日期格式):
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; } } }
将转换注释放在属性设置器上(或使用 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. I used an additional hidden field to keep the original value (another alternative would have been the use of Preparable interface):
就我而言,我不需要编辑它,但想在 jsp 中指定格式。我使用了一个额外的隐藏字段来保留原始值(另一种选择是使用 Preparable 接口):
<s:textfield name="uploadedDateDisplay" value="%{getText('format.datetimesecond',{uploadedDate})}" size="70" disabled="true"/>
<s:hidden name="uploadedDate" />
回答by surfealokesea
jsp:
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
动作.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});
回答by Jiawu Zhang
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>
回答by Jiawu Zhang
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();
我尝试了一种解决方案并且它起作用了:)
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 格式存储在 table 中。
5)您还可以将 datecolumn 的数据与 curdate() 和相关函数进行比较,并且它有效:)。
6)就像我用过的查询:选择 id,name,DATE_FORMAT(datecolumnname,'%d/%m/%Y') as datecolumn2 from tablename where datecolumnname >= curdate();