重温经典struts1之自定义全局异常处理类处理异常以及<exeception>标签的配置

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

前言

前面的文章,我们学习了,Action类中调用Service,通过try…catch代码块,catch自定义异常类,通过ActionMessage类,进行错误信息页面显示,
今天我们来学习,自定义全局异常处理类,无需try…catch代码块,通过配置struts-config.xml文件中的< exeception>标签,统一处理异常,将错误信息显示到页面


需求

如下图所示,
写一个login页面
当用户名和密码不等于admin时,
login页面上显示错误信息:用户名和密码错误

重温经典struts1之自定义全局异常处理类处理异常以及<exeception>标签的配置_第1张图片

具体实现步骤

  1. 自定义MyException异常类
    继承RuntimeException类,定义messageKey和args变量,提供get和set方法,来接收错误消息key和参数内容
    这里注意args变量是object数组类型,可以接收多个参数

MyException异常类代码如下:

package xxx.xxx.exception;

public class MyException extends RuntimeException {

	private String messageKey;

	private Object[] args;

	public String getMessageKey() {
		return messageKey;
	}

	public void setMessageKey(String messageKey) {
		this.messageKey = messageKey;
	}

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

	public void setArgs(Object[] args) {
		this.args = args;
	}

	public MyException(String messageKey) {
		this(messageKey, null);
	}

	public MyException(String messageKey, Object arg) {
		this(messageKey, new Object[] { arg });
	}

	public MyException(String messageKey, Object[] args) {
		this.messageKey = messageKey;
		this.args = args;
	}

}
  1. 自定义MyExceptionHandler全局异常处理类
    继承ExceptionHandler类,放行自定义MyException以外的异常类,处理我们自定义的异常类,同样,将自定义异常类的消息key和参数赋值到ActionMessage类,返回到页面显示

MyExceptionHandler异常处理类代码如下:

package xxx.xxx.handler;

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;

import xxx.xxx.exception.MyException;

public class MyExceptionHandler extends ExceptionHandler {

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

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

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

		if (ae.getPath() != null) {
			forward = new ActionForward(ae.getPath());
		} else {
			forward = mapping.getInputForward();
		}

		MyException ece = (MyException) ex;
			error = new ActionMessage(ece.getMessageKey(), ece.getArgs());
			property = error.getKey();

		this.logException(ex);

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

		return forward;
	}
}

  1. 将自定义MyException异常类和MyExceptionHandler异常处理类,配置到struts-config.xml文件中的< global-exceptions>< exception>标签内,交给struts管理

struts-config.xml代码如下:

	<global-exceptions>
		<exception key=""
		           type="xxx.xxx.exception.MyException"
		           handler="xxx.xxx.handler.MyExceptionHandler"/>
	global-exceptions>
  1. UserService类中验证用户名和密码,错误时,抛出自定义MyException的异常类
    错误消息内容的login.error,是定义在国际化资源文件中。
    具体内容参看我之前的文章
    重温经典struts1之国际化(I18N)

UserService 代码如下:

package xxx.xxx.service;

import xxx.xxx.exception.MyException;

public class UserService {

	public void login(String username, String password) {
		if (!"admin".equals(username) || !"admin".equals(password)) {
			throw new MyException("login.error", username);
		}
	}

}

  1. action类调用UserService类完成用户名和密码验证
    通过下边的示例,可以看到,action中调用service的异常处理代码变得比较简洁。

Action类代码如下:

package xxx.xxx.action;

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

import org.apache.struts.action.Action;
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.ActionMessages;

import xxx.xxx.form.LoginForm;
import xxx.xxx.service.UserService;

public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		LoginForm lf = (LoginForm) form;
		String username = lf.getUsername();
		String password = lf.getPassword();

		UserService userService = new UserService();

		ActionMessages messages = new ActionMessages();

		userService.login(username, password);

		ActionMessage message = new ActionMessage("login.success", username);
		messages.add("login.success", message);
		this.saveMessages(request, messages);

		return mapping.findForward("success");

	}
}

总结

到这里我们就完成了自定义全局异常处理类处理异常以及将其配置到struts-config.xml的<exeception>标签中,运行效果在文章开头需求中的图可以看到,欢迎留言交流,下篇见。

你可能感兴趣的:(struts1,Struts1)