我们知道在http协议中,所有的参数都是String类型的,其实这些参数就是没有类型。那么从表单中得到的String数据怎么转换到程序中对应的数据类型呢?这其实是由Parameter拦截器实现的。那么如果说数据转换呢出现了错误怎么把?好比说应该是一个int类型的,我输入了一个string,那么默认的是不转,则int最终是0。那么我们要管理这种错误呢?

我们只要实现了ValidationAware接口就可以了,这个接口专门负责处理错误的数据类型转换,但是其中会有很多的方法要实现,我们可以使用现成的,继承ActionSupport类即可。

这时,我们必须写出一个出现了错误之后的处理页面。在struts.xml中。添加一个<result name="input">xxxx.jsp</retult>,一旦有错误就跳到这里,而且会显示一个提示。如果要修改默认的提示,在Action类对应的包下,创建ActionClassName.properties文件,里面加一条:invalid.fieldvalue=xxxx.即可。


下面是一个例子:

index.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>


<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<s:form action="error">
<s:textfield label="年龄" name="age"></s:textfield>
<s:submit label="确定"></s:submit>
</s:form>

</body>
</html>


success.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h2>成功!</h2>

</body>
</html>


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="struts2"
extends="struts-default">
<action name="error" class="com.nju.ErrorAction">
<result>success.jsp</result>
<result name="input">index.jsp</result>
</action>

</package>
</struts>

ErrorAction.java:

package com.nju;

import com.opensymphony.xwork2.ActionSupport;

public class ErrorAction extends ActionSupport{

/**
*
*/
private static final long serialVersionUID = 1L;
private int age;

public void setAge(int age) {
this.age = age;
}

public int getAge() {
return age;
}

public String execute(){
System.out.println("age:" + age);
return "success";
}
}

ErrorAction.properties

invalid.fieldvalue.age=No valid !


结构:

struts2错误类型_struts2