上篇博客:詳解Java異常處理——簡介 簡單介紹了Java異常處理,這篇博客具體講解Java異常處理過程——編程式異常處理。
編程式異常處理是以前我們經常用到的一種異常處理方法,簡單點說,編程式異常處理就是用try、catch的方式截獲異常以後,手工對異常進行處理。下面我以一個簡單的登錄實例爲大家演示一下編程式異常處理具體是如何實現的。
目錄結構
以下是幾個核心類的代碼。
UserManager.java
package struts;
public class UserManager {
public void login(String username, String password) {
if (!"admin".equals(username)) {
throw new UserNotFoundException();
}
if (!"admin".equals(password)) {
throw new PasswordErrorException();
}
}
}
package struts;
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;
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginActionForm laf = (LoginActionForm)form;
String username = laf.getUsername();
String password = laf.getPassword();
UserManager userManager = new UserManager();
ActionMessages messages = new ActionMessages();
try {
userManager.login(username, password);
//創建國際化消息文本
ActionMessage message = new ActionMessage("login.success", username);
messages.add("login_success_1", message);
//傳遞國際化消息
this.saveMessages(request, messages);
return mapping.findForward("success");
}catch(UserNotFoundException e) {
e.printStackTrace();
//創建國際化消息文本
ActionMessage error = new ActionMessage("login.user.not.found", username);
messages.add("error_1", error);
//傳遞國際化消息
this.saveErrors(request, messages);
}catch(PasswordErrorException e) {
e.printStackTrace();
//創建國際化消息文本
ActionMessage error = new ActionMessage("login.password.error");
messages.add("error_2", error);
//傳遞國際化消息
this.saveErrors(request, messages);
}
return mapping.findForward("error");
}
}
login.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<%-- <html:errors/> --%>
<form action="login.do" method="post">
用戶名:<input type="text" name="username"><br>
密碼:<input type="password" name="password"></br>
<input type="submit" value="登錄">
</form>
</body>
</html>
login_error.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<font color="red">
<html:messages id="msg" property="error_1">
<bean:write name="msg"/>
</html:messages>
</font>
<font color="blue">
<html:messages id="msg" property="error_2">
<bean:write name="msg"/>
</html:messages>
</font>
</body>
</html>
login_success.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<html:messages id="msg" message="true">
<bean:write name="msg"/>
</html:messages>
</body>
</html>
國際化資源文件MessageResources.properties
errors.header=<UL>
errors.prefix=<font color="red"><LI>
errors.suffix=</LI></font>
errors.footer=</UL>
login.success={0},Login Success
login.user.not.found=User Not Found,UserName\=[{0}]
login.password.error=Password Error
struts-config.xml配置文件
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="loginForm" type="struts.LoginActionForm"/>
</form-beans>
<action-mappings>
<action path="/login"
type="struts.LoginAction"
name="loginForm"
scope="request"
>
<forward name="success" path="/login_success.jsp" />
<forward name="error" path="/login_error.jsp"/>
<!-- <forward name="error" path="/login.jsp"/> -->
</action>
</action-mappings>
<message-resources parameter="resources.MessageResources" />
</struts-config>
運行結果如下:
以上就是編程式異常處理的詳細過程,我們可以看出,這種方式對異常的處理粒度比較細,實現也較爲複雜。它的優點是:可以根據具體的異常自定義處理過程,處理較爲靈活。當然,異常處理的方法遠不止這一種,有沒有更簡單的方法呢?有,但是這裏的簡單是以犧牲處理的靈活性爲代價的。所以,我們在選擇異常處理方法的過程中,要充分了解自己的需求,在簡單和靈活性之間做出判斷,選擇適合自己業務的異常處理方法。
下篇博客將爲大家介紹一種更爲簡單的異常處理方法。