尚学堂-马士兵Struts2教学视频之Struts2 学习笔记
- 格式:doc
- 大小:772.67 KB
- 文档页数:41
Struts1是一个优秀的框架,但是还是具有很多不好的地方,如Action和ActionForm严重倚赖系统框架中的API。
如ActionForm必须继承ActionForm,Action控制器继承Action,测试麻烦。
Struts2是基于webwork发展而来,并非struts1使用MyEclipse8.5版本,可自动添加依赖struts2的系统库Struts2原理:说明:Struts2没使用Servlet作为核心控制器,而是换做一个Filter过滤器来进行,其类是org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 过滤器所拦截的请求是<url-pattern>/*</ url-pattern>(当然根据版本的不同,过滤器类也不同,如Org.apache.Struts2.dispatcher.FilterDispatcher)如果请求中带有.action或.do,则转入Struts2框架处理。
配置文件:Web.xml中:<filter><filter-name>struts2</filter-name><!-版本不同这里的配置不同-→<!—<filter-class>Org.apache.Struts2.dispatcher.FilterDispatcher</filter-class>→<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFi lter</filter-class><init-param><param-name>config</param-name><param-value>struts-default.xml,struts-plugin.xml,../struts.xml </param-value></init-param></filter><filter-mapping><filter-name>struts2</ filter-name><url-pattern>/*</ url-pattern></filter-mapping>Struts.xml<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN""/dtds/struts-2.1.dtd"> <struts><!—这个package可以处理文件同名的情况,一般不会更换-- ><package name="default"extends="struts-default"namespace="\"> <action name="Login"class="com.test.action.LoginAction"><result name="cheng">/index.jsp</result><result name="bai">/fail.jsp</result></action></package></struts>配置文件说明:1、package中的name为了区分不同的包2、extends是继承的包名3、namespace是提交时区分的地址,如namespace=”user”,则提交时需要加入action=”/user/xxx.action”控制其中的代码,其中数据直接封装和页面表单元素名称对应。
1、namespaece(最好用模块的名字命名)Namespace 为空时,用于处理其他package不能处理的全部的action2、Package 用于区分重名的情况3、copy项目的方法及注意事项修改它的启动项引入别人的项目的方法4、action4`1修改文件的默认编码4`2每次访问action都重新new出一个新的对象,不存在同步的问题执行过程4`3Action 继承ActionSupport5、路径:获取系统绝对路径<% String context = request.getContextPath(); %><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>使用绝对路径6、ActionMethod动态调用方法7、ActionWildcard通配符使用通配符,将配置量减到最低约定优于配置8、数值传递ActionAttrParamInputDomainModelDrivenModel过程9、中文问题 2.1.6.的bug不能解决中文问题10、11、value stack值栈< s:property value=“Name”/>取值栈中的数值如:< s:property value=“error”/>< s:property value=“[0]Propertyvalue是一个map,name就是key name is error 就是value 13、访问页面元素访问Stack Context中的元素14、include,模块包含15、认Action (好处:访问不存在时自动跳转带默认页)Default-action-ref默认action引用16、result类型1)默认是dispatcher 常用服务器端跳转2)Rdiect 只能是视图不能是action 客户端跳转,最后显示jsp3)Chain ---forwordaction action前不可以加”/”action之间的跳转,最后显示action4)RedirectAction action跳转,最后显示jsp服务器断的跳转:17、Global_ResultExtends =“要继承的包名“Result name属性:18、取value stack中的值动态绑定的。
Struts2项目的构建与配置1.配置struts.xml(1)配置struts.xml可以参考下载的struts-2.3.14.1-all.zip解压后的apps文件夹下的参考项目的struts.xml文件。
(2)主要的配置如下:<constant name="struts.devMode"value="true"/><package name="hello"namespace="/"extends="struts-default"><action name="hello"><result>/hello.jsp</result></action></package><constant name="struts.devMode"value="true"/> value="true"表示是开发模式,当修改了配置时服务器会自动加载修改后的配置,不需要中期服务器,方便开发。
(3)namespace="/"与浏览器的访问地址有关,namespace的默认值为空。
(4)<action name="hello"><result>/hello.jsp</result></action> action的name值与浏览器的访问地址有关,当地址是“http://…/hello”时,浏览器就会返回result中的hello.jsp 的页面。
2.配置web.xml(1)配置web.xml也可以参考下载的struts-2.3.14.1-all.zip解压后的apps文件夹下的参考项目的web.xml文件(2)主要配置如下:<filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>3.配置Struts2的jar包(1)复制下载的struts-2.3.14.1-all.zip解压后的apps文件夹下的参考项目的WEB-INF\lib文件夹下的所有的jar包到我们自己项目的WEB-INF\lib文件夹下即可。
1.包头的设置name是struts的包,与Java的包名效果类似,但不是按项目中SRC中包名设置的。
namescape是该包的命名空间。
将作为访问该报Action的路径的一部分。
默认命名空间为namescape=””;假设form 表单提交给helloworld的action ,其action=”/test/helloworld”exctends是表示该包继承的其他包struts_default是任何包都必须继承的包。
否则无法使用struts的核心功能,比如参数上传到action,文件上传,数据校验等。
abstract=”true”定义为抽象包,不得包含Action。
2.action的查找顺序(1)寻找namespace为path1/path2/path3/的包,有这个包:寻找test的Action有这个action:执行没有这个action:寻找namespace为””的命名空间(默认命名空间)是否有这action,没有的话提示找不到action没有这个包:寻找namespace为path1/path2/的包重复(1)步骤。
3.action的默认属性4.Action中各种result的转发类型dispatcher(默认类型)redirect(重定向)redirectAction (重定向到新的Action)plainText (显示原始文件内容)result转发还可包含参数,该参数取自Action中的属性。
例:<action name=”login” class=”xxxx.xxx.xxx.sdsds”><result name=”sucess”> /aaa.jsp?username=${ssss}</result></action>其中ssss是login这个Action中所必须具有的属性redirect书写格式1.<result name=”sucess” type=”redirectAction”>login</result>该写法只能访问位于同一包中的Action;2. <result name=”sucess” type=”redirectAction”><parma name=”actionname”>login</parama><parma name=”namespace”>/xxxxx</parama></result>该写法可访问位于其他包的ActionplainText书写格式1.<result type=”plainText”>/login.jsp</result>2. <result type=” plainText”><parma name=”location”>/login.jsp</parama><parma name=”charSet”>UTF-8</parama></result>全局转发只能在包内定义全局转发。
一:Struts2标签库
2. Generic Tag
二:OGNL
值栈的含义正如它的名字所表示的那样——对象所组成的栈。
OGNL的全称是Object
Graph Navigational Language(对象图导航语言),提供了访问值栈中对象的统一方式。
它是一种功能强大的表达式语言(Expression Language,简称为EL),通过它简单一致的表达式语法,可以存取对象的任意属性,调用对象的方法,遍历整个对象的结构图,实现字段类型转化等功能。
几个概念
1. ActionContext: ActionContext是Action上下文,可以得到request session application
一次Action调用都会创建一个ActionContext
调用:ActionContext context = ActionContext.getContext()
2. ValueStack: 是值栈存放表单中的值
由OGNL框架实现, 可以把它简单的看作一个List
3. Stack Object:放入stack中的对象,一般是action。
Stack Context stack上下文也是用来存值的
Stack Context(map):stack上下文,它包含一些列对象,包括request/session/attr/application map等。
struts2课堂笔记一、环境配置1、下载struts2所需包()2、解压空项目(apps/struts2-blank)3、复制项目中的web.xml(WEB-INF文件夹中),并修改web.xml起始默认页4、复制项目中lib(WEB-INF文件夹中)下面的所有包5、复制项目中的struts.xml(WEB-INF\classes文件夹中),留下xml的定义头、struts和package标签,其他的全部删除6、配置struts.xml的提示,window-references-xml Calalog-addLocation:struts-2.3.dtd所在路径(struts-2.3.3\src\core\src\main\resources)Key Type:URIKey:/dtds/struts-2.3.dtd7、新建action可以继承ActionSupport类或实现Action接口8、配置struts.xml,package标签中增加action标签,指定name属性(该属性为必填属性,别名的作用),可以指定class属性(class为选填属性,表示别名对应的action类)9、jsp页面可以直接使用上面配置的action的name属性值了(一般使用范围:form的action,a标记的href)二、struts.xml配置1、参考struts-2.3.3\src\core\src\main\resources\struts-2.3.dtd配置2、参考struts-2.3.3\src\core\src\main\resources\struts-default.xml配置result-types:action中结果类型的配置(很少用)interceptors:拦截器定义(下节重点)default-interceptor-ref:声明默认拦截器引用(下节重点)default-action-ref:声明默认actiondefault-class-ref:声明默认的classglobal-results:全局返回结果(常用于登陆或出错了)global-exception-mappings:全局异常处理action:action的配置(此节重点介绍)<action name="..." class="..." method="...">-action中方法名为execute时,此处method可以省略配置<result name="..." type="...">-action返回值为success时,此处name可以省略配置<param name="...">...</param></result></action>type:掌握chain,dispatcher(默认),redirect,redirectAction,stream内部转发(chain,dispatcher)重定向(redirect,redirectAction)跳转页面(dispatcher,redirect)跳转action(chain,redirectAction)三、校验框架校验execute方法(方法执行顺序:validate-execute)1、在action中编写validate方法2、如果验证出错了可以用:this.addFieldError("...","...");或this.addActionError("...");或this.addMessage("...");来增加错误提示3、前台JSP页面可以用<s:filederror filedName="..." />或<s:actionError />或<s:message />或EL表达式(${errors[0].name})4、如果action中增加错误,则action中的execute方法是不会执行的,并且会自动返回input,所有在struts.xml中配置action的时候一定要配置返回结果为input的类型校验自定义方法(方法执行顺序:validate-validateTest-test)1、如自定义方法名为test,则增加validateTest方法实现校验2、其他步骤和上面execute方法的校验一样3、注意事项(自定义校验注意方法名的大小写规范,注意方法的执行顺序)配置校验(action名-validation.xml)参考xwork-core-2.3.3.jar下的com.opensymphony.xwork2.validator.validators下的default.xml文件配置提示(见第1章):struts-2.3.3\src\xwork-core\src\main\resources\xwork-validator-1.0.2.dtd验证器说明required:验证非数字是否非空requiredstring:验证字符串字段是否非空int:验证是否为数字long:验证长数字short:验证短数字double:验证小数date:验证日期email:验证邮箱url:验证URL地址stringlength:验证字符串长度regex:验证正则表达式四、拦截器和Action通配拦截器编写与配置(参考struts-2.3.3\src\core\src\main\resources\struts-default.xml配置)1、拦截器编码新建拦截器类,实现Interceptor接口或继承AbstractInterceptor抽象类2、拦截器的定义在struts.xml中增加<interceptors>标签(参考第2章struts.xml配置)在<interceptors>标签中增加<interceptor name="..." class="...">标签3、拦截器栈的定义在<interceptors>标签中增加<interceptor-stack name="...">标签在<interceptor-stack name="...">标签中添加拦截器的引用(参考第4点)4、拦截器的引用在<action>标签下增加<interceptor-ref name="...">标签引用配置好的拦截器或拦截器栈5、默认拦截器增加<default-interceptor-ref name="...">标签引用拦截器或拦截器栈6、拦截器的执行顺序action中的拦截器-默认拦截器-继承的拦截器7、struts2提供的拦截器defaultStack:struts2提供的拦截器(配置了自定义拦截器之后,一定要把默认的拦截器加上,否则会导致struts2的很多功能无法使用)Action通配(*)配置Action的时候要注意约束规则(包括大小写)<action name="*_*" class="com.zit.action.{1}Action" method="{2}"><result><param name="location">{1}{2}success.jsp</param></result><result name="input"><param name="location">{1}{2}.jsp</param></result></action>提交的action别名:student_addaction类名:com.zit.action.studentActionmethod方法名:add成功页面:studentaddsuccess.jsp失败页面:studentadd.jsp五、OGNLOGNL表达式(<s:debug>标签的应用)1、Value Stack(可以直接访问,例:<s:property value="name" />)2、Action Context(访问时候需要加#号,例:<s:property value="#" />)掌握的三个符号#(1.访问非值栈的内容2.构造Map集合3.投影())%(和javascript中的eval用法类似)$(EL表达式所用)六、标签库需要掌握的标签:<s:property><s:date><s:debug><s:if><s:elseif><s:else><s:iterator><s:form><s:textfiled><s:password><s:hidden><s:radio><s:checkboxlist>七、上传下载上传文件1、编写页面代码参考struts2-core-2.3.3.jar\org.apache.struts2.interceptor\FileUploadInterceptor.class代码<form action="upload" method="post" enctype="multipart/form-data"><input type="file" name="file" /><input type="submit" value="上传" /></form>2、编写Actionpublic class UploadAction extends ActionSupport {//待上传的文件private File file;//文件名,注意命名private String fileFileName;//文件类型,注意命名private String fileContentType;@Overridepublic String execute() throws Exception {//获取项目所在根目录下的upload文件夹String path=ServletActionContext.getServletContext().getRealPath("/upload");//定义输入输出字节流InputStream is=null;OutputStream os=null;try {//指定待上传的文件is=new FileInputStream(file);//指定上传之后存放的路径os=new FileOutputStream(path+"//"+fileFileName);byte[] b=new byte[1024];int len=0;while((len=is.read(b, 0, 1024))>0){os.write(b, 0, len);}} catch (Exception e) {e.printStackTrace();}finally{os.close();is.close();}return SUCCESS;}//省略getter/setter}3、配置struts.xml<action name="upload" class="com.zit.action.UploadAction"><result><param name="location">index.jsp</param></result></action>配置上传文件限制大小(默认2M)参考:struts2-core-2.3.3.jar\org.apache.struts2\default.properties在package标签上面增加<constant name="struts.multipart.maxSize" value="2097152"></constant>,改变value值配置上传文件的临时存储空间<constant name="struts.multipart.saveDir" value="c://temp"></constant>上传文件注意事项:1、前台页面表单一定要修改属性enctype="multipart/form-data"和method="post"2、如果要使用多文件上传,修改上面action代码为数组类型(File[],String[]),下面用循环即可下载文件1、编写页面代码<form action="download" method="post" id="myform"><input type="hidden" name="name" id="myfile" /></form><s:iterator value="list" var="s"><div class="show" onclick="getName('<s:property value="s" />');"><s:property value="s" /></div></s:iterator>function getName(name){var myform=document.getElementById("myform");var myfile=document.getElementById("myfile");myfile.value=name;myform.submit();}2、编写Action代码public class DownLoadFileAction extends ActionSupport {private String name;public InputStream getInputStream() throws Exception{String path=ServletActionContext.getServletContext().getRealPath("/upload");return new FileInputStream(path+"//"+name);}public String getName() throws Exception {//转换编码return URLEncoder.encode(name,"utf-8");}public void setName(String name) { = name;}}3、配置struts.xml参考:struts2-core-2.3.3.jar/org.apache.struts2.dispatcher/StreamResult.class<action name="download" class="com.zit.action.DownLoadFileAction"><result type="stream">//${name}一定要和前台JSP中传递过来的名字保持一致<param name="contentDisposition">attachment;filename=${name}</param>//此参数的名字一定要和Action中的方法名保持一致,如:inputStream,action 中一定要有个方法叫做getInputStream<param name="inputName">inputStream</param></result></action>下载注意事项:1、下载文件编码问题(用post提交请求)2、配置文件和后台action的对应3、下载的时候配置文件中的结果类型要用stream。
Struts2 学习笔记---wjt276 [二○一○年一月五日完]目录01 Struts2-Action (5)一、Struts作用: (5)二、搭建Struts2的运行环境: (5)三、Namespace (6)四、<package>标签 (6)五、Action (6)六、路径问题的说明 (8)七、Action的动态调用方法 (8)八、Action通配符(wildcard)的配置 (9)九、Action的属性接收参数 (10)1、在Action添加成员属性接受参数 (10)2、域模型(Domain Model) (10)3、ModelDriven接收参数 (11)十、Action属性接收参数中文问题 (12)十一、简单数据验证 (12)十二、访问Web元素 (14)一、方法一:ActionContext方式 (15)二、方式二:Ioc(控制反转)—推荐使用 (15)三、方式三:获取原类型 (16)四、方式四:获取原类型-控制反转 (17)十三、Struts2配置文件模块化包含(include) (17)十四、默认的Action (18)十五、Action总结 (18)02 Struts2-Result (19)一、Result类型 (type) (19)二、全局结果集(Globle Result) (20)三、动态的结果集(dynamic result) (21)四、带参数的结果集 (21)五、Result总结 (22)六、项目经理: (22)03 OGNL表达式语言 (23)04 Struts2-Tags (28)Struts2标签目录 (28)一、property标签 (28)二、set标签 (29)三、bean标签 (29)四、<include>标签-少使用 (29)五、If elseif else (30)六、Iterator标签 (31)七、Theme (31)05设计约定(编码规定) (32)06 项目开发顺序 (32)07 声明式异常处理 (33)08 国际化 (35)一、国际化资源文件 (35)二、Java国际化 (35)Struts学习笔记第3页共39页三、Struts2国际化 (35)1、Action级别 (35)2、Package级别 (36)3、Application级别 (36)四、资源文件中的参数处理 (37)五、国际化-动态语言切换 (37)09 自定义拦截器 (38)10 类型转换 (38)Struts2总结 (39)目录Action⏹简单数据校验Result常用配置文件OGNL & ValueStackTags---------------------Project⏹类型转换、上传与下载、interceptor、防止重复提交 MVC思想深入剖析源码解读其他话题01 Struts2-Action一、Struts作用:将请求与结果分开二、搭建Struts2的运行环境:1、建立Web项目;2、建立Struts2的配置文件(struts.xml);将Struts2的空项目中的配置文件(struts.xml)复制到项目的src目录下。
配置如下:<!--struts.devMode :是否设置为开发模式true:是开发模式,否则不是注:在开发模式下,修改Struts的配置文件后不需要重新启动Tomcat服务器即生效。
否则修改Struts配置文件后需要重新启动Tomcat服务器才生效。
--><constant name="struts.devMode"value="true"/><!--namespace :对应与项目名称后面的"/"(例如Struts2_0100_Introduction后面的"/") (http://localhost:8080/Struts2_0100_Introduction/)--><package name="default"namespace="/"extends="struts-default"><action name="hello"><result>/hello.jsp</result></action></package>3、复制Struts2相应的jar包及第三方包。
将空项目中lib目录中的除junit和spring-test之外的所有文件复制到项目的WebRoot/WEB-INF/lib目录下4、修改对应的web.xml,建立struts2的filter(参考struts自带的项目),添加如下配置:<filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>三、NamespaceNamespace决定了action的访问路径,默认为“”,可以接收所有路径的action,如果没有找到相应的namespace时,则使用namespace为空的actionNamespace可以写为/,或者/xxx,或者/xxx/yyy,对应的action访问路径为/index.action、/xxx/index.action、或者/xxx/yyy/index.action.Namespace最好也用模块来进行命名。
namespace :对应与项目名称后面的"/"(例如Struts2_0100_Introduction后面的"/")(http://localhost:8080/Struts2_0100_Introduction/)四、<package>标签<package>是用来解决重名的问题,例如当系统的前台和后台都有一个action名叫hello,这时就需要用package来区分。
前台<package name="front">后台<package name="back">struts2中的package与java的package是相同的作用的。
五、Action具体视图的返回可以由用户自己定义的Action来决定具体的手段是根据返回的字符串找到对应的配置项,来决定视图的内容,有三种手段:<constant name="struts.devMode"value="true"/><package name="front"extends="struts-default"namespace="/"><action name="index"class="com.bjsxt.struts2.front.action.IndexAction1"> <result name="success">/ActionIntroduction.jsp</result></action></package>注:<action>标签中的class属性是表示action的对应的类(这个类是一个普通Java类),当访问这个action时会创建这个类成为一个对象,然后执行这个对象中的execute方法()(execute方法返回类型为String)。
第一种:Action 普通Java类public class IndexAction1 {public String execute() {return"success";}}当<action>标签中class属性省略时,则默认执行com.opensymphony.xwork2.ActionSupport类中的execute方法,而这个方法返回一个字符串常量SUCCESS(常量值为:”success”).第二种:Action 实现com.opensymphony.xwork2.Action接口,这个接口中定义了一些常量和一个execute 方法,我们重写execute()方法就可以了。
import com.opensymphony.xwork2.Action;public class IndexAction2 implements Action {@Overridepublic String execute() {//return "success";return this.SUCCESS;//SUCCESS常量值为:"success"}}第三种:Action 继承com.opensymphony.xwork2.ActionSupport类,而这个类又实现了com.opensymphony.xwork2.Action接口,我们重写execute()方法就可以了。
import com.opensymphony.xwork2.ActionSupport;public class IndexAction3 extends ActionSupport {@Overridepublic String execute() {//return "success";return this.SUCCESS;//SUCCESS常量值为:"success"}}注:第三种Action是我们需要使用的方式,因为这个类不担实现了com.opensymphony.xwork2.Action 接口,更重要的是它已经帮我封装了许多其它有用的方法。
六、路径问题的说明struts2中的路径问题是根据action的路径而不是jsp路径来确定,所以尽量不要使用相对路径。