struts2教程(完全版)
- 格式:doc
- 大小:212.00 KB
- 文档页数:99
一.Struts2基础知识1. struts2的特点及配置1.1struts2与struts1的比较1)在软件设计上struts2没有struts1那样跟ServletApi和StrutsApi有着紧密的耦合,Struts2的应用可以不因爱ServletApi和StrutsApi.struts2的这种设计属于无侵入式设计,而Struts1却属于侵入式设计public class OrderListAction ectends Action//struts依赖于java2)Struts2提供了拦截器,利用拦截器可以进行AOP编程,实现如权限拦截等功能3)Struts2提供了类型转换器,我们可以把特殊的请求参数转换成我们需要的类型,在struts1中,如果我们实现同样的功能,就必须向struts1的底层实现BeanUtil注册类型转换器4)Struts2提供了支持多种表现层技术,如JSp,freeMarker等5)Struts2的输入校验可以对指定方法进行校验,解决了Struts的长久之疼6)提供了全局范围,包范围和Action范围的国际化资源文件管理实现1.2搭建struts2的开发环境1)新建web项目2)导入必要的包3)写配置文件Struts2默认的配置文件为Struts.xml,该文件需要存放在WEB-INF/classes下,该文件的配置模板如下(在m yeclipse中放在src目录下就可以了)模板在D:\Program Files\struts-2.3.4.1-all\struts-2.3.4.1\apps 解压struts2-blank.var再打开web-info/classes中的struts.x m l文件即可<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration2.3//EN""/dtds/struts-2.3.dtd"><struts></struts>4)在web.xm l中加入Struts2MVC框架启动配置在struts1.x中struts框架是通过Servlet启动的,在struts2中,struts框架式通过Filter 启动的,他在web.xm l中的配置如下:(D:\Program Files\struts-2.3.4.1-all\struts-2.3.4.1\apps 解压struts2-blank.var再打开Web-Info\web.xm l即可)<filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.Str utsPrepareAndExecuteFilter</filter-class><!—自从struts2.1.3以后,下面的FilterDispatcher已经标注为过时<filter-class>org.apache.struts2.dispatcher.ng.filter.FilterDispather</filter-class> --></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>在StrutsPrepareAndEXecuteFilter()方法中将会读取类路径下的默认文件struts.xml完成初始化操作。
在很多Web应用中,为了完成不同的工作,一个HTML form标签中可能有两个或多个submit 按钮,如下面的代码所示:<!--[if !supportLineBreakNewLine]--><ht ml action="" method="post"><input type="submit" value="保存"/><input type="submit" value="打印"/></ht ml>由于在<form>中的多个提交按钮都向一个action提交,使用Struts2 Action的execute 方法就无法判断用户点击了哪一个提交按钮。
如果大家使用过Struts1.x就会知道在Struts1.2.9之前的版本需要使用一个LookupDispatchAction动作来处理含有多个submit 的form。
但使用LookupDispatchAction动作需要访问属性文件,还需要映射,比较麻烦。
从Struts1.2.9开始,加入了一个Event DispatchAction动作。
这个类可以通过java反射来调用通过request参数指定的动作(实际上只是判断某个请求参数是不存在,如果存在,就调用在action类中和这个参数同名的方法)。
使用EventDispatchAction必须将submit的name 属性指定不同的值以区分每个submit。
而在Struts2中将更容易实现这个功能。
当然,我们也可以模拟Event DispatchAction的方法通过request获得和处理参数信息。
但这样比较麻烦。
在Struts2中提供了另外一种方法,使得无需要配置可以在同一个action类中执行不同的方法(默认执行的是execute方法)。
Struts2的工作流程及配置文件--- ---Struts2.0的流程图从图中看到Struts2的工作流程如下:1.服务器接收到的请求首先经过一组过滤器链(实际中的其他过滤器可能还包括诸如Spring 的字符过滤器CharactorEncodingFilter、V elocity的过滤器等,一般FilterDispatcher位于过滤器的最后一个执行),过滤器链按照你在web.xml中的配置顺序在接收客户请求时顺序执行,在向客户发送响应时反序执行,Struts2的核心FilterDispatcher在web.xml中的配置如下:<filter><filter-name>setCharactor</filter-name><!-- 配置字符过滤--><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter><filter-name>struts2</filter-name><!-- 配置Struts2过滤器--><filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter><filter-mapping><filter-name>setCharactor</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>注意:如果你使用的是W ebLogic6.1作为应用服务器,需要使用FilterDispatcherCompatW eblogic61替代FilterDispatcher。
struts2入门手册首先这个教程是基于你已经安装了myeclipse的基础上的,如果你还没有安装myeclipse 工具软件的话,你需要马上去安装一个。
如果你已经有了工具软件了的话,现在就按照以下步骤来入门struts2吧。
一、下载struts2进入struts的官网/,点击download,选择Full Distrybution:下的struts2-xxx-all.zip,下载struts2的最新版本,将压缩包解压,放置到D盘目录下。
二、解压struts2进入你解压后的struts2文件夹中,到D:\struts2-xxx\apps中,解压其中的struts2-blank.war 压缩文件到D:\struts2-xxx\example,这是struts2提供的基础例子,里面的WEB-INF\lib目录下的包正是struts2正常工作所需要的基本包。
三、导入struts2基本包打开你的myeclipse,创建一个web project工程,命名为test(你也可以自己随意起一个),不要急着点击Finish,先选择Next>,继续选择Next>,在弹出的对话框中把第二个单选框打勾,如图,再点击Finish。
创建好之后在你创建的工程上目录下的WebRoot/WEB-INF/lib目录上单击右键,选择import...,选择General下的File System,点击Next>,选择Browse...,浏览选择到D:\struts\example\WEB-INF\lib目录,点击确定。
选择Sellct All,点击Finish,就完成了struts需要的最基础的核心包的导入。
四、用struts实现一个简单的登陆验证1.修改工程目录下的WebRoot\WEB-INF目录下的web.xml文件,将里面的内容替换为如下代码:<?xml version="1.0"encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance"xmlns="/xml/ns/javaee"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID"version="3.0"><display-name>test</display-name><!-- 设置初始页面的URL --><welcome-file-list><welcome-file>login.jsp</welcome-file></welcome-file-list><!-- 设置struts过滤器 --><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>2.在工程的src目录下创建struts.xml,代码如下:<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""/dtds/struts-2.3.dtd"><struts><!-- 是否开启动态方法调用 --><constant name="struts.enable.DynamicMethodInvocation"value="false"/> <!-- 指定被struts2处理的请求的后缀类型,多个用逗号隔开 --><constant name="struts.action.extension"value="action"/><!-- 设置浏览器是否静态缓存内容,开发阶段最好关闭 --><constant name="struts.devMode"value="true"/><!-- 设置当struts.xml改动后,是否重新加载,默认为false,开发环境下最好打开 --> <constant name="struts.configuraction.xml.reload"value="true"/> <package name="myPackage"namespace="/"extends="struts-default"> <action name="login"class="action.LoginAction"><result name="success">/welcome.jsp</result> <result name="input">/login.jsp</result></action></package></struts>3.在工程的src目录下创建package(包),命名为action,在action中新建class,命名为LoginAction,代码如下:package action;import javax.servlet.http.HttpSession;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.ServletActionContext;@SuppressWarnings("serial")public class LoginAction extends ActionSupport {private String name;private String password;public String getName() {return name;}public void setName(String name) { = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String forward() throws Exception {return SUCCESS;}//重载ActionSupport中的execute()方法public String execute() throws Exception {//验证输入的Name是否为"name",是则返回"success"否则返回"input"if("name".equals(name)) {HttpSession session = ServletActionContext.getRequest().getSession();session.setAttribute("name", name);return SUCCESS;} else {return INPUT;}}}4.在工程的WebRoot目录下创建login.jsp,代码如下:<%@page language="java"contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="s"uri="/struts-tags"%><!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"> <title>Login</title></head><body><!-- 创建一个登陆表单 --><s:url action="login"id="loginUrl"></s:url><s:form action="%{loginUrl}"method="post"><s:textfield label="Name"name="name"/><s:password label="Password"name="password"/><s:submit></s:submit></s:form></body></html>5.在工程的WebRoot目录下创建welcome.jsp,代码如下:<%@page language="java"contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@taglib prefix="s"uri="/struts-tags"%><!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"> <title>Welcome</title></head><body><h1>登陆成功</h1></body></html>现在就来验证一下我们的登陆页面吧,选择工具栏中的按钮,在弹出的对话框中单击project后的矩形选框,从下拉列表中选择你创建的工程,然后单击Add,从弹出的对话框中单击sever后的矩形选框,从下拉列表中选择tomcat7,单击Finish。
struts2核心工作流程与原理做为一名技术人员,听到太多关于.net和java的比较的话题。
我想对那些技术人员说,请先了解一下什么是java(或者.net)吧,其实你根本不了解。
这是Struts2官方站点提供的Struts 2 的整体结构。
一个请求在Struts2框架中的处理大概分为以下几个步骤1.客户端提起一个(HttpServletRequest)请求,如上文在浏览器中输入”http://localhost:8080/TestMvc/add.action”就是提起一个(HttpServletRequest)请求。
2.请求被提交到一系列(主要是三层)的过滤器(Filter),如(ActionContextCleanUp、其他过滤器(SiteMesh等)、 FilterDispatcher)。
注意这里是有顺序的,先ActionContextCleanUp,再其他过滤器(SiteMesh等)、最后到 FilterDispatcher。
3.FilterDispatcher是控制器的核心,就是mvc中c控制层的核心。
下面粗略的分析下我理解的FilterDispatcher工作流程和原理:FilterDispatcher进行初始化并启用核心doFilter其代码如下:public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain ) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) res;ServletContext servletContext = filterConfig.getServletContext();// 在这里处理了HttpServletRequest和HttpServletResponse。
一、发展历史及简介发展历史Struts最早是作为Apache Jakarta项目的组成部分,项目的创立者希望通过对该项目的研究,改进和提高JavaServer Pages、Servlet、标签库以及面向对象的技术水准。
Struts这个名字来源于在建筑和旧式飞机中使用的支持金属架。
这个框架之所以叫"Struts",是为了提醒我们记住那些支撑我们房屋,建筑,桥梁,甚至我们踩高跷时候的基础支撑。
这也是一个解释Struts在开发Web应用程序中所扮演的角色的精彩描述。
当建立一个物理建筑时,建筑工程师使用支柱为建筑的每一层提供支持。
同样,软件工程师使用Struts为业务应用的每一层提供支持。
它的目的是为了帮助我们减少在运用MVC设计模型来开发Web应用的时间。
我们仍然需要学习和应用该架构,不过它将可以完成其中一些繁重的工作。
如果想混合使用Servlets和JSP的优点来建立可扩展的应用,Struts是一个不错的选择。
早期Smalltalk程序语言便采用了MVC(Model-View-Controller)模式(Patterns)以增加程序代码弹性,MVC模式将程序代码整理切割为三部分,Model部分是业务与应用领域(Business domain)相关逻辑、管理状态之对象,Controller部分接收来自View所输入的资料并与Model部分互动,struts业务流程控制(Flow Control)之处,View部分则负责展现资料、接收使用者输入资料。
在Java应用中,JFC/Swing、AWT、JSP皆是可用作View的技术规格,而JavaBean与Enterprise JavaBean规格则可用于Model程序代码,一旦应用程序以MVC模式加以适当的分割,Model部分程序代码可在不同使用者接口外观的应用程序中重复使用。
随着JSP与Servlet技术大量应用于以Web为基础的应用程序,Java开发人员群体认为应以较佳的模式以提升Web应用程序的可维护性与重复使用性。
配置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方法相同的格式。
Struts2入门初步需掌握1.struts2概述2.struts2环境搭建(第一个struts2的应用程序)3.struts.xml文件配置详解4.struts2请求的URL的搜索路径的顺序概述5.struts2工作原理概述6.struts2指定多个配置文件7.struts2动态方法调用8.使用通配符定义action一:简介Struts 2是Struts的下一代产品,是在 struts 1和WebWork的技术基础上进行了合并的全新的Struts 2框架。
其全新的Struts 2的体系结构与Struts 1的体系结构差别巨大。
Struts 2以WebWork为核心,采用拦截器的机制来处理用户的请求,这样的设计也使得业务逻辑控制器能够与Servlet API完全脱离开,所以Struts 2可以理解为WebWork的更新产品。
虽然从Struts 1到Struts 2有着太大的变化,但是相对于WebWork,Struts 2的变化很小。
二:环境搭建搭建Struts2环境时,我们一般需要做以下几个步骤的工作:1.找到开发Struts2应用需要使用到的jar文件.下载官网:/download.cgi#struts221解压后:开始学习使用依赖的最基本的jar 包2:编写Struts2的配置文件解压其中一个案例在此目录下找到struts.xml 文件先拷贝到项目的src 下。
再对起进行修改。
删除剩余如下代码:[html]01.<?xml version ="1.0"encoding ="UTF-8" ?> 02.<!DOCTYPE struts PUBLIC 03."-//Apache Software Foundation//DTD StrutsConfiguration 2.3//EN" 04."/dtds/struts-2.3.dtd"> 05.06.<struts> 07.08. </struts>无法加载插件。
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。
Struts2(上)一、经典的MVC模式二、Struts1.x对MVC的实现三、Struts1.x的主要组件和作用组件作用ActionServlet 中央控制器Action 分控制器,调用JavaBean实现业务逻辑,Action可以分为Action、DispatchAction等不同类型ActionForm 封装参数,实现服务器验证,文件上传等Forward 转发到目的地,可以是JSP,也可以是另一个ActionStruts-config.xml 配置文件,配置有ActionForm,Action,Forward等,通过XML解析,然后使用反射技术使用该文件Struts标签库和JSTL类似,和Struts-config.xml、ActionForm、Action等对象可以紧密集成四、Struts1.x 开发实例-登录程序见案例。
五、Struts2(WebWork)的MVCStruts2的MVC架构六、Struts2的主要组件组件作用FilterDispatcher 起中央控制器作用的过滤器Action 处于Model层的Action,调用JavaBean实现业务逻辑struts.xml 核心配置文件,配置有Action、Result等result 和forward类似,转发的目的地,支持多种视图技术。
七、Struts2的实例-登录在MyEclipse环境中建立一个新的web工程,名称“Struts2Login”,存放路径“f:\Struts2Login”。
在Struts2.0.11版本中找到war包struts2-blank-2.0.11.war,解开该war包,在WEB-INF/lib 目录下复制出所有的jar包,这些jar包就是一个Struts2程序所需要的基础jar包,把它们复制到新建的web工程的WEB-INF/lib目录中。
在src目录下建立一个类,包名mypack,类名UserAction,其代码如下:package mypack;import com.opensymphony.xwork2.ActionSupport;public class UserAction extends ActionSupport {private String username;private String userpass;public String getUsername() {return username;}public void setUsername(String username) {ername = username;}public String getUserpass() {return userpass;}public void setUserpass(String userpass) {erpass = userpass;}@Overridepublic String execute() throws Exception {if ("Mike".equals(username) && "123".equals(userpass)|| "张三".equals(username) && "abc".equals(userpass))return "success";elsereturn "error";}}在src目录下建立Struts2的配置文件struts.xml,内容如下:<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""/dtds/struts-2.0.dtd"><struts><!-- 定义包管理配置的action 继承struts-default.xml中的配置 --><package name="actions" extends="struts-default"><!-- 定义Action(login.action) --><action name="login" class="erAction"><!-- 定义转发路径对应的字符串名 --><result name="success">/Success.jsp</result><result name="error">/Error.jsp</result></action></package></struts>修改web.xml,在其中加入一个过滤器,过滤/*路径。
Yaio 4一、准备工作及实例 41.解压struts-2.1.6-all.zip 42.六个基本包 43.初识struts2配置文件 4(1).web.xml文件 4(2).struts.xml文件 4(3).struts.properties(参default.properties) 4 (4)struts-default.xml 5(5)其它配置文件 54.让MyEclipse提示xml信息 55.如何使用alt+/提示 56.实例 57.开启struts2自带的开发模式常量 78.vo传参模式 89.ModerDriven传参模式(不建议采用) 810.为什么要使用struts2代替struts1.x 9二、struts.xml配置及例程 91.配置文件的优先级 92.配置形式 93.package配置相关 104.分工合作include:指定多个配置文件 125.tomcat认证访问 126.初识拦截器 137.Action中的method属性 158.使用ForwardAction实现页面屏蔽。
178.使用default-Action配置统一访问 17小结Action 189.使用通配符 1810.使用0配置:ZERO Annotation 1911.Result配置详解 1912.异常处理 24三、在Action获取Scope对象 25方式一、与Servlet解耦合的非IOC方式 25方式二、与Servlet解耦合的IOC方式 27 方式三、与Servlet耦合的非IOC方式 27 方式四、与Servlet耦合的IOC方式 28四、OGNL与ValueStack(VS) 291.值栈入门 292.OGNL入门 313.普通方法访问 314.静态方法访问 315.默认类Math的访问 326.调用普通类的构造方法 327.集合对象初步 328.集合对象进阶 339.N语法top语法 3410.获取Stack Context中的信息 3511.总结$ # %的区别 3512.总结OGNL[重点] 35五、拦截器 361.概述strust2中的拦截器 362.自定义拦截器 37方式一,实现Interceptor接口。
37方式二、继承AbstractInterceptor抽象类 38 方式三、继承MethodFilterInteceptor类 383.使用来MethodFilterInterceptor灵活拦截 414.使用默认的execAndWait拦截器 425. TokenInterceptor防止表单重复提交。
446.使用拦截器实现权限验证 467.拦截器中的注解 488.使用PreResultListener实现回调 50六、使用标签 521.基础表单标签 522.单选按钮和复选框: 523.三种方式实现下拉列表 524.二级联动 545.其它表单标签 576.其它常用标签的使用(代码参名为“补充”的文件夹下的tag.jsp) 59七、国际化 601.action级别下的国际化 602.配置package的资源文件 633.app级别的资源文件 634.使用资源文件的原理 635.选择使用资源文件 64八、验证机制 651.基于手工编码的校验 65简析校验流程: 692.基于XML配置形式的校验 69九、文件上传下载(了解) 711. 上传实例 712.下载实例 74十、类型转换 751.基于Action的直接属性转换 752.基于Action的间接属性vo转换 76十一、注解配置 77十二、总结本教程对struts2的基本知识进行了一些说明,关于struts2的更多详细内容应参看struts2的官方文档及提供的app实例。
下面对struts2的基本执行流程作一简要说明,此流程说明可以结合官方提供的struts2结构图来看: 78Yaio一、准备工作及实例1.解压struts-2.1.6-all.zipapps目录:struts2自带的例子程序docs目录:官方文档。
lib 目录:存放所有jar文件。
Src 目录:源文件存放地2.六个基本包struts2-core-2.1.6.jar :开发的核心类库freemarker-2.3.13.jar :struts2的UI标签的模板使用freemarker编写commons-logging-1.0.4.jar :日志包OGNL-2.6.11.jar :对象图导航语言,通过它来读写对象属性xwork-2.1.2.jar :xwork类库,struts2在其上进行构建commons-fileupload-1.2.1.jar:文件上传组件,2.1.6版本后必须加入此jar包特别需要说明的是目前strust2的最新版本是struts-2.1.6,它作为2.1.X 的正式版。
特别要注意导入commons-fileupload-1.2.1.jar包,在此jar包中包含了RequestContext类,如果不导入该jar包将会报异常。
3.初识struts2配置文件(1).web.xml文件主要完成对StrutsPrepareAndExecuteFilter的配置(在以前的版本中是对FilterDispatcher配置,新版本同样支持用FilterDispatcher配置),它的实质是一个过滤器,它负责初始化整个Struts框架并且处理所有的请求。
这个过滤器可以包括一些初始化参数,有的参数指定了要加载哪些额外的xml配置文件,还有的会影响struts框架的行为。
除了StrutsPrepareAndExecuteFilter外,Struts 还提供了一个ActionContexCleanUp类,它的主要任务是当有其它一些过滤器要访问一个初始化好了的struts框架的时候,负责处理一些特殊的清除任务。
(2).struts.xml文件框架的核心配置文件就是这个默认的struts.xml文件,在这个默认的配置文件里面我们可以根据需要再包括其它一些配置文件。
在通常的应用开发中,我们可能想为每个不同的模块单独配置一个struts.xml文件,这样也利于管理和维护。
这也是我们要配置的主要文件。
(3).struts.properties(参default.properties)在Struts框架使用了很多属性,我们可以通过改变这些属性来满足我们的需求。
要改变这些属性,只需在struts.properties文件中指定属性的key和value 即可。
属性文件可以放在任何一个包含在classpath中的路径上,但是通常我们都把它放在/WEB-INF/classes目录下面。
我们可以在struts-default.properties 文件中找到一个属性的列表。
(4)struts-default.xml此文件是struts2框架默认加载的配置文件,它定义了struts2一些核心bean和拦截器,它会自动包含(included)到struts.xml文件中(实质是通过<package extends="struts-default">),并为我们提供了一些标准的配置。
我们可以在struts2-core.jar中找到这个文件。
(5)其它配置文件velocity.properties,struts-default.vm,struts-plugin.xml4.让MyEclipse提示xml信息当我们在编写struts.xml时,发现eclipse并不会给出帮助提示,那是因为MyEclipse默认并不支持struts2,所以我们需要手工导入dtd以支持提示。
步骤:[window][preferences][MyEclipse][Files and Editors][XML][xml Catelog]然后在右边点add添加:location为dtd文件所在的位置(struts-2.0.dtd文件struts2-core-2.1.6.jar中可以得到),KeyType选择URI,Key为struts-2.0.dtd文件中文档声明的内容(),在struts.xml文件中也有此key值。
5.如何使用alt+/提示在MyEclipse6.5中,默认的提示为Ctrl+Space,而它会与我们的输入法切换冲突,使提示失效。
找到key,先取消Content Assist命令的绑定,再用“alt+/”来绑定。
6.实例步骤一,新建myStruts2项目,并导入struts2的六个基本jar包。
步骤二,建立LoginAction文件,主要代码如下:package com.asm;import com.opensymphony.xwork2.Action;public class LoginAction implements Action {private String username;private String password;...省略get/set方法public String execute() throws Exception {if (username.equals("struts2")) {return "loginSuccess";} else {return "loginFailure";}}}说明:实现了Action接口,主要是为了保证execute的正确定义,其实我们也可以不实现此接口,只要能保证execute方法书写的正确书写(方法名,返回值)。
步骤三,在struts.xml文件中注册LoginAction。
此配置文件要放在src目录下,实质就是成为classpath环境变量下的文件。
主要代码如下:<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"""><struts><package name="myFirst" namespace="/" extends="struts-default"><action name="login" class="com.asm.LoginAction"><result name="loginSuccess">/success.jsp</result><result name="loginFailure">/failure.jsp</result></action></package></struts>说明:package后面会有详细说明。