第五章 Struts2基础入门 (理论)
- 格式:doc
- 大小:419.00 KB
- 文档页数:25
Struts2 复习题1.以下属于 struts2 的控制器组件是:A.ActionB.ActionFormC.ActionServletD.dispatchAction2.以下属于 struts2 的体系结构的是: (多选 )3.以下属于 struts2 配置文件中的配置元素是: (多选 ) A.<package> B.<action> C.<form-beans>D.<action-mappings>4.关于 struts1 和 struts2 对比的说法正确的是:A.struts1 要求 Action 类继承 struts1 框架中的 Action 父类, struts2 中则不一定需要继承,可以是 POJO类B.struts1 中的 Action 不是线程安全的,而struts2 中的 Action 是线程安全的C.struts1 和 struts2 中都使用ActionForm 对象封装用户的请求数据D.struts1 使用 OGNL表达式语言来支持页面效果,struts2 通过 ValueStack 技术使标签库访问值5. 以下关于A.每个ActionB.每个ActionValueStack 说法正确的是: (多选 ) 对象实例拥有一个ValueStack 对象对象实例拥有多个ValueStack 对象C.Action 中封装了需要传入下一个页面的值,这些值封装在ValueStack 对象中D.ValueStack会在请求开始时被创建,请求结束时消亡6. 关于 struts2 配置文件说法正确的是:A.必须在 WEB-INF/classes目录下B.名字必须为struts.xmlC.配置 Action 时,必须配置包信息D.使用 <forward> 元素配置转发7. 在 struts2 配置中用()元素来配置常量:A.<const>B.<constants>C.<constant>D.<constant-mapping>8.关于 struts2 包的说法正确的是:A.struts2 框架使用包来管理常量B.struts2 框架定义包时必须指定name 属性C.struts2 框架中配置包时,必须继承自struts-default 包,否则会报错D.struts2 框架中使用包来管理Action9. struts2 中获取 Servlet API 的方法正确的是: (多选 )A.使用B.使用ActionContext 对象以解耦合的方法访问S ervlet API ServletActionContext 对象以解耦合的方式访问Servlet APIC.使用D.使用ActionContext 对象以耦合的方式访问S ervlet API ServletActionContext 对象以耦合的方式访问Servlet API10.struts2 动态调用的格式为:A.ActionName?methodName.actionB.ActionName! methodName.actionC.ActionName*methodName.actionD.ActionName@mathodName.action11.如果要实现 struts2 的数据校验功能A.普通 Action 类可以实现B.继承自 Action 接口可以实现C.继承自 ActionSupport 类可以实现D.继承自 ActionValidate 类可以实现12.如果要实现自定义处理结果,需继承那个类A.DispathcerB.StrutsResultSupportC.SupportD.Action13.实现动态返回结果,在配置 <result> 元素时使用()指定视图资源A.${属性名 }B.@{属性名 }C.${'属性名 '}D.${" 属性名 "}14.用于实现国际化的 struts2 标签是:A.<s:text>B.<s:message>C.<s:textfield>D.<s:resource>15.struts2 默认的处理结果类型是:A.dispatcherB.redirectC.chainD.forward16.自定义转换器继承的抽象类是:A.ConverterB.TypeConverterC.StrutsTypeConverterD.converts17.自定义转换器的注册方式有:18.自定义拦截器类的方式有: (多选 )19.在 struts.xml 文件中,使用()元素定义拦截器A.<interceptor-ref>B.<interceptor>C.<intercep>D.<default-interceptor-ref>20.在 OGNL中?操作符的作用是:A.取出符合选择逻辑的第一个元素B.取出符合选择逻辑的最后一个元素C.取出符合选择逻辑的所有元素D.以上说法都不对21.以下属于 struts2 标签的是: (多选 )A.Ajax 标签B.数据访问标签C.logic 标签D.bean 标签22.以下哪个标签是 struts2 中的用于循环迭代 :A.<s:property>B.<s:iterator>C.<s:logic>D.<s:foreach>23. Struts2 主要核心功能是由()实现a)过滤器b)拦截器c)类型转换器d)配置文件24. Struts 中的 ActionServlet 属于 MVC 模式()a)视图b)模型c)控制器d)业务层25.Struts2 框架由()和()框架发展而来的【选择二项】a)Hibernateb)Strutsc)Springd)WebWork26.Struts2 以( B)为核心,采用()的机制处理用户请求a)Strutsb)WebWorkc)拦截器d)jar 包27. struts2 中,不属于Action 接口中定义的字符串常量的是()a)SUCCESSb)FAILUREc)ERRORd)INPUT28. struts2 在控制器类中一般需要添加相应属性的()和()【选择二项】a)setter 方法b)as 方法c)getter 方法d)is 方法29. struts2 控制器需要在()配置文件中进行配置a)web.xmlb)struts.xmlc)application.porpertiesd)webwork.xml30. 不属于 struts2 标签库的是()a)<s:textfield>b)<s:textarea>c)<s:submit>d)<select>31. 在 JSP页面中可以通过Struts2 提供的()标签来输出国际化信息a)<s:input>b)<s:messages>c)<s:submit>d)<s:text>32.资源文件的后缀名为()a)txtb)docc)propertyd)properties33. struts2 自定义类型转换器必须实现的接口是()a)Convertb)TypeConverterc)StrutsTypeConverterd)StrutsConvert34. struts2 关于注册全局类型转换器的说法正确的是()【选择二项】a)必须提供 xwork-conversion.properties 文件b)注册文件的格式为:复合类型 =对应类型转换器c)注册文件的格式为:对应类型转换器=复合类型d)以上说法都不正确35. struts2 自定义拦截器中的“return invocation.invoke ”代码表示()【选择二项】a)不执行目标 Action 的方法,直接返回b)执行目标 Action 的方法,直接返回逻辑视图名称c)在自定义拦截器中,该代码是必需的d)在自定义拦截器中,该代码是可选的36. struts2 中,以下配置文件上传拦截器只允许上传 bmp 图片文件的代码,正确的是()a)<param name= ” allowedTypes ” >image/bmp</param>b)<param name= ” allowedTypes ” >*.bmp</param>c)<param name= ” allowedTypes ” >bmp</param>d)<param name= ” allowedTypes ” >image/*bmp</param>.37.以下关于 OGNL的说法正确的是()【选择二项】a)ActionContext 是 OGNL的上下文环境b)StackContext 是 OGNL的上下文环境c)ValueStack 是 OGNL的根d)ActionContext 是 OGNL的根38. 假设在 Session 中存在名为uid 属性,通过OGNL访问该属性,正确的代码是()a)#uidb)#session.uidc)uidd)${session.uid}39. 关于“ #session.persions.{? #this.age>20} ” OGNL代码所表示的意义说法正确的是()a) 从 persons 集合中取出第一个年龄>20 的 Person 对象b) 从 persons 集合中取出所有年龄> 20 的 Person 对象子集c) 从 persons 集合中取出最后一个年龄>20 的 Person 对象d)该代码不符合 OGNL的语法40. 假设在某 JSP页面中存在” <s:property> ”代码,则以下说法正确的是()a)编译 JSP页面时会出现错误b)编译 JSP页面时不会出现错误,但页面不会显示任何内容c)该代码用于输出位于 ValueStack(值栈)栈顶的对象d)以上说法都不正确41. struts2 默认的处理结果类型是()a)dispatcherb)redirectc)chaind)以上说法都不正确42. 下列选项中,关于Struts2 配置文件说法正确的是()a)必须置于 WEB-INF/classes目录下b)必须为 Struts.xmlc)配置 Action 时必须配置包信息d)使用 <forward> 元素配置转发43. 下列选项中,关于 Struts2 的Action 说法正确的是()【选择二项】a) struts2 会为每一个请求创建一个对应的Action 实例b) struts2 在请求处理过程中,只有一个Action 实例c)struts2 通过属性来封装用户请求参数d)在 struts2 中定义的属性都用于封装用户请求参数44. struts2 中动态方法调用的格式为()a)ActionName_methodName.dob)ActionName!methodName.doc)ActionName_methodName.actiond)ActionName!methodName.action问答题: MVC是什么含义?。
Struts2学习之二--Struts2标签介绍热12已有 14625 次阅读 2009-07-12 18:53[顶]3G移动--Android开发工程师全能班(转) Struts2学习之二--Struts2标签介绍在上一篇文章《为Struts 2.0做好准备》中,我过于详细地介绍了Struts 2.0开发环境和运行环境的配置,所以,本文很少涉及的以上两方面的细节。
如果,您看完《为Struts 2.0做好准备》后,还有什么不明白,或者没法运行文中例子,请联系我。
我的E-MAIL:Max.M.Yuan@。
在介绍常用标志前,我想先从总体上,对Struts 1.x与Struts 2.0的标志库(Tag Library)作比较。
分类将标志库按功能分成HTML、Tiles、Logic和Bean等几部分严格上来说,没有分类,所有标志都在URI为“/struts-tags”命名空间下,不过,我们可以从功能上将其分为两大类:非UI标志和UI标志表达式语言(expression languages)不支持嵌入语言(EL)OGNL、JSTL、Groovy和Velcity以上表格,纯属个人总结,如有所不足或错误,请不吝指正好了,我要开始介绍“常用”(这里所谓的“常用”,是指在已往工作中使用Struts里经常用到的)的标志了。
1.非UI标志o if、elseif和else描述:执行基本的条件流转。
参数:名称必需默认类型描述备注test 是Boolean 决定标志里内容是否显示的表达式else标志没有这个参数id 否Object/String 用来标识元素的id。
在UI和表单中为HTML的id属性例子:<%@ page contentType="text/html; charset=UTF-8" %><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Condition Flow</title></head><body><h3>Condition Flow</h3><!--这里有点小技巧:本来可以用#[0]来获得,请求中name的值。
学习struts2.2.1遭遇滑铁卢~~~~~好多异常~~~~~好多bug~~~~好多问题~~~~~~好多困难~~~好多肥羊~~~一、Filter mapping specifies an unknown filter name ----filter标签在web.xml 里的顺序<filter-mapping><filter-name>adminOperateLogFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter><filter-name>adminOperateLogFilter</filter-name><filter-class>com.berheley.exam.web.filter.AdminOperateLogFil ter</filter-class></filter>这样写启动服务器时报错 Filter mapping specifies an unknown filter nameadminOperateLogFilter将这两块换个顺序就没问题了,web.xml信息的加载是有顺序的,filter在mapping之前必须要让服务器找到其定义。
<filter><filter-name>adminOperateLogFilter</filter-name><filter-class>com.berheley.exam.web.filter.AdminOperateLogFil ter</filter-class></filter><filter-mapping><filter-name>adminOperateLogFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>二、ng.IllegalArgumentException: Filter mapping specifies an unknown filter nameStruts2答:“Struts2”?大写的?are you sure?我猜你一定是看了某struts2.0的权威指南(那是一个chm文件电子书,而且你看的可能是翻译成中文的),我不知道英文版的有没有写错,但是我检查了很久后才发现中文版存在这个大小写错误。
Struts2标签使用(1):<s:textfield> ---- 文本输入框使用:<s:textfield name=”实体Bean。
属性”></s:textfield>(2):<s:textarea> ----- 文本域输入框使用:<s:textarea name=”实体Bean。
属性”></s:textarea>(3):<s:password> ----- 密码输入框使用:<s:password name=”实体Bean。
属性”></s:password>前三个基本都是一样的。
如果是要显示值的话可以这样:value = “实体Bean。
Get***()”。
(4):<s:radio list=””> ---- 单选按钮使用:<s:radio list=””>其中list 属性是必须要有的。
<1>:第一种方式:list = “#{‘male’:’男’,’female’:’女’}”<2>:第二中方式:list = “#request/session.list”。
---- 与action 结合起来了。
如果要默认选中的话后面加上value = “”.也可以通过javascript 的方式来默认选中。
(5):<s:url/> --- url连接<s:a/> --- 超链接这两个标签一般结合起来来使用。
使用:<s:url id = “id” action = “userAction”/><s:a href=”%{id}”/>(6):<s:form/> --- 获取相应form的值使用:<1>:<s:form action = “userAction”><2>:<s:url id=”userId” action = “userAction”> -- 定义了一个userId的指向userActionde 路径<s:form action=”%{userId}”>(7):<s:submit/> ---- 提交标签(8):<s:reset/> ---- 重置标签(9):<s:hidden/> ---- 隐藏域标签使用:<s:hidden name=”实体Bean。
配置ActionStruts2的核心功能是action,对于开发人员来说,使用Struts2主要就是编写action,action类通常都要实现com.opensymphony.xwork2.Action接口,并实现该接口中的execute()方法。
该方法如下:public String execute() throws ExceptionStruts2并不是要求所有编写的action类都要实现Action接口,也可以直接编写一个普通的Java类作为action,只要实现一个返回类型为String的无参的public方法即可:public String xxx()在实际开发中,action类很少直接实现Action接口,通常都是从com.opensymphony.xwork2.ActionSupport类继承,ActionSupport实现了Action接口和其他一些可选的接口,提供了输入验证,错误信息存取,以及国际化的支持,选择从ActionSupport继承,可以简化action的定义。
开发好action之后,好需要对action进行配置,以告诉Struts2框架,针对某个URL的请求应该交由哪个action进行处理。
1.Action映射:action映射是Struts2框架中的基本”工作单元”,action映射就是将一个请求URL(即action的名字)映射到一个action类,当一个请求匹配某个action的名字时,框架就使用这个映射来确定如何处理请求。
action元素的完整属性表例如:<action name="user" class="erAction"><result name="success">/user.jsp</result></action>2. 使用method属性在配置action时,我们可以通过action元素的method属性来指定action调用的方法,所指定的方法,必须遵循与execute方法相同的格式。
About the T utorialApache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. This framework is designed to streamline the full development cycle from building, to deploying and maintaining applications over time. Apache Struts 2 was originally known as Web Work 2.This tutorial will teach you, how to use Apache Struts for creating enterprise-ready Java web applications in simple and easy steps.AudienceThis tutorial is designed for Java programmers who are interested to learn the basics of Struts 2.x framework and its applications.PrerequisitesBefore proceeding with this tutorial, you should have a good understanding of the Java programming language. A basic understanding of MVC Framework and JSP or Servlet is very helpful.Disclaimer & CopyrightCopyright 2015 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute, or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness, or completeness of our website or its contents including this tutorial. If you discover any errorsonourwebsiteorinthistutorial,******************************************iT able of ContentsAbout the Tutorial (i)Audience (i)Prerequisites (i)Disclaimer & Copyright (i)Table of Contents .................................................................................................................................. i i STRUTS 2 - BASIC MVC ARCHITECTURE (1)The Model (2)The View (2)The Controller (2)STRUT 2 – OVERVIEW (3)Struts 2 Framework Features (3)Struts 2 Disadvantages (4)ENVIRONMENT SETUP (5)Step 1 - Setup Java Development Kit (JDK) (5)Step 2 - Setup Apache Tomcat (5)Step 3 - Setup Eclipse (IDE) (7)Step 4 - Setup Struts2 Libraries (8)STRUTS 2 – ARCHITECTURE (10)Request Life Cycle (11)STRUTS 2 – EXAMPLES (12)Create a Dynamic Web Project (13)Create Action Class (14)Create a View (15)Create Main Page (16)iiTo Enable Detailed Log (18)Procedure for Executing the Application (19)STRUTS 2 – CONFIGURATION (22)The web.xml File (22)The Struts.xml File (23)The Struts-config.xml File (25)The Struts.properties File (27)STRUTS 2 – ACTIONS (29)Create Action (29)Create a View (31)Execute the Application (33)Create Multiple Actions (35)STRUTS 2 – INTERCEPTORS (37)Struts 2 Framework Interceptors (37)How to Use Interceptors? (39)Create Custom Interceptors (40)Create Interceptor Class (41)Create Action Class (42)Create a View (43)Create Main Page (43)Configuration Files (44)Stacking Multiple Interceptors (46)STRUTS 2 – RESULT TYPES (48)The Dispatcher Result Type (48)iiiThe Redirect Result Type (50)STRUTS 2 – VALUE STACK / OGNL (52)The Value Stack (52)The OGNL (53)ValueStack/OGNL Example (54)Create Views (56)Configuration Files (57)STRUTS 2 – FILE UPLOADS (60)Create View Files (60)Create Action Class (61)Configuration Files (63)Error Messages (67)STRUTS 2 – DATABASE ACCESS (69)Create Action (69)Create Main Page (71)Create Views (72)Configuration Files (73)STRUTS 2 – SENDING EMAIL (77)Create Action (77)Create Main Page (80)Create Views (81)Configuration Files (82)STRUTS 2 - VALIDATIONS (86)Create Main Page (86)ivCreate Action (87)Configuration Files (88)How this Validation Works? (91)Xml Based Validation (92)STRUTS 2 - LOCALIZATION (95)Resource Bundles (95)Access the messages (96)Localization Example (96)STRUTS 2 – TYPE CONVERTION (104)STRUTS 2 – THEMES & TEMPLATES (110)Selecting Themes (111)How a Theme Works? (112)Creating New Themes (112)STRUTS 2 – EXCEPTION HANDLING (115)Global Exception Mappings (120)STRUTS 2 – ANNOTATIONS (122)Create Main Page (122)Create Views (123)Create Action (124)Configuration Files (125)STRUTS 2 – CONTROL TAGS (130)The If and Else Tags (130)If and Else Tags – Detailed Example (130)The Iterator Tags (134)vThe Iterator Tags – Detailed Example (135)The Merge Tag (142)The Merge Tag – Detailed Example (142)The Append Tag (147)The Append Tag – Detailed Example (148)The Generator Tag (153)The Generator Tag – Detailed Example (154)STRUTS 2 – DATA TAGS (158)The Action Tag (158)The Action Tag – Detailed Example (158)The Include Tag (164)The Include Tag – Detailed Example (164)The Bean Tag (168)The Bean Tag – Detailed Example (169)The Date Tag (173)The Date Tag - Detailed Example (173)The Param Tag (176)The Param Tag – Detailed Example (177)The Property Tag (181)The Property Tag – Detailed Example (181)The Push Tag (185)The Push Tag – Detailed Example (186)The Set Tag (190)The Set Tag – Detailed Example (190)The Text Tag (195)The Text Tag – Detailed Example (195)viThe URLTag (199)STRUTS 2 – THE FORM TAGS (204)Simple UI Tags (204)Group UI Tags (206)STRUTS 2 – THE AJAX TAGS (211)STRUTS 2 & SPRING INTEGRATION (214)STRUTS 2 & TILES INTEGRATION (220)STRUTS 2 & HIBERNATE (226)Database Setup (226)Hibernate Configuration (226)Envrionment Setup (227)Hibernate Classes (228)Action Class (231)Struts Configuration (234)viiStruts 2 1M odel V iew C ontroller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts:∙Model - The lowest level of the pattern which is responsible for maintaining data. ∙View - This is responsible for displaying all or a portion of the data to the user. ∙ Controller - Software Code that controls the interactions between the Model and View. MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here the Controller receives all requests for the application and then works with the Model to prepare any data needed by the View. The View then uses the data prepared by the Controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows.STRUTS 2 - BASIC MVC ARCHITECTUREStruts 2The ModelThe model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself.The ViewIt means presentation of data in a particular format, triggered by a controller's decision to present the data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology.The ControllerThe controller is responsible for responding to the user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model.Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC methodology within Struts2.2Struts 2 3 Struts2 is a popular and mature web application framework based on the MVC design pattern. Struts2 is not just a new version of Struts 1, but it is a complete rewrite of the Struts architecture.The Webwork framework initially started with Struts framework as the basis and its goal was to offer an enhanced and improved framework built on Struts to make web development easier for the developers.After a while, the Webwork framework and the Struts community joined hands to create the famous Struts2 framework.Struts 2 Framework FeaturesHere are some of the great features that may force you to consider Struts2:∙ Pojo Forms and Pojo Actions - Struts2 has done away with the Action Forms that were an integral part of the Struts framework. With Struts2, you can use any POJO to receive the form input. Similarly, you can now see any POJO as an Action class.∙ Tag Support - Struts2 has improved the form tags and the new tags which allow the developers to write less code.∙ Ajax Support - Struts2 has recognized the take over by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, this function is very similar to the standard Struts2 tags.∙ Easy Integration - Integration with other frameworks like Spring, Tiles and SiteMesh is now easier with a variety of integration available with Struts2.∙ Template Support - Support for generating views using templates.∙ Plugin Support - The core Struts2 behavior can be enhanced and augmented by the use of plugins. A number of plugins are available for Struts2.∙ Profiling - Struts2 offers integrated profiling to debug and profile the application. In addition to this, Struts also offers integrated debugging with the help of built in debugging tools.∙ Easy To Modify Tags - Tag markups in Struts2 can be tweaked using Freemarker templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS knowledge is enough to modify the tags.∙Promote Less Configuration - Struts2 promotes less configuration with the help of using default values for various settings. You don't have to configure something unless it deviates from the default settings set by Struts2.STRUT 2 – OVERVIEWStruts 2 ∙View Technologies- Struts2 has a great support for multiple view options (JSP, Freemarker, Velocity and XSLT)Listed above are the Top 10 features of Struts 2 which makes it as an Enterprise ready framework.Struts 2 DisadvantagesThough Struts 2 comes with a list of great features, there are some limitations of the current version - Struts 2 which needs further improvement. Listed are some of the main points:∙Bigger Learning Curve- To use MVC with Struts, you have to be comfortable with the standard JSP, Servlet APIs and a large & elaborate framework.∙Poor Documentation- Compared to the standard servlet and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized.∙Less Transparent - With Struts applications, there is a lot more going on behind the scenes than with normal Java-based Web applications which makes it difficult to understand the framework.Final note, a good framework should provide generic behavior that many different types of applications can make use of it.Struts 2 is one of the best web frameworks and being highly used for the development of Rich Internet Applications (RIA).4Struts 2 5Our first task is to get a minimal Struts 2 application running. This chapter will guide you on how to prepare a development environment to start your work with Struts 2. I assume that you already have JDK (5+), Tomcat and Eclipse installed on your machine. If you do not have these components installed, then follow the given steps on fast track: Step 1 - Setup Java Development Kit (JDK)You can download the latest version of SDK from Oracle's Java site: Java SE Downloads . You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you should be inputting the following line in your C:\autoexec.bat file.Alternatively, on Windows NT/2000/XP:∙ You can right-click on My Computer, Select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.∙On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file. Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as per the given document of IDE.Step 2 - Setup Apache T omcatYou can download the latest version of Tomcat from /. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-6.0.33 on windows, or /usr/local/apache-tomcat-6.0.33 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.ENVIRONMENT SETUPYou can start Tomcat by executing the following commands on windows machine, or you can simply double click on startup.batTomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it should display the following result:Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat website: 67 Tomcat can be stopped by executing the following commands on windows machine:Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine:Step 3 - Setup Eclipse (IDE)All the examples in this tutorial are written using Eclipse IDE. I suggest that, you have the latest version of Eclipse installed in your machine.To install EclipseDownload the latest Eclipse binaries from /downloads/. Once you download the installation, unpack thebinary distribution into a convenient location.For example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exeEclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:After a successful startup, if everything is fine, it should display the following result:Step 4 - Setup Struts2 LibrariesNow if everything is fine, then you can proceed to setup your Struts2 framemwork. Following are the simple steps to download and install Struts2 on your machine.∙Make a choice whether you want to install Struts2 on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.∙Download the latest version of Struts2 binaries from /download.cgi.∙At the time of writing this tutorial, I downloaded struts-2.0.14-all.zip and when you unzip the downloaded file it will give you directory structure inside C:\struts-2.2.3 as follows.8Second step is to extract the zip file in any location, I downloaded & extracted struts-2.2.3-all.zip in c:\folder on my Windows 7 machine so that I have all the jar files into C:\struts-2.2.3\lib. Make sure you set your CLASSPATH variable properly otherwise you will face problem while running your application.9End of ebook previewIf you liked what you saw…Buy it from our store @ https://10。
第8章?第9章Struts2标签库和OGNL学习内容Struts 2标签库OGNL能力目标熟练使用Struts 2常用标签熟练使用OGNL本章简介前面我们编写的案例使用的都是HTML 标签,这些标签并不能很好的与Struts 2框架结合,Struts 2和Struts 1一样都自带了功能强大、成熟完善的标签库供我们使用,通过使用这些标签库可以大大提高开发效率和代码的可维护性。
其实Struts 2的标签库是建立在OGNL 基础上的,OGNL 是一种功能强大的表达式语言,通过简单的语法即可存取对象的属性、调用对象的方法、遍历等功能。
本章将学习OGNL 和Struts 2标签库,包括数据访问标签、控制标签、表单标签和非表单标签等。
核心技能部分9.1 OGNL9.1.1 ActionContextStruts 2中的ActionContext 、ValueStack 和StackContext 对象与OGNL 密切相关,理解这三个对象时学习OGNL 的前提。
在前面的学习中,我们已经在使用ActionContext 、ValueStack 和StackContext 对象了,这三个对象的作用及其之间的关系如图8.1.1所示。
图8.1.1ActionContext1. ActionContext 对象ActionContextValueStackStackContextAction 其他Session Request Application Parameters Attribute 其他ActionContext(com.opensymphony.xwork.ActionContext)是Action执行时的上下文。
我们可以把上下文可以看作是一个容器,用于存放Action执行时需要使用的对象,例如请求的参数(Parameter)、会话(Session)、Servlet上下文(ServletContext)等。
1.1通过代码实例跟我学Struts2框架从入门到精通——在Struts2框架中实现国际化的Web应用实例(第2部分)1.1.1体验三种不同形式的资源文件加载的顺序1、系统加载的顺序首先以“类文件”为优先,其次为“包”文件、最后才是“全局”资源文件。
2、如果在三种资源文件中都没有提供对应的Key的提示信息resultMessage =getUserName()+" "+ this.getText("strutsweb.login.success.noexist");将出现下面的“错误”(没有显示正确的提示信息)。
3、如果在三种资源文件中都提供有相同的Key但不同的提示信息——能够区分加载的顺序(1)在Action类范围内的资源文件中的提示信息为strutsweb.login.success=\u767B\u9646\u6210\u529F\uFF08\u5728Action\u7C7B\u8303\u56F4\u FF09strutsweb.login.success=登陆成功(在Action类范围)(2)在包资源文件中页提供相同的key的提示信息strutsweb.login.success=\u767B\u9646\u6210\u529F\uFF08\u5728Action\u7C7B\u8303\u56F4\u FF09strutsweb.login.success=登陆成功(在包范围内的信息)(3)在全局资源文件中提供相同的key的提示信息strutsweb.login.success=\u767B\u9646\u6210\u529F\uFF08\u5728Action\u7C7B\u8303\u56F4\u FF09strutsweb.login.success=登陆成功(在全局范围内的资源信息)(4)测试因此,以类资源文件为优先。
(5)再删除类资源文件中的下面的信息strutsweb.login.success=\u767B\u9646\u6210\u529F\uFF08\u5728Action\u7C7B\u8303\u56 F4\uFF09因此,其次是以包资源文件。
第5章Struts2 基础入门本章学习内容:1. Struts2 体系结构2. Struts2 运行流程3. Struts2与Struts1的对比4. Struts2入门示例5. 跟踪用户状态6. ValueStack的概念本章学习目标:1. 掌握Struts2体系结构2. 理解Struts2运行流程3.掌握struts.xml文件的配置4.能使用Struts2框架开发Web应用程序5.掌握使用ValueStack存储数据本章简介:通过上一章的学习,我们掌握了Struts1框架的HTML标签库、Bean标签库、Logic标签库等知识。
但是Struts1框架有天生的设计缺陷,包括:支持的表现层技术单一、与Servlet API严重耦合,难于测试、代码严重依赖于Struts1 API,属于侵入式设计等。
为了弥补以上缺陷,Struts2框架应运而生。
Struts2的体系与Struts1的体系差别非常大,因为Struts2使用了WebWork的设计核心,而不是使用Struts1的设计核心。
Struts2大量使用拦截器来处理用户请求,从而允许用户的业务逻辑控制器彻底与Servlet API分离。
Struts2下的控制器不再像Struts1下的控制器,需要继承一个Action父类,甚至可以无需实现任何接口,Struts2的控制器就是一个包含execute方法的普通POJO类。
本章主要讲述Struts1存在的问题、Struts2体系结构、运行流程、使用Struts2重构用户登录、Struts2中的valueStack等知识。
5.1Struts2概述Struts1现在已经发展成为一个高度成熟的框架,不管是稳定性还是可靠性,都得到了广泛的证明。
但由于Struts1存在一些设计上的缺陷,于是催生了Struts2框架。
Struts2与Struts1相比,确实有很多革命性的改进,但它并不是一个全新的框架,而是在WebWork基础上发展起来。
从某种意义上讲,Struts2没有继承Struts1,而是继承了WebWork框架,或者说,WebWork衍生出了Struts2,而不是Struts1衍生了Struts2。
因为Struts2是WebWork的升级,而不是一个全新的框架,因此稳定性和性能各方面都有很好的保证,而且吸收了Struts1和WebWork两者的优势,因此,Struts2是一个非常完善的MVC实现框架。
5.1.1Struts1框架存在的问题对于Struts1框架而言,因为它与JSP/Servlet紧密耦合,因而导致了许多不可避免的设计缺陷,随着Web应用程序规模的扩大,这些缺陷逐渐变成制约Struts1发展的重要因素,这也是Struts2出现的原因。
下面具体分析Struts1中存在的缺陷。
(1)支持的表现层技术单一Struts1只支持JSP作为表现层技术,不提供与其它表现层技术,例如Velocity、FreeMarker等技术的整合。
这一点严重制约了Struts1框架的使用,对于目前的很多Java EE应用程序而言,并不一定使用JSP作为表现层技术。
(2)与Servlet API严重耦合,难于测试因为Struts1框架是在Model 2的基本上发展起来的,因此它完全是基本Servlet API的,所以在Struts1的业务逻辑控制器内,充满了大量的Servlet API。
分析以下Struts1业务逻辑控制器代码:public class LoginAction extends Action{public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {. . .}}当我们需要测试上面Action类的execute()方法是,该方法有4个参数:ActionMapping、ActionForm、HttpServletRequest和HttpServletResponse,初始化这4个参数比较困难。
尤其是HttpServletRequest和HttpServletResponse两个参数,通常由Web容器负责实例化。
因此一旦脱离了Web服务器,Action测试非常困难。
(3)代码严重依赖于Struts1 API,属于侵入式设计正如从上面代码片段中所看到的,Struts1的Action类必须继承Struts1的基类,实现处理方法时,又包含了大量Struts1的API:如ActionMapping、ActionForm和ActionForward类。
这种侵入式设计的最大缺点在于,一旦系统需要重构时,这些Action类完全没有利用价值。
可见,Struts1的Action类这种侵入式设计导致了较低的代码利用。
5.1.2Struts2体系结构Struts2的体系与Struts1的体系差别非常大,因为Struts2使用了WebWork的设计核心,而不是使用Struts1的设计核心。
Struts2大量使用拦截器来处理用户请求,从而允许用户的业务逻辑控制器彻底与Servlet API分离。
Struts2的体系结构主要包括Struts2控制器组件、Struts2配置文件和Struts2标签库等3部分。
1Struts2的控制器组件Struts2的控制器组件是Struts2框架的核心,事实上,所有MVC框架都是以控制器组件为核心的。
Struts2的控制器由两个部分组成:核心控制器FilterDispathcer和业务控制器Action。
(1)核心控制器:FilterDispathcherFilterDispatcher是Struts2框架的核心控制器,该控制器作为一个Filter运行在Web应用程序中,它负责拦截所有的用户请求,当用户请求到达时,该Filter会过滤用户请求。
如果用户请求以action结尾,该请求将被转入Struts2框架处理。
Struts2框架获得了*.action请求后,将根据*.action请求的前面部分决定调用那个业务控制器,例如,对于login.action的请求,Strtus2调用名为login的Action来处理该请求。
(2)业务控制器业务控制器Action需由用户自己实现,在配置文件中进行配置,以供核心控制器FilterDispatcher 来使用。
实际上,Struts2应用程序起作用的业务控制器不是用户自定义的Action,而是系统生成的Action的代理,但该Action代理以用户定义的Action为目标。
以下是Struts2的Action代码示例:public class LoginAction{//封装用户请求参数的uid属性private String uid;//封装用户请求参数的pwd属性private String pwd;//处理用户请求的execute方法public String execute() throws Exception{//如果登录成功,则进入主页面if("scott".equals(this.uid) && "tiger".equals(this.pwd)){return "success";}//否则进入登录失败错误提示页面return "fial";}//getter、setter方法public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getUid() {return uid;}public void setUid(String uid) {this.uid = uid;}}以上Action代码无需实现任何父接口,无需继承任何Struts2基类,该Action类完全是一个POJO(普通、传统的Java对象),因此具有很好的复用性。
归纳起来,Struts2的Action类有如下优势:1.Action类完全是一个POJO类,因此具有很好的代码重用性。
2.Action类无需与任何Servlet API耦合,因此进行单元测试非常简单。
3.Action类的execute方法仅返回一个字符串作为处理结果,该处理结果可映射到任何的视图,甚至是另一个Action。
2Struts2的配置文件当Struts2创建系统的Action代理时,需要使用Struts2的配置文件。
Struts2的配置文件有两份:(1)配置Action的struts.xml文件(2)配置Struts2全局属性的struts.properties文件(可选)struts.xml文件内定义了Struts2的系列Action,定义Action时,指定该Action的实现类,并定义该Action处理结果与视图资源之间的映射关系。
以下是struts.xml配置文件的示例:<struts><!-- Struts2的Action都必须配置在package里面 --><package name="default" extends="struts-default"><!--继承自默认包 --><!-- 定义一个login的Action类,实现类为LoginAction --><action name="login" class="com.soft.struts5l.web.struts.action.LoginAction"><!-- 定义结果与视图资源的映射关系 --><result name="success">/index.jsp</result><result name="fail">/fail.jsp</result></action></package></struts>在上面的struts.xml文件中,定义了一个Action,定义Action时,不仅定义了Action实现类,而且通过”name”属性指定访问该Action的逻辑名,此处为“login”。
其中”result”元素用于指定execute方法返回值和视图资源之间的映射关系。
对于如下配置片段:<result name="success">/index.jsp</result>表示当execute方法返回”success”字符串时,流程将转发至index.jsp页面。