Struts2シングルテキストフィールドで3回検証します
-
14-11-2019 - |
質問
Struts(2.2.3)に本当に怒っている問題を抱えています。ActionName-validation.xml のマイフィールド検証です。
<field name="txtRequestDateFrom">
<field-validator type="conversion">
<param name="repopulateField">false</param>
<message>${getText("E011", {"Date from"})}</message>
</field-validator>
</field>
.
アクションクラスにvalidate()メソッドはありません。そして私は私の行動クラスにこれを持っています:
private Date txtRequestDateFrom;
{getter, setters}
.
TXTRequestDateFromフィールドに文字を入力すると、に3つの検証メッセージが表示されます
<s:fielderror fieldName="txtRequestDateFrom"/>
.
こののように見えます
Invalid field value for field "txtRequestDateFrom".
Invalid field value for field "txtRequestDateFrom".
Date from has an invalid value
.
私のカスタムテーマを持っています、そして私はシンプルなテーマからのあまり修正があまりないと確信しています。私のインターセプタースタックはほとんど同じデフォルト値スタックです。
<interceptor-stack name="defaultStack">
<interceptor-ref name="security"/>
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="debugging"/>
<interceptor-ref name="scopedModelDriven"/>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="fileUploadStack" />
<interceptor-ref name="fileUpload" >
<param name="maximumSize">4000000</param>
</interceptor-ref>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="multiselect"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation">
<param name="excludeMethods">execute, complete ...</param>
</interceptor-ref>
<interceptor-ref name="workflow"/>
</interceptor-stack>
.
StackからConversionErrorインターセプタを削除することで、1つのフィールドエラーを削除できることがわかりました。しかし、私はそれがこの問題を引き起こすだろうとは思わない。Strutsは開発者によってのみ定義されたエラーを表示できるようにする必要があります。
こので私を助けてください
解決 2
私のカスタムDateTimeConverter
が例外と追加のエラーメッセージを引き起こしていたことを見つけました。日付の通常の形式を変更するために、Struts2 Bookから以下のコードを見つけました。例外をスローすると、例外をバリデータに渡すのではなく、フィールドエラーのコンソールとエラーメッセージの例外が表示されます。このクラスはStrutsTypeConverter
を拡張し、通常のコンバータとして機能する必要がありますので、それが種類のバグですと思います。
public class StringToDateTimeConverter extends StrutsTypeConverter {
private static final DateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy/MM/dd");
public Object convertFromString(Map context, String[] strings, Class toClass) {
if (strings == null || strings.length == 0 || strings[0].trim().length() == 0) {
return null;
}
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(DATETIME_FORMAT.parse(strings[0]));
calendar.set(Calendar.HOUR, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
return calendar.getTime();
} catch (ParseException e) {
throw new TypeConversionException(e);
}
}
public String convertToString(Map context, Object date) {
if (date != null && date instanceof Date) {
return DATETIME_FORMAT.format(date);
} else {
return null;
}
}
.
}
とにかくthrow new TypeConversionException(e);
をreturn null;
に変更し、検証XMLにREQUIRED
バリデータを追加しました。日付フィールドに無効な日付を入れると、私がエラーが表示されるようになりました。
PS:Strutsグローバル日付形式を変更する方法は他にありますか?ありがとう
他のヒント
あなたは Struts2が変換エラーを処理する方法< / a>。
型変換中に発生する誤り任意のエラーが報告されたくない場合があります。たとえば、入力 "abc"を数値に変換できなかったことを報告することは重要かもしれません。一方、空の文字列を数値に変換できないと報告することは重要ではないかもしれません - 特にウェブ環境では、ユーザーを区別することが難しい場合は、空白値を入力していないユーザーを区別することが難しい場合があります。
...
これらのエラーのどれも実際に直接報告されていないことを知ることが重要です。むしろ、それらはActionContext内のConderctorderRorsというマップに追加されます。このマップにアクセスできる方法はいくつかあり、それに応じてエラーを報告することができます。
エラー報告が発生する2つの方法がある:
- グローバルには、変換エラーインターセプターを使用して
- フィールドごとに、変換バリデータを使用して
両方のメカニズムを使用しているため、見つかったエラーを複製します。ドキュメントの状態として、通常はすべての変換エラーを報告したくないため、 conversionErrorInterceptor スタックから。これで、
conversion
Validatorを使用してフィールドエラーとして変換エラーを選択的に上げます。
私は昨日の同様の問題に直面し、ついに共有するのが好きな解決策を見つけました。検証のために私のアクションに注釈を使用しているので、デフォルトのStrutsインターセプタースタックを変更し、StrutsConVersionErrorInterceptor InではなくMy SensiBleConVersionErrorInterceptorを変更しました。これは同じであるが検証エラーを作成しません。代わりに、それらは私のアクションのアノテーションで設定された検証によって生成されます。
これは私のコンバーターです:
public class SensibleConversionErrorInterceptor extends StrutsConversionErrorInterceptor {
private static final long serialVersionUID = 8186282792289268544L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext invocationContext = invocation.getInvocationContext();
Map<String, Object> conversionErrors = invocationContext.getConversionErrors();
ValueStack stack = invocationContext.getValueStack();
HashMap<Object, Object> fakie = null;
for (Map.Entry<String, Object> entry : conversionErrors.entrySet()) {
String propertyName = entry.getKey();
Object value = entry.getValue();
if (shouldAddError(propertyName, value)) {
// removed cause error messages are generated from annotations in actions
// String message = XWorkConverter.getConversionErrorMessage(propertyName, stack);
// Object action = invocation.getAction();
// if (action instanceof ValidationAware) {
// ValidationAware va = (ValidationAware) action;
// va.addFieldError(propertyName, message);
// }
if (fakie == null) {
fakie = new HashMap<Object, Object>();
}
fakie.put(propertyName, getOverrideExpr(invocation, value));
}
}
if (fakie != null) {
// if there were some errors, put the original (fake) values in place right before the result
stack.getContext().put(ORIGINAL_PROPERTY_OVERRIDE, fakie);
invocation.addPreResultListener(new PreResultListener() {
public void beforeResult(ActionInvocation invocation, String resultCode) {
Map<Object, Object> fakie = (Map<Object, Object>) invocation.getInvocationContext().get(ORIGINAL_PROPERTY_OVERRIDE);
if (fakie != null) {
invocation.getStack().setExprOverrides(fakie);
}
}
});
}
return invocation.invoke();
}
.
}
とアクションの例:
@Conversion
public class ProductAction extends ActionSupport {
private Product product;
// getter, setter and so on...
@Action(...)
@Validations(
requiredFields = {
@RequiredFieldValidator(
type = ValidatorType.FIELD,
fieldName = "product.validFrom",
message = "required.product.validFrom",
shortCircuit = true
)
},
conversionErrorFields = {
@ConversionErrorFieldValidator(
fieldName = "product.validFrom",
key = "invalid.fieldvalue.product.validFrom'",
shortCircuit = true
)
}
)
public String saveOrUpdate() {
// do something here...
}
}
.