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
如果类型转换异常 就出现提示 你输入的数据类型不符合要求!