Struts2教程02

合集下载

Struts2学习之二--Struts2标签介绍

Struts2学习之二--Struts2标签介绍

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自学完全文档

struts2自学完全文档

一.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完成初始化操作。

Struts2教程2:处理一个form多个submit

Struts2教程2:处理一个form多个submit

在很多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方法)。

02-Struts2的工作流程及配置文件

02-Struts2的工作流程及配置文件

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入门手册

struts2入门手册

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入门教程(全新完整版)

STRUTS2入门教程(全新完整版)

一、发展历史及简介发展历史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应用程序的可维护性与重复使用性。

Struts2配置详解2 配置Action

Struts2配置详解2 配置Action

配置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方法相同的格式。

Apache Struts 2 教程(PDF)说明书

Apache Struts 2 教程(PDF)说明书

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。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

注:上面的两个方法都必须重写.
自定义类型转换器
5
自定义类型转换器--示例:转换成int[] 自定义类型转换器--示例:转换成int[]
6
注册自定义类型转换器有两种方法
局部类型转换器:只有特定的Action才可以使用
注册方法:在Action所在的包中建立properties文件,文件 名格式:Action类名-conversion.properties,内容如下: inver=com.aptech.conversition.IntArrayConverter 其中:inver是action属性名,
注:验证文件要和Action类放在同一包中
使用struts2验证框架我们应该做什么? 使用struts2验证框架我们应该做什么?
12
两个方面
DOCTYPE
从xwork-core-2.1.6.jar中可以找到
验证内容
查看doc文档,有详尽的说明和示范
验证文件怎么写? 验证文件怎么写?
13
输入员工信息应该遵循下面的规范
boolean,char,int,long,float,double基础类型,包括 封装类型和对应数组. Date,String数组,元素类型为String的List
Struts2类型转换 Struts2类型转换
4
类型转换器是一个继承自StrutsTypeConverter (抽象类)的类,必须重写两个方法:
public Object convertFromString(Map context, String[] values, Class toClass)
从字符串转换成目标类型
public String convertToString(Map context, Object o)
将目标类型转换成字符串
总结
19
int v = Integer.parseInt(request.getParameter(v));
缺陷:
过程烦琐枯燥.
传统类型转换
3
Struts2提供了强有力的表现层类型转换机制,无 需程序员过多干预即可自动完成转换. Struts能自动处理类型转换过程中出现的未知异 常. 下面的数据类型会自动转换:
验证示例--Action 验证示例--Action
15
验证文件名称为: EmployeeAction-validation.xml
验证员工姓名
<field name="ename" > <field-validator type="requiredstring"> <param name="trim">true</param> <message>员工姓名不能为空</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">20</param> <message>员工姓名必须在${minLength}-${maxLength}个字 符之间</message> </field-validator> </field>
处理类型转换异常
8
一般来说,struts为我们提供的默认转换器能实现 大部分需求,不需要重新定义新的转换器.
类型转换器小结
9
验证器和转换器是一对兄弟,他们总是如影随形. 所有用户的输入都是邪恶的 先类型转换,再验证 Struts2主要通过验证框架来完成数据验证. Action必须继承ActionSupport
前提:Action必须是ActionSupport的子类 如果不使用struts自带的错误信息,可以在Action所在 的包中定义”Action类名.properties”文件,内容如下:
invalid.fieldvalue.inver=整型数组转换出错 其中, invalid.fieldvalue固定,inver是属性名称
</field>
17
验证失败后,struts会自动跳转到result为input 的URL中,在页面中显示错误信息使用下面的标签
<s:fielderror>
此时,显示所有错误信息 通过fieldName显示指定属性的错误信息
显示验证错误信息
18
Struts2强大的数据类型转换与验证功能不仅降 低耦合度,而且能处理复杂的任务 数据验证需要阅读相关doc,实现起来并不难,但很 有用
验证文件格式:Action类名-validation.xml
也可以为Action的方法定义一个验证文件:
必须先为方法配置action
<action name="abcdo" class="com.aptech.actions.EmployeeAction" method="abc">
验证文件格式: Action类名-name-validation.型/长整型数值范围 邮箱验证 验证字段关系 必填项验证 字符串长度验证 URL验证 正则表达式验证
正则表达式能解决绝大部分验证问题
Struts2的验证框架能做什么? Struts2的验证框架能做什么?
11
我们可以为每一个单独的Action定义一个验证文 件
全局类型转换器:所有Action都可以使用
注册方法:在classpath下建立名为 xwork-conversion.properties的文件,内容如下: 目标类型(全限定名)=转换器全限定名
注册自定义类型转换器
7
转换出错后, ConversionErrorInterceptor截拦 器会截拦转换异常,该截拦器会带领我们进入 result为input的URL,并通过 <s:fielderror></s:fielderror>显示错误信息.
员工姓名必填,且在6-20个字符之间 员工年龄必须在18-100之间 员工的邮箱必须输入正确格式 员工电话号码只接受手机号
验证示例
14
public class EmployeeAction extends ActionSupport { private String ename; private int age; private String email; private String phone; }
Struts— Struts—第二章
类型转换与输入验证
1
2.1 类型转换 2.2 输入验证 2.3 fielderror标签
目标
2
客户端浏览器只能将字符串传送到服务器(文件上 传除外),而服务器端java语言是强类型语言,数据 类型非常丰富,这就造成B/S两端的类型不兼容问 题. 传统做法:
将客户端数据转变成int
验证示例— 验证示例—验证文件
16
验证电话号码(使用正则表达式)
<field name="phone">
<field-validator type="regex"> <param name="expression">
<![CDATA[(1[358]\d\d{8})]]>
</param> <message>只接受手机号</message> </field-validator>
相关文档
最新文档