下午搞了一下Struts处理异常的框架,不错,确实很好用,可以省很多事,闲话暂且不表,进入正题

     首先新建一个项目,然后要做的第一步当然是——添加Struts支持啦~~呵呵。

     找到struts-config.xml文件,如果想配置全局异常处理,则需要在<global-exceptions></global-exceptions>之间设置,如果只想单独为某个Action设置其异常处理,则将设置写在<action></action>之间即可,具体配置很简单,代码如下:

     

exception
  key="unLogin"<!--对应资源文件中的key,用于错误显示-->
  path="/index.jsp"
<!--出错了程序会跳到哪里去关于Struts处理异常框架的小例子.-->
  type="java.lang.Exception" 
<!--捕获异常的类型-->/>

     接下来测试一下吧,写一个登陆页面,提交到某个action里面,当用户名为空时抛出Exception,当然你也可以编写自己的Exception类,然后在配置文件中作相应的修改就可以了。

index.jsp代码如下:

 

 


  <head>
    
<html:base />
    
    
<title>index.jsp</title>
  
</head>
  
  
<body><html:errors/>
    
<html:form action="/login" method="post" focus="login">
      
<table border="0">
        
<tr>
          
<td>Login:</td>
          
<td><html:text property="username" /></td>
        
</tr>
        
<tr>
          
<td>Password:</td>
          
<td><html:password property="password" /></td>
        
</tr>
        
<tr>
          
<td colspan="2" align="center"><html:submit /></td>
        
</tr>
      
</table>
    
</html:form>
  
</body>
</html:html>

loginAction代码如下:

 


 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.lc.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 com.lc.LoginForm;

/** 
 * MyEclipse Struts
 * Creation date: 07-30-2008
 * 
 * XDoclet definition:
 * @struts.action path="/login" name="loginForm" input="/form/login.jsp" scope="request" validate="true"
 * @struts.action-exception key="unLogin" path="/index.jsp"
 
*/
public class LoginAction extends Action {
    
/*
     * Generated Methods
     
*/

    
/** 
     * Method execute
     * 
@param mapping
     * 
@param form
     * 
@param request
     * 
@param response
     * 
@return ActionForward
     * 
@throws Exception 
     
*/
    
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) 
throws Exception {
    LoginForm loginForm 
= (LoginForm) form;// TODO Auto-generated method stub
    if(loginForm.getUsername()==null||loginForm.getUsername().equals("")){
        
throw new Exception();
    }
    
return mapping.findForward("login");
    }
}

     接下来测试一下吧,异常被捕获了,login.do被重定向到了index.jsp中去,测试结束。

     虽然这是一个很小的例子,但是足以感觉到运用到实际中可以省很多事,项目中异常的处理不再需要无数个try/catch块组合,只需要在xml文件中进行简单设置即可。

相关文章:

  • 2022-01-21
  • 2021-09-23
  • 2022-12-23
猜你喜欢
  • 2021-04-22
  • 2021-11-28
  • 2022-12-23
  • 2021-09-23
  • 2021-09-15
  • 2021-09-26
  • 2021-09-11
相关资源
相似解决方案