您的位置:首页 > 其它

4.Strut国际化动态文本(声明式处理异常,可以拥有多个占位符):业务逻辑层,自定义异常处理器

2012-08-27 16:24 531 查看
package com.bjpowernode.i18n;

public class UserManager {

public void login(String username, String password) throws ErrorCodeException{
if (!("admin".equals(username) && "admin".equals(password))) {
throw new ErrorCodeException("110", new Object[]{username, password});
}
}
}


package com.bjpowernode.i18n;

@SuppressWarnings("serial")
public class ErrorCodeException extends RuntimeException {

private String errorCode;// 错误码

private Object[] args; // 错误信息(从配置文件读取)的动态信息,用来替代占位符

public ErrorCodeException(String errorCode) {
this(errorCode, null);
}

public ErrorCodeException(String errorCode, Object args0) {
this(errorCode, new Object[]{args0});
}

public ErrorCodeException(String errorCode, Object[] args) {
this.errorCode = errorCode;
this.args = args;
}

public String getErrorCode() {
return errorCode;
}

public Object[] getArgs() {
return args;
}

}


package com.bjpowernode.i18n;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.util.ModuleException;

/**
* 个性化的异常处理类
* @author Administrator
*
*/
public class ErrorCodeExceptionHandler extends ExceptionHandler {

public ActionForward execute(
Exception ex,
ExceptionConfig ae,
ActionMapping mapping,
ActionForm formInstance,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException {

if (!(ex instanceof ErrorCodeException) ) {
return super.execute(ex, ae, mapping, formInstance, request, response);
}

ActionForward forward = null;
ActionMessage error = null;
String property = null;

// Build the forward from the exception mapping if it exists
// or from the form input
if (ae.getPath() != null) {
forward = new ActionForward(ae.getPath());
} else {
forward = mapping.getInputForward();
}

// Figure out the error
if (ex instanceof ModuleException) {
error = ((ModuleException) ex).getActionMessage();
property = ((ModuleException) ex).getProperty();
} else {
//error = new ActionMessage(ae.getKey(), ex.getMessage());

ErrorCodeException ece = (ErrorCodeException)ex;
error = new ActionMessage(ae.getKey(), ece.getArgs());

property = error.getKey();
}

this.logException(ex);

// Store the exception
request.setAttribute(Globals.EXCEPTION_KEY, ex);
this.storeException(request, property, error, forward, ae.getScope());

return forward;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐