RunTimeException处理:
/**
* 根据itemCode查找物料替代料
* @author emma
* @return
*/
1.
public Item addItemInstead(Item item, String insteadItemCode){
Item insteadItem = itemDao.findByItemCode(insteadItemCode);
item = itemDao.findById(item.getId());
//不能添加不存在的物料
if (insteadItem == null)
throw new ApplicationException("errors.CanNotAddNotExistedCodeException", new String[] {insteadItemCode });
//不能添加自己
if(insteadItem.getItemCode() == item.getItemCode()){
throw new ApplicationException("errors.CanNotAddSelfCodeException", new String[] {insteadItemCode });
}
//不能添加重复物料
if (item.getInsteadItems().contains(insteadItem))
throw new ApplicationException("errors.CanNotAddDuplicatedCodeException", new String[] {insteadItemCode });
itemDao.addItemInstead(new ItemInstead(item.getId(), insteadItem.getId()));
itemDao.addItemInstead(new ItemInstead(insteadItem.getId(),item.getId()));
return insteadItem;
}
2.
public class ApplicationException extends RuntimeException{
private static final long serialVersionUID = 3830821949267447214L;
public ApplicationException() {
super();
}
public ApplicationException(String msg) {
super(msg);
}
public ApplicationException(String msgKey, String[] params) {
super();
setMsgKey(msgKey);
setParams(params);
}
private String msgKey;
public String getMsgKey() {
return msgKey;
}
public void setMsgKey(String msgKey) {
this.msgKey = msgKey;
}
private String[] params;
public String[] getParams() {
return params;
}
public void setParams(String[] params) {
this.params = params;
}
}
3.struts.xml
<action name="itemInsteadAdd"></action> class="itemAction" method="itemInsteadAdd">
<exception-mapping exception="com.tw.twerp.exception.ApplicationException" result="error"></exception-mapping>
<result name="error" type="chain"></result>itemInsteadPreAdd
<result name="success" type="chain"></result>itemInsteadPreAdd
4.package com.tw.twerp.xwork;
public class ExceptionDisplayInterceptor extends ExceptionMappingInterceptor {
private static final long serialVersionUID = 2679293582391915433L;
@Override
protected void publishException(ActionInvocation invocation, ExceptionHolder exceptionHolder) {
Exception exception = exceptionHolder.getException();
if (exception instanceof ApplicationException) {
ApplicationException e = (ApplicationException) exception;
ActionSupport action = (ActionSupport) invocation.getAction();
// action.addActionError(action.getText(e.getMsgKey(), e.getParams()));
ServletActionContext.getRequest().setAttribute("APPLICATION_EXCEPTION", action.getText(e.getMsgKey(), e.getParams()));
}
super.publishException(invocation, exceptionHolder);
}
}
5.jsp页面:
加入<s:fielderror></s:fielderror>
6.资源文件:
。。。。。。。。。
ok!就是这么简单!