struts2错误类型

我们知道在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 !

结构:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值