1.1 Struts内部机制
MVC模式
MVC(Model模型,View视图,Controller控制器)
模型:
用于表示业务数据,调用业务逻辑,由系统状态Bean ActionForm和商业逻辑的JavaBean来构建
视图:
由JSP和Struts提供的自定义标签来实现
控制器:
负责控制流程,由ActionServlet负责读取struts-config.xml,并使用ActionMapping来查找对应的Action
1.2 添加Struts开发环境
1.2.1 使用MyEclipse添加
MyEclipse->add struts capabilities
Struts支持的包列表:
l antlr.jar
l commons-beanutils.jar
l commons-digester.jar
l commons-fileupload.jar
l commons-logging.jar
l commons-validator.jar
l jakarta-oro.jar
l struts.jar
1.2.2 Struts配置文件列表:
在/WebRoot/WEB-INF下添加了下列配置文件
l struts-config.xml
l struts-config.mex
l struts-html.tld
l struts-bean.tld
l struts-logic.tld
l struts-tiles.tld
l struts-nested.tld
1.2.3 手动添加
1、 添加Struts的jar支持包(8个)
…/WebRoot/WEB-INF/lib目录下
2、 添加Struts的tld标签文件(5个)
…/WebRoot/WEB-INF目录下
3、 添加Struts的核心配置文件Struts-config.xml
…/WebRoot/WEB-INF目录下
4、 在web.xml中添加Struts的ActionServlet配置
…/WebRoot/WEB-INF目录下
1.2.4 配置Struts日志组件
1、 添加日志组件包
Log4j-1.2.12.jar、commons-logging.jar,复制这两个文件到项目/WebRoot/WEB-INF/lib目录下即可。
2、 添加日志配置文件
commons-logging.properties(放入项目/WebRoot/WEB-INF目录下)
log4j.properties (放入项目web-inf/class目录下)
3、 修改commons-logging.properties调用log4j
在默认情况下commons-logging.properties中会配置使用SimpleLog,要配置使用Log4j,只需注释掉SimpleLog行,添加log4j即可
##set Log as Log4J
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
## set Log as SimpleLog
#org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
4、 Log4j配置文件log4j.properties
## LOGGERS ##
#define a logger
log4j.rootLogger=INFO,console,file
## APPENDERS ##
# define an appender named console, which is set to be a ConsoleAppender
log4j.appender.console=org.apache.log4j.ConsoleAppender
# define an appender named file, which is set to be a RollingFileAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=../logs/jdbc_bk.log
#set the log's size
log4j.appender.file.MaxFileSize=1000KB
log4j.appender.file.MaxBackupIndex=20
## LAYOUTS ##
# assign a SimpleLayout to console appender
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
# assign a PatternLayout to file appender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH:mm:ss}] %m%n
注:
log4j.properties文件需要放到web-inf/class目录下面,在eclipse里面放到src目录下面,会自动拷贝到class目录下面去。否则在tomcat启动的时候,会出现以下警告,且日志不会输出。
log4j:WARN No appenders could be found for logger (org.apache.commons.digester.Digester.sax).
log4j:WARN Please initialize the log4j system properly.
1.3 工作流程
1、 输入表单页面
如:
<form action="test.do" method="post">
<input type="text" name="str1">
<input type="text" name="str2">
<input type="submit">
</form>
2、 ActionServlet接收用户请求(Request)
在Web.xml中定义
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
... ...
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
表示Struts能够接收*.do的请求
3、 ActionMapping映射Action
通过struts-config.xml中的<action-mappings>来对应Action类
<action-mappings>
<action path="/test" name="testForm" scope="request"
type="com.demo.struts.forms.TestAction" input="/input.jsp">
<forward name="success" path="/success.jsp"></forward>
<forward name="failure" path="/error.jsp"></forward>
</action>
</action-mappings>
此处的test对应test.do
4、 ActionMapping映射ActionForm
通过struts-config.xml中的<form-beans>来对应ActionForm类
<form-beans>
<form-bean name="testForm" type="com.demo.struts.forms.TestForm"></form-bean>
</form-beans>
此处name="testForm",对应<action-mappings>中的name="testForm"
5、 ActionForward转发
Action处理完后返回ActionForward对象,对应<action-mappings>中转发的URL
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
ActionErrors errors=new ActionErrors();
TestForm testForm = (TestForm) form;
ActionForward forward =new ActionForward();
try{
String str1=testForm.getStr1();
String str2=testForm.getStr2();
}catch(Exception e){}
if(!errors.isEmpty()){
forward=mapping.findForward("failure");
}else{
forward=mapping.findForward("success");
}
return forward;
}
此处的failure,success分别对应:<action-mappings>中的forward
1.4 Struts配置文件详解
1.4.1 配置ActionForm:<form-beans>元素
1.4.2 配置映射关系:<action-mappings>
1.4.3 其他
1.4.4 分离Struts配置文件
1.5 ActionForm Bean开发技术
1.5.1 使用默认表单ActionForm
org.apache.struts.action.ActionForm
表示HTTP窗体中的数据,可以将其看做是模型和视图的中介
1.5.2 使用动态表单DynaActionForm
org.apache.struts.action.DynaActionForm
1.5.3 使用自动校验表单
org.apache.struts.validator.DynaValidatorForm
其中validator.xml和validator-rules.xml分别表示验证定义和验证规则的内容
1.6 Action组件开发技术
org.apache.struts.action.*
1.6.1 使用默认的Action
注:视图级的验证工作放在ActionForm来完成,比如输入不能为空、E-Mail格式是否正确等;而与具体业务相关的验证则放入Action中,这样就可以获得最大ActionForm重用性的可能。在执行业务逻辑的JavaBean中不要引用任何与Web应用相关的对象,比如HttpServletRequest、HttpServletResponse等对象,而应该将其转换为普通的Java对象
1.6.2 可直接转发的ForwardAction
1.6.3 可包含文件的IncludeAction
1.6.4 可自动分发的DispatchAction
通常,如果继承默认的Action类,只能完成一种业务操作。如果要完成一组业务操作,例如对用户进行update、insert、delete操作,则需要建立多个操作类,分别来接收响应。但DispatchAction来实现函数的分发。它的作用就是实现按业务实体划分类。
1、<action>中添加一个parameter
<action path="/test" parameter=”method” name="testForm" scope="request"
type="com.demo.struts.forms.TestAction" input="/input.jsp">
...
</action>
在<form>请求地址中传递了参数”method=test”
<form action="test.do?method=test" method="post">
...
</form>
在Action类中新建参数值对应的函数
public ActionForward test(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
...
return forward;
}
1.6.5 可进行多个提交的LookupDispatchAction
1.6.6 可实现交换的SwitchAction
1.7 使用Struts标签进行页面国际化
1.7.1 软件国际化与本地化
I18N:Internationalization的缩写,意即在i和n之间有18个字母,本意是指软件的“国际化”。支持多种语言,但同一时间只能是英文和一种选定的语言,例如英文+中文。
L10N:Localization。本意是软件的“本地化”。支持2种语言,英文和另外一种语言(例如中文)
M17N:Multilingualization。本意指软件的“多语言库”,用以实现各国语言间的代码移植。可以在同一时间支持多种语言,例如你可以在一个页面里看到中文、英文、德文等。
1.7.2 软件本地化的设置方法
1、 用户在软件操作界面中选择需要显示的语言来显示该软件。
2、 软件根据操作系统的语言设置,自动显示默认的操作语言。
为IE添加英语和中文显示的列表,工具->Internet选项->语言。
1.7.3 软件编码
1、 ASCII(单字节)
编码字符集:ISO-8859-1
英文DOS
2、 ANSI编码(双字节)
GB2312、BIG5等,中文DOS、中文/日文Windows95/98
3、 Unicode编码
UTF-8、UTF-16、UTF-32,WindowsNT/2K/XP、linux
1.7.4 Java对国际化的支持
1、 Locale类
Java.util.Locale类是最重要的Java I18N类
1) 通过构造函数创建Locale对象
如:
Locale chLocale=new Locale(“zh”,”CN”);//中国中文
第一个参数是语言代码,语言代码由两个小写字母组成,遵从ISO-639规范。
第二个参数是国家代码,由两大写字母组成,遵从ISO-3166规范。
使用默认定义的Locale对象
Locale locale1=Locale.JAPAN;
Locale locale2=new Locale(“ja”,”JP”);
取得操作系统的默认Locale对象
Locale defaultLocale=Locale.getDefault();
在Web应用中访问客户端的Locale对象
调用HttpServletRequest对象的以下两个方法来取得包含Web客户的Locale信息
Public java.util.Locale getLocale();
Public java.util.Enumeration getLocales();
ResourceBundle类
Java.util.ResourceBundle类提供存放和管理与Locale相关的资源的功能。这些资源包括文本域、按钮的Label、状态信息、图片名、错误信息和网页标题等。
1.7.5 Struts对国际化的支持
1、 创建Struts的ResourceBundle资源文件
2、 访问Resource Bundle资源文件
3、 在Struts应用中访问Resource Budle的方法
4、 在Struts应用中访问Resource Budle的组件。
1.7.6 Struts页面国际化的过程
1、 定义Struts的资源文件
在strust-config.xml中通过<message-resources>定义
<message-resources parameter="com.demo.struts.ApplicationResources" />
2、 创建Struts的资源文件
我们应该在包com.demo.struts.resources中创建UTF-8资源文件,这里的资源文件会被编译到/WEB-INF/classes/com.demo.struts.resources下。每一个资源文件是“键=值”对的集合。
资源文件的格式为:默认资源文件名_国别_语言.properties。其中每个文件都是通过%JAVA_HOME%/bin/native2ascii.exe工具转换而来。
如:
//ApplicationResources.properties;默认资源文件,通常里面的内容是英文的
Label.name=USERNAME;
Lable.password=PASSWORD;
//ApplicationResources_zh_CN.bak;默认资源文件,通常里面的内容是英文的
//它需要工具将其中的内容处理成UTF-8
Label.name=用户名;
Lable.password=密 码;
上面的中文资源文件中写的是中文,还需要用如下的命令专为UTF-8编码的资源文件。
native2ascii -encoding utf-8 ApplicationResources_temp.properties ApplicationResources_zh_CN.properties
3、 定义JSP页面的字符集合
<%@ page contentType="text/html;charset=UTF-8"%>
4、 在JSP页面获取资源文件里面的内容
<table width="200" border="1">
<tr>
<td align=”right”><bean:message key=”label.username”></td>
</tr>
<tr>
<td align=”right”><bean:message key=”label.password”></td>
</tr>
</table>
在这个页面显示的时候,如果客户的IE的语言集合是zh_CN的话,就会显示:
用户名:
密 码:
如果客户的IE的语言是en的话,就会显示:
USERNAME:
PASSWORD:
1.7.7 Struts HTML标签
使用Struts HTML标签需要通过以下配置
1、 在web.xml中注册标签库
2、 确信将struts-html.tld文件复制到WEB-INF目录中。
3、 在运用标签库的每个JSP页面中,插入下面的<taglib>指示符
1.7.7.1 用于生成基本的HTML元素的标签
1、 <html:html>标签
用于生成HTML的<html>元素
2、 <html:base>
3、 <html:link>
4、 <html:rewrite>
1.7.7.2 用于生成HTML表单的标签
1、 <html:form>
2、 数据输入标签
<html:text>
<html:password>
<html:hidden>
<html:textarea>
<html:radio>
<html:checkbox>
<html:select>
<html:option>
3、 提交按钮标签
<html:submit>
<html:cancel>
<html:reset>
<html:button>
<html:image>
1.7.7.3 用于显示错误或正常消息的标签
<html:errors>:用于显示错误消息
<html:messages>:用于显示正常消息
1.7.8 Struts Bean标签
1.7.8.1 用于访问HTTP请求信息或JSP隐含对象
1、 <bean:cookie>
2、 <bean:header>
3、 <bean:parameter>
4、 <bean:page>
1.7.8.2 用于访问Web应用资源
1、 <bean:message>:用于显示ResourceBundle 中的消息。
用来从指定的locale中取回国际化的消息并输出。这个过程可以传递5个以内的参数。Message标签有两种指定message key的方式,一是通过key属性直接指定;二是通过name和property属性间接的指定,其中message key是在message resources文件中定义的。
如:
<bean:message key=”login.page.title”>
2、 <bean:resource>
3、 <bean:struts>
4、 <bean:include>
1.7.8.3 用于定义或输出JavaBean的Bean标签
1、 <bean:define>
2、 <bean:write>
3、 <bean:size>
1.7.9 Struts Logic标签
1.7.9.1 进行比较运算的Logic标签
<logic:equal>
<logic:notEqual>
<logic:greaterEqual>
<logic:greaterThen>
<logic:lessEqual>
<logic:lessThan>
1.7.9.2 进行字符串匹配的Logic标签
<logic:match>
<logic:notMatch>
1.7.9.3 判断指定内容是否存在的Logic标签
<logic:empty>和<logic:notEmpty>
<logic:present>和<logic:notPresent>
<logic:messagesPresent>和<logic:messagesNotPresent>
1.7.9.4 进行循环遍历的Logic标签
<logic:iterate>
1.7.9.5 进行请求转发或重定向的Logic标签
<logic:forward>
<logic:redirect>
1.8 Struts数据验证
1.8.1 使用Validator校验器组件
ActionForm Bean提供了Validator的一个ActionForm子类,它提供验证或存储错误消息的功能
Validator使用两个XML配置文件来分别确定安装哪个验证程序,以及如何将它们用于给定的应用程序
Validator-rules.xml:说明应该被插入到框架中的验证程序,并提供每个验证的逻辑名称
Validation.xml:确定哪个验证程序应用到哪个ActionForm Bean。
配置使用Validator
1、 在struts-config.xml中配置使用validator插件
<plug-in className="ora.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml" />
</plug-in>
注:你的应用程序的struts-config.xml文件必须与Struts Configuration Document Type Definition(Struts配置文档类型定义,DTD)一致,后者规定文件中元素出现的顺序。所以必须把Validator插件定义放到该文件的适当位置,一般放到<message-resources>下
2、 Validator验证程序配置文件validator-rules.xml
3、 使用Validator的两个父类来创建自己的表单类
为了使用Validator,你的应用程序的ActionFormBean必须归到Validator的ActionForm的某一子类。Validator提供了两个父类ValidatorForm和DynaValidatorForm
1) 使用普通的验证表单类ValidatorForm
在struts-config.xml文件中配置这个特定的ActionForm Bean,与配置正常的方法相同
<form-bean name="loginForm" type="com.demo.struts.forms.LoginForm"></form-bean>
2) 使用动态表单类DynaValidatorForm
<form-bean name="loginForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name=”username” type=”java.lang.String”/>
<form-property name=”password” type=”java.lang.String”/>
</form-bean>
4、 配置表单的验证规则validation.xml
用于声明将应用到ActionForm Bean的一组验证。
5、 绑定验证中的错误消息ApplicationResources.properties
使用Struts的资源绑定(Resource Bundle)机制将错误消息具体化。
1.8.2 在ActionForm中检验合法性
Validator框架针对表单数据的验证提供了可配置的系统,从而为核心Struts框架添加了很多有价值的功能。然而Validator的开发和配置过程,被设计了多个额外的配置文件,无疑让开发更加复杂化。
我们可以在ActionFormBean对象的validate()方法中编写验证逻辑代码。此外,还必须编写代码来存储验证失败的出错消息。
1.8.2.1 为ActionForm添加表单验证功能
1、 添加一个验证函数validate(),该函数继承其父类ActionForm
public ActionErrors validate(ActionMapping arg0, HttpServletRequest arg1) {
ActionErrors errors=new ActionErrors();
String queryString=arg1.getQueryString();
if(queryString.equalsIgnoreCase("method=register")){
if(username==null||username.equals("")){
errors.add("username", new ActionMessage("register.error.username"));
}
if(password1==null||password1.equals("")){
errors.add("password1", new ActionMessage("register.error.password1"));
}
...
}
arg1.setAttribute("registerFormBean", this);
return errors;
}
2、 ApplicationResources.properties中添加标签
#loginForm
login.error.username=用户名不能为空
login.error.password=密码不能为空
3、 JSP页面中输出错误信息
<tr>
<td><bean:message key="login.page.username" /></td>
<td><input type="text" name="username"> <html:errors property="username"/>
</td>
</tr>
1.8.2.2 为Action添加逻辑验证功能
1、 Action的execute()中修改检验代码
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionMessage("login.message.failed"));
2、 ApplicationResources.properties中添加标签
#loginForm
login.message.failed=用户名或密码不存在!
3、 JSP中输出这个全局错误信息
<html:errors property="org.apache.struts.action.GLOBAL_MESSAGE"/>
1.8.2.3 验证出错时维持表单输入
1、 ActionForm的validate()后面添加如下代码
request.setAttribute("loginFormBean", this);
2、 在Action的execute()后面添加
request.setAttribute("loginFormBean", loginForm);
3、 修改JSP表单
<tr>
<td><bean:message key="login.page.username" /></td>
<td>
<logic:present name="loginFormBean">
<html:text property="username" name="loginFormBean" />
</logic:present>
<logic:notPresent name="loginFormBean">
<input type="text" name="username">
</logic:notPresent>
<html:errors property="username"/>
</td>
</tr>
使用<logic:present>标签判断Bean对象loginFormBean是否存在,如存在则使用<html:text>输出属性”username”的值;如不存在,则依然输出空的HTML表单
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/rollice/archive/2009/04/25/4123494.aspx