Struts 类型转换异常拦截器(三十三)

本文详细介绍了在Struts2框架中如何通过默认拦截器栈处理类型转换异常,以及如何在Action类中定义资源文件以实现中文错误提示。通过实例展示了当公布时间输入字符时出现的转换异常,并提供了解决方法。
1.在Strtus2框架中默认拦截器栈提供了conversionError拦截器,当程序在运行时发生类型转换问题,那么拦截器就将会对该异常错误进行处理,然后输出到视图页面中。

2.action

package com.sh.action;

import com.opensymphony.xwork2.ActionSupport;
import com.sh.pojo.News;

public class AddNewsAction extends ActionSupport {
private News news;
public News getNews() {
return news;
}

public void setNews(News news) {
this.news = news;
}

public String execute(){
return SUCCESS;
}
}


3.struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
<!-- 定义国际化资源文件的基本名称 -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<include file="struts-default.xml"/>
<package name="default" extends="struts-default">
<action name="addnewsAction" class="com.sh.action.AddNewsAction">
<result name="success">/shownews.jsp</result>
<result name="input">/addnews.jsp</result>
</action>
</package>
</struts>


4.addnews.jsp

<body>
<s:form action="addnewsAction" method="post">
<table width="401" height="176" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2">窗内网新闻发布</td>
</tr>
<tr>
<td width="118" style="font-weight:normal;text-align: right">标题:</td>
<td width="224"><s:textfield name="news.newstitle"/></td>
</tr>
<tr>
<td style="font-weight:normal;text-align: right">内容</td>
<td><s:textfield name="news.newscontent"/></td>
<tr>
<td style="font-weight:normal;text-align: right">公布时长</td>
<td><s:textfield name="news.newstime"/></td>
</tr>
<tr>
<td style="font-weight:normal;text-align: right">发布人</td>
<td><s:textfield name="news.newsuser"/></td>
</tr>
<tr>
<td style="font-weight:normal;text-align: right"> </td>
<td style="font-weight:normal;text-align: right"><s:submit value="发布"/></td>
</tr>
</tr>

</table>
</s:form>
</body>


5.pojo

package com.sh.pojo;

public class News {
private String newstitile;
private String newscontent;
private int newstime;
private String newsuser;
//get set
}

6.访问
--http://localhost:8080/Struts2_ConversionError/addnews.jsp
--如果 公布时间 输入字符 会出现转换异常
--此时 会在页面输入公布时间的地方出现 Invalid field value for field "news.newstime".

7.定义action的中文资源文件(发现 错误提示还是不友好 。通过设置属性文件成中文提示)
AddNewsAction_zh_CN.properties(放在action类的同包下)

invalid.fieldvalue.news.newstime=你输入的数据类型不符合要求!
news=News


8.-http://localhost:8080/Struts2_ConversionError/addnews.jsp
如果类型转换异常 就出现提示 你输入的数据类型不符合要求!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值