在Struts中使用异常
1 、自定义用户异常
public class MyException extends Exception {
private String code;
public MyException() {
super();
}
public MyException(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
2、 在相应的业务方法中抛出异常
public boolean isExistMember(String memberCode)throws MyException{
List list=(List)baseDAO.getByProperty("TMember","memberCode",memberCode);
if(list.size()>0){
throw new MyException("Error_001");
}else{
return false;
}
}
3 在Action中作出相应的页面跳转
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
AddMemberForm addMemberForm = (AddMemberForm) form
try{
if(!memberManager.isExistMember(addMemberForm.getMemberCode())){
memberManager.addMember(addMemberForm);
}
}catch(MyException ee){
request.setAttribute("code",ee.getCode());
return mapping.findForward("error");
}catch(Exception e){
e.printStackTrace();
}
return mapping.findForward("success");
}
*其中"error","success"要先在对应的Action中配置好,内容如下
name="addMemberForm"
path="/addMember"
scope="request">
4、首先定义好Struts中常用的标签文件,把这些标签统一放到一个jsp文件中方便在其它页面使用标签时可以直接引用
taglibs.jsp内容如下:
5、 再创建一个引用properties文件的jsp文件
i18n.jsp内容如下:
<fmt:setbundle basename="com.demo.resource.member" var="addMember"></fmt:setbundle>
其中member.properties文件内容如下:
####==============Error====================
Error_001=此会员已存在!
####==============Success====================
Succ_001=增加成功!
6 、在jsp页面使用时:
如在error.jsp内容如下:
<html:html lang="true">
<html:base>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
error.jsp
<fmt:message bundle="${addMember}"></fmt:message>
</html:html>
<html:html lang="true">
<fmt:message bundle="${addMember}"></fmt:message>
</html:html>