Struts入门教程(三)

来源:互联网 发布:开源 网络摄像头 编辑:程序博客网 时间:2024/05/01 21:29
本文内容:
7 视图选择
8 国际化
9 Struts中的异常处理


7 视图选择

局部转发与全局转发(优先级:局部转发的优先级比全局转发的优先级高)
1)局部转发:只对某个Action可见
<action …>
<forward name=”success” path=”/success.jsp” />
</action>

2)全局转发:对所有的Action可见(共享)
<global-forwards>
<forward name=”fail” path=”/fail.jsp” />
</global-forwards>
8 国际化

I18N解决办法
创建多个资源文件,根据用户设置选择不同资源文件
ApplicationResources.properties
ApplicationResources.zh_CN.properties
ApplicationResources.zh_TW.properties
资源文件:用于映射页面中的静态信息、按钮标签、错误信息等,通过一个属性文件(.properties)把所有页面的静态信息集中在一起,便于修改
编写资源文件的步骤:
1)编辑资源文件ApplicationResources.properties。
app.title=Welcome to ASD0702 HomePage
app.name=Student Management System

2)在JSP文件中使用<bean:message key=”app.title”/>标签输出资源文件中的值
3)在struts-config.xml文件中配置资源文件
<message-resources parameter=”abc” />

9 Struts中的异常处理

java class: try/catch/finally/throws/throw/custom Exception class
jsp: …
struts: try/catch/finally/throws/throw/custom Exception class
声明方式(*)——->struts-config.xml
定制异常处理器(*)

数据验证过程:
1)输入格式验证:    数据格式等验证
JavaScript(ActionForm:validate())
客户端完成

2)业务逻辑验证:    业务规则等验证
java(Action:execute())
服务器端完成

ActionErrors:异常的集合类
ActionMessage:具体异常类

name:<input type=”text” name=”name”/>
password:<input type=”password” name=”pass”/>

一种方法:在actionform的validate方法中处理
(1)重写action form的validate方法

public ActionErrors validate(ActionMapping actionMapping,
                            
HttpServletRequest httpServletRequest) {
      
/** @todo: finish this method, this is just the skeleton.*/
    
ActionErrors errors=new ActionErrors();
    
if(name==null || name.trim.length()==0){
        
ActionMessage message=new ActionMessage("error.username");//key,资源文件找value
        
errors.add("nullname",message);
    
}
    
return errors;
 
}

abc.properties

error.username=User name don’t exist!
(2)配置struts-config.xml文件
在action标记内添加一个input属性和validate属性
input属性的值表示发生错误后跳转到的页面
validate属性的值表示ActionServlet是否去执行ActionForm的validate(…)方法
这个属性默认值是true

<action-mappings>
        <
action input="/addStudent.jsp" name="studentForm" path="/addStudent" scope="request"
            
type="com.action.StudentAction" validate="true">
            <
forward name="error" path="/error.jsp" />
            <
forward name="success" path="/success.jsp" />
        </
action>
    </
action-mappings>

(3)在jsp页面中输出错误<html:errors/>

第二种处理方法:在action的execute方法中处理

(1)在action的execute方法中写错误处理的代码(和action form里valdiate方法的代码基本一致)
Action:
execute(…){
ActionErrors errors=new ActionErrors();
if(!name.equals(”narci”)){
ActionMessage message=new ActionMessage(”error.user.authorization”);
errors.add(”noauthorization”,message);
}
}

(2)
//比在form的validate方法多出的一步

(3)应该把action标记的validate属性设置为false
//把错误信息保存(html:errors标签才能找到errors)
saveErrors(request, errors);
<html:errors/>—->用于页面中显示异常信息(通过资源文件映射)

第三种,通过抛出异常处理错误(推荐使用:处理业务逻辑方面出现的错误)
(1)在action的方法中抛出异常
(2)在struts-config.xml声明该异常的处理方法(通过exception标记)
局部异常

<action input="/login.jsp" name="loginForm" path="/login"
    
scope="request" type="action.LoginAction" validate="true">
      <
exception key="error.noauthorization" path="/noauthorization.jsp"
      
type="exception.NoAuthorizationException"/>
      <
forward name="success" path="/success.jsp"/>
    </
action>

key=”error.noauthorization”                     异常提示信息仍然通过资源文件作映射
path=”/noauthorization.jsp”                     出现异常时的处理页面
type=”exception.NoAuthorizationException” Action处理业务过程中有可能出现的异常类型

全局异常(对所有的action共享的,所以优先级应该比较低)

<global-exceptions>
    <
exception key="error.global" path="/error.jsp" type="java.lang.Exception" />
  </
global-exceptions>

定制异常处理器(*)
ExceptionHandler
1)开发异常处理器类继承org.apache.struts.action.ExceptionHandler

public class NoAuthorizationExceptionHandler extends ExceptionHandler {
 
    
public ActionForward execute(Exception ex, ExceptionConfig config,
            
ActionMapping mapping, ActionForm formInstance,
            
HttpServletRequest request, HttpServletResponse response)
            
throws ServletException {
        
ActionForward forward = null;
        
ActionMessage error = null;
        
String property = null;
 
        
/*
         * Get the path for the forward either from the exception element or
         * from the input attribute.
         */

        
String path = null;
        
if (config.getPath() != null) {
            
path = config.getPath();
        
} else {
            
path = mapping.getInput();
        
}
        
// Construct the forward object
        
forward = new ActionForward(path);
 
        
/*
         * Figure out what type of exception has been thrown. The Struts
         * AppException is not being used in this example.
         */

        
if (ex instanceof BaseException) {
            
// This is the specialized behavior
            
BaseException baseException = (BaseException) ex;
            
String messageKey = baseException.getMessageKey();
            
Object[] exArgs = baseException.getMessageArgs();
            
if (exArgs != null && exArgs.length > 0) {
                
// If there were args provided, use them in the ActionError
                
error = new ActionMessage(messageKey, exArgs);
            
} else {
                
// Create an ActionMessage without any arguments
                
error = new ActionMessage(messageKey);
            
}
        
} else {
            
error = new ActionMessage(config.getKey());
            
property = error.getKey();
        
}
 
        
// Store the ActionMessage into the proper scope
        
// The storeException method is defined in the parent class
        
storeException(request, property, error, forward, config.getScope());
 
        
return forward;
    
}
}

2)覆盖execute()方法
3)通过struts-config.xml中异常声明设置异常类型与异常处理器之间的映射关系
****异常处理器处理完异常后,最后对用户的响应页面可在异常处理器中指定****

<exception key="error.noauthorization"
handler="exception.NoAuthorizationExceptionHandler"
path="/noauthorization.jsp"
type="exception.NoAuthorizationException"/>
原创粉丝点击