struts2 validator 驗證框架遇到的問題
阿新 • • 發佈:2018-12-10
我在使用 ValidationInterceptor 驗證框架驗證使用者名稱是否為空時,出現下面的錯誤
Struts Problem Report
Struts has detected an unhandled exception:
Messages: |
|
File: | file:/D:/java/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Struts2Test/WEB-INF/classes/com/demo/struts2/validate/validate.xml |
ValidateAction.java
package com.demo.struts2.validate; import org.apache.struts2.interceptor.validation.SkipValidation; import com.opensymphony.xwork2.ActionSupport; public class ValidateAction extends ActionSupport{ private static final long serialVersionUID = 1L; private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String reg() { System.out.println("reg"); return SUCCESS; } @SkipValidation public String toRegView() { System.out.println("toRegView"); return "regView"; } }
struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="ValidatePkg" namespace="/validate" extends="struts-default"> <action name="ValidateAction_*" class="com.demo.struts2.validate.ValidateAction" method="{1}"> <result name="success">/validate/reg.jsp</result> <result name="regView">/validate/reg.jsp</result> <allowed-methods>reg,toRegView</allowed-methods> </action> </package> </struts>
reg.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>reg.jsp</title>
</head>
<body>
<s:debug></s:debug>
<s:form action="ValidateAction_reg" namespace="/validate" method="post">
<s:textfield name="name" label="UserName"></s:textfield>
<s:textfield name="age" label="Age"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
ValidateAction-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>請輸入使用者名稱</message>
</field-validator>
</field>
</validators>
ValidateAction-validation.xml 的DOCTYPE 可以在 struts2-core-2.5.16.jar 下面找到 xwork-validator-1.0.3.dtd 開啟這個檔案如下,
ValidateAction-validation.xml 中欄位驗證的型別(field-validator 元素的type屬性)可以在 struts2-core-2.5.16.jar裡面找到 com.opensymphony.xwork2.validator.validators包裡面的default.xml 如下圖所示
這樣做驗證會出現錯誤
解決辦法:
struts.xml 檔案中必須要加上result name為input的頁面,具體如下(至於為什麼要這樣我也不太清楚,但是這樣確實可以解決問題)