struts2入门手册
- 格式:doc
- 大小:261.82 KB
- 文档页数:10
1 Struts2极速表单验证框架使用说明书struts ‐plusStruts enhancement, includes quick form validation, permission mgmt. Struts 框架增强, 包括极速表单验证, 权限管理等.子模块之Struts 2 极速表单验证框架作者: 刘长炯(beansoft@)日期: 2010‐01‐20版本: 0.1修订历史2010‐01‐20 初始版1 Struts2极速表单验证框架使用说明书..................................................................................1 2 Struts 2 极速表单验证框架简介...........................................................................................2 3 项目许可...................................................................................................................................3 4 下载本项目...............................................................................................................................3 5 演示应用...................................................................................................................................4 6 整合步骤step by step...............................................................................................................8 7 验证规则表达式详解.............................................................................................................12 8 和RapidValidation 配合实现前后台一致验证.......................................................................13 9 如何扩展验证规则.................................................................................................................14 10 下一版本开发计划 (17)2 Struts 2 极速表单验证框架简介Struts Plus, Struts + 项目, 计划包含极速表单验证框架, 权限管理等子模块. 目前主要关注于 Struts 2 方面的生产力提高项目, 主要基于注解方式进行增强, 并提供抽象层, 使项目仅仅依赖于 Struts 本身, 而不需要强制您使用某种业务层和数据层框架. 项目的许可采用MIT协议, 您可自由的使用本项目, 但需遵循MIT协议保留本人版权签名及MIT协议本身.本文主要讲述子模块Struts 2 极速表单验证框架(Struts 2 QuickFormValidation).本验证机制基于表达式和注解(Annotation), 验证规则的扩展通过实现验证接口进行.诞生历史:2009年12月18日晚提出框架原理, 并于2009年12月19日晨提出实现思路, 最终框架核心初步完成于2009年12月20日(周日), 2010‐01‐20日整理发布.在项目的开发中, 表单验证需要用去开发者大量的时间, 尤其是为了保证前后台的验证规则一致时, 更是需要大量的人力物力. 虽然Struts 2本身的验证框架可以保证前后台一致, 但在使用和整合方式上, 需要编写大量的Validation XML文件, 费力费时容易出错, 尤其是实际开发中需要反复调整各种验证规则及其组合, 这时就更加困难; 扩展Struts 2的验证框架更是需要比较繁琐的步骤. 针对这些挑战, 笔者试图提供一种简便易用的方式来进行表单验证, 即基于Java注解和验证规则表达式.如下面的代码即可实现如下的验证要求: 1) 用户名不能为空, 最小长度5, 最大长度10, 只能输入英文字母; 2) 年龄字段只能输入数字, 最小值为18, 最大值为100; 验证失败时, 转向input页面并显示出错信息: ${validationErrors}.@FormValidator(input="form_tag", value=",用户名,required min-length-5 max-length-10 validate-alpha;" +"age,年龄,validate-digits min-value-18 max-value-100;") public String form_tag() throws Exception {return SUCCESS;}•最快速的后台表单验证框架•简洁,快速的验证语法•无需编写验证提示信息•错误消息在指定地方显示•支持组合验证•易于扩展•基于标准的Java Annotation添加验证,易于和现有项目的无缝集成•特殊应用场景支持,如:密码确认,结束日期必须大于开始日期•支持前后台一致的验证规则本框架主要是为了和前台基于JavaScript的开源验证框架RapidValidation(/p/rapid‐validation/ )使用统一的验证规则, 最大限度的减少重复的后台验证代码, 使用方式简便, 扩展方便.本框架依赖于:z Struts 2z Java 5或者更高版本3项目许可The MIT LicenseCopyright (c) 2010 刘长炯(beansoft@)Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.4下载本项目您可访问/p/struts‐plus/downloads/list 来获取最新源代码包文件名说明大小struts2-quickvalidation-plugin-1.0-src.jar Struts 2 QuickFormValidation 26.81.0 sources 源码Featured KBstruts2-quickvalidation-plugin-1.0.jar Struts 2 QuickFormValidation1.0 jar Featured 26.8 KBstruts2-quickvalidation-demo.war 演示war包,部署至Tomcat6运行Featured 3.4 MBJavascript_RapidValidation.pdf JavaScript Rapid Validation框架的详细使用及规则说明文档(转载)176KB5演示应用可下载示例应用来体验Struts极速验证框架, 下载地址为:http://struts‐/files/struts2‐quickvalidation‐demo.war . 放入Tomcat后即可查看运行效果. 您可以本demo应用为基础快速的进行开发.本演示包含三个内容:纯后台表单验证前后台一致表单验证(前台验证基于RaplidValidation)前后台一致表单验证(Struts 2 Form 标签)本war包中的唯一的.java文件源码如下:package actions;import com.opensymphony.xwork2.ActionSupport;import common.validation.FormValidator;public class HelloWorldAction extends ActionSupport {// 或者implements Action {@FormValidator(input="form", value=",用户名,required min-length-5 max-length-10 validate-alpha;" +"age,年龄,validate-digits min-value-18 max-value-100;" +"password,密码,required;" +"password2,重复密码,required equals-password-原始密码;" +"email,,validate-email;" +"gender,性别,validate-one-required;" +"ip,,validate-ip;" +"date,生日,validate-date;" +"num1,数字1,validate-number;" +"num2,数字2,validate-number less-than-num1-数字1;" +"float,数字范围,float-range-1-10;" +"address,地址,validate-chinese;" +"zip,邮编,validate-zip;" +"id_num,身份证,validate-id")public String form() throws Exception {return SUCCESS;}@FormValidator(input="form_js", value=",用户名,required min-length-5 max-length-10 validate-alpha;" +"age,年龄,validate-digits min-value-18 max-value-100;" +"password,密码,required;" +"password2,重复密码,required equals-password-原始密码;" +"email,,validate-email;" +"gender,性别,validate-one-required;" +"ip,,validate-ip;" +"date,生日,validate-date;" +"num1,数字1,validate-number;" +"num2,数字2,validate-number less-than-num1-数字1;" +"float,数字范围,float-range-1-10;" +"address,地址,validate-chinese;" +"zip,邮编,validate-zip;" +"id_num,身份证,validate-id")public String form_js() throws Exception {return SUCCESS;}@FormValidator(input="form_tag", value=",用户名,required min-length-5 max-length-10 validate-alpha;" +"age,年龄,validate-digits min-value-18 max-value-100;") public String form_tag() throws Exception {return SUCCESS;}}下面是三个演示的效果:6整合步骤step by step1. 将文件struts2‐quickvalidation‐plugin‐1.0.jar放入Web项目的WEB‐INF/lib目录下;2. 修改您自己的代码的src/struts.xml中的package定义继承自quickValidation;示例代码:<?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><package name="test" namespace="" extends="quickValidation"> <action name="helloworld" class="actions.HelloWorldAction"> <result name="index">/index.jsp</result><result name="success">/helloworld.jsp</result></action></package></struts>3. 使用注解加入验证规则表达式;在每个需要调用的Action的入口方法处, 加入@FormValidator注解.注解的完整语法如下:@common.validation.FormValidator(input="出错时需要返回的result别名", enabled=true/false, value="表单参数名称1,表单参数中文提示信息1,规则1 规则2…; 表单参数名称2,表单参数中文提示信息2,规则1 规则2…;更多字段验证信息")input参数: 可选. 如果不指定, 则出错时仍然继续进入到Action方法中; 如果指定, 则在表单验证出错时, 返回到给定的result中, 例如: 原始表单输入页面或者统一的错误输出页面; enabled参数: 可选. 是否启用此验证规则, 如果不指定, 则忽略解析注解, 不进行任何验证; value参数: 必填选项, 可输入一个或者多个表单参数验证规则. 简单说就是: [字段1验证配置];[字段2验证配置];…. 虽然不建议, 然而字段验证配置可以留空, 此时不会进行任何验证处理.而每个验证配置的格式如下:表单参数名称: 必填选项. 指向输入的表单控件的名称(input的name);表单参数中文提示信息: 可选. 如果为空, 则和表单参数名称相同. 不为空时, 则显示在出错时的信息提示的开头位置;规则1 规则2…: 可选. 理论上可加入任意多个验证规则, 以单个空格隔开. 在验证开始后, 依次进行每个规则的验证并加入提示信息. 需要注意的是, 除required规则之外的所有规则只有当用户输入的字段值非空时, 才进行有效性验证, 如此便可避免所有字段都成为必填字段的问题发生.每个规则本身则由两部分组成: 规则名‐规则子名‐参数1‐参数2‐参数3‐….规则名和规则子名是固定名称, 不能任意填写, 这两个名称对应一个具体的规则实现类.其中参数是必填选项, 参数的意义则需要参考下一节的验证规则表达式中的说明. 下面举例说明若干验证规则:required 这是特殊规则, 不带规则子名, 也没有额外的参数;float‐range‐1‐20 其中float‐range分别是规则名和规则子名, 而1和20则分别是两个参数. 特别需要注意的是有负数时的情况此时参数列表变为: float-range--1--20, 此时参数值分别为‐1和‐20.如果需要给另一字段加入验证规则, 则以分号隔开.下面是若干验证的示例及其解释:规则 解释@FormValidator 空的验证规则, 不进行任何操作@FormValidator("username,用户名,required min‐length‐5") 对username字段进行验证, 规则为必填, 最小长度为5; 出错时分别提示:用户名不能为空用户名的长度不能小于5, 当前长度为1.由于没有指定input参数, 所以当验证失败时, 仍然会继续进入到业务逻辑处理, 相关的错误信息则存入request 的attribute中.@FormValidator("username, ,required min‐length‐5")由于没有指定字段的中文提示, 因此出错时将提示:username的长度不能小于5, 当前长度为1.@FormValidator(input="index",value=" username,用户名,required min‐length‐5”) 这大概是最常用格式的验证规则的写法了. 此例和上例的区别为: 所以当验证失败时, 将进入input参数所指定的出错信息显示页面.@FormValidator(input="index",enabled=false,value=" username,用户名,required min‐length‐5”) 忽略所有验证规则处理, 常用于调试阶段.@FormValidator(input="index",value=" username,用户名,required min‐length‐5;password2,重复密码,required equals‐password‐原始密码;”) 此规则加入了对重复密码字段的验证, 出错时将提示:重复密码和原始密码的输入不一致@FormValidator(input="index",value="username,用户名,required min‐length‐5;password2,重复密码,required equals‐password;”) 此规则省略了另一字段的中文描述, 出错时将提示:重复密码和前面的输入不一致以下为一个完整的Action类示例代码:import com.opensymphony.xwork2.ActionSupport;import common.validation.FormValidator;public class HelloWorldAction extends ActionSupport {@FormValidator(input="index", value="username,用户名,requiredmin-length-5 max-length-10 validate-alpha;" +"age,年龄,validate-digits min-value-18max-value-100;password,密码,required;" +"password2,重复密码,required equals-password-原始密码;" +"gender,性别, validate-one-required")public String execute() throws Exception {return SUCCESS;}}4. 修改前台显示验证结果.根据Action的不同, 前台的显示划分为两类:普通的错误显示:所有错误信息: ${validationErrors}返回的内容是一个字符串, 显示了所有的出错信息, 而出错字体的颜色则需要用户自己去设置.出错信息的显示格式是以<br>分开的, 例如:用户名不能为空<br>密码不能为空<br>重复密码不能为空<br>性别必须至少选中一项<br>另一种推荐的做法是让Action继承自Struts2中的ActionSupport, 此时则可用Struts 2的标签来显示出错信息, 可定位到具体的字段:<%@ taglib prefix="s" uri="/struts-tags" %><s:actionerror /><s:fielderror/><s:form action="helloworld.action" method="post"><s:textfield name="username" label="用户名" /><s:password name="password" label="密码" /><s:submit/></s:form>或者使用纯JSP来编写页面来定位到单条错误:用户名: <input name=username value=${ername}> ${ername[0]}下面给出这两种写法的完整示例:<%@ page pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><html><head><style>.errorMessage {color:red;}.errorLabel {font-weight:bold}</style><title>测试页面</title></head><body><s:actionerror /><form action="helloworld.action" method=postenctype="multipart/form-data">用户名: <input name=username value=${ername}>${ername[0]} <br>年龄: <input name=age value=${param.age}><br>密码: <input name=password><br>密码重复: <input name=password2><br>邮件: <input name=email><br>性别: <input type=checkbox name=a>男<input type=checkbox name=a>女<br> IP地址: <input name=ip><br>数字1: <input name=num1>数字2: <input name=num2><br>日期:<input name=date><br>附件: <input name=file type=file><br><input type=submit value="提交"></form><span class="errorMessage">${validationErrors}</span>Struts 2表单标签示例:<s:fielderror/><s:form action="helloworld.action" method="post"><s:textfield name="username" label="用户名" /><s:password name="password" label="密码" /><s:submit/></s:form></body></html>7验证规则表达式详解说明: 加红色背景的部分是目前尚不支持的验证规则; 加黄色背景的是增加了第二个可选参数的规则(和前台验证规则略有变动).验证表达式 描述 示例 required 非空域,全部空格也算空validate-number 一个有效数validate-digits 只能包含0-9任意个数字validate-alpha 只能是字母a-z, A-Zvalidate-alphanum 只能是字母和数字的组合validate-email 只能是有效的emailvalidate-url 只能是有效的url地址validate-one-required 至少有一个被选中,例如一组checkbox, radiobutton,它们最好包含在一个div和span中validate-integer 只能是整数,可以有正负号validate-ip 有效的IP地址min-length-$number 最小长度是$number (此处$some表示一个特定的值)最小长度为8: min-length-8max-length-$number 最大长度是$number 最大长度为8:max-length-8 max-value-$number 输入域的最大值是$number 最大值为8.1:max-value-8.1 min-value-$number 输入域的最小值是$number 最大值为-8.1:max-value--8.1equals-$otherInputId-$othe rInputLabel 必须和某个input field相等,用于密码两次输入验证等,$otherInputLabel是可选项,用来描述另一字段信息equals-password重复密码和原始密码输入不一致:equals-password-原始密码less-than-$otherInputId-$o therInputLabel 小于某个input fieldless-than-otherInputId,多用于结束日期不能小于开始日期的需求,$otherInputLabel是可注:相等时也不能通过选项,用来描述另一字段信息great-than-$otherInputId-$ otherInputLabel 大于某个input fieldless-than-otherInputId,$o therInputLabel是可选项,用来描述另一字段信息validate-date-$dateFormat 只能是日期,$dateFormat为日期格式,$dateFormat的可选,默认格式为yyyy-MM-DD validate-date-yyyy年MM月dd 日validate-file-$type1-$type 2-$typeX 验证文件输入域选择的文件类型只能为声明的$type1 –$typeX中的一种validate-file-png-jpegfloat-range-$minValue-$max Value 必须是$minValue到$maxValue的一个浮点数1至20:float-range-1-20int-range-$minValue-$maxVa lue 必须是$minValue到$maxValue的一个整数length-range-$minLength-$m axLength 输入字符串的长度必须在$minLength到$maxLength之间validate-pattern-$RegExp 通过自定义正则表达式$RegExp来验证输入域的正确性 vaidate-patter n-/a/givalidate-chinese 只能是中文(以下为中国的相关验证)validate-phone 有效的电话validate-mobile-phone 有效的手机号validate-id-number 验证是否有效的身份证号码validate-zip 验证邮政编码validate-qq 验证QQ号码8和RapidValidation配合实现前后台一致验证RapidValidation (/p/rapid‐validation/) 是专注于前台的验证框架, 例如下面的例子:<!-- 为form增加required-validate class,标识需要验证form --><form id='helloworld' action="#" class='required-validate'> helloworld:</br><!--通过class添加验证: required表示不能为空,min-length-15表示最小长度为15 --><textarea name='content' class='requiredmin-length-15'></textarea></br><input type='submit' value='Submit'/><input type='reset' value='Reset'/></form>其对应的后台验证规则为:@FormValidator(input="index",value=" content,helloworld,required min‐length‐15”)请注意比较异同, 不同部分已经以红色粗体进行了区分, 相同部分则以绿色粗体标识.大家可以看到, 两者很容易就实现了一致的前后台验证规则.相关的说明文档请访问: /p/rapid‐framework/wiki/rapid_validation , 另外本项目也提供了一份完整文档的转载, 包含详细的规则说明文档和整合步骤:(http://struts‐/files/Javascript_RapidValidation.pdf ).9如何扩展验证规则要扩展验证只需要实现IValidator即可即可, 并将实现类放入包 common.quickvalid.validators下. 下面是IValidator接口定义:package common.quickvalid.validators;import java.util.Map;/***所有验证器的抽象接口.*@author beansoft*日期:2009-12-20*/public interface IValidator {/***实现验证方法.*@param fieldName字段name*@param fieldDescription出错时的字段描述信息*@param params参数列表<String key, String[] values>表单参数Map *@param args参数列表*@return验证信息,为空时表示没有任何出错信息,通过验证*/public String doValidation(String fieldName, String fieldDescription, Map<String, String[]> params, String... args) ;/***获取验证器本身的参数列表.*@return*/public String[] getArgs();/***设置验证器本身的参数列表*@param args-一个或者多个参数,允许为null*/public void setArgs(String[] args);/***获取原始表达式.*@return*/public String getExpression();/***设置原始表达式,用于日期,正则等验证方式,避免和-号冲突.*@param Expression*/public void setExpression(String expression);}在实践中, 已经提供了几种比较常见的实现类的抽象基类, 它们是:BaseValidator, 抽象的验证器实现, 仅实现了 setter和getter;BaseRegexValidator(继承自BaseValidator), 基于正则表达式验证的基类; BaseTwoNumberValidator(继承自BaseValidator), 提供基于两个数字规则的验证, 可获取两个参数(含‐号).类名有一定规则, 将第一个减号替换为下划线即可, 例如:float-range-$minLength-$maxLength 对应的类名是: length_range.下面则给出一些实现类, 供参考:手机号的验证:package common.quickvalid.validators;/***手机号验证*TODO更多号段的支持?*@author beansoft**/public class validate_mobile extends BaseRegexValidator {@Overridepublic String getMessage() {return"只能输入正确的手机号码,如:138********";}@Overridepublic String getRegEx() {return"(^0?[1][35][0-9]{9}$)";}}数字范围的验证:package common.quickvalid.validators;import java.util.Map;/***表单域取值浮点数验证*@author beansoft**/public class float_range extends BaseTwoNumberValidator {public String doValidation(String fieldName, String fieldDescription,Map<String, String[]> params, String... args) { super.setParams(params);String value = getValue(fieldName);super.parseTwoNumberArgs();//重新分析=args// 非空时进行验证if(value != null && value.length() > 0) {boolean result = false;try {(Double.parseDouble(value) <=resultDouble.parseDouble(args[0])) ||(Double.parseDouble(value) >Double.parseDouble(args[1]));} catch(Exception ex) {return fieldDescription + "的输入值不是有效的数字";}if(result) {return fieldDescription + "的输入值" + value + "应该为" + args[0] + "到" + args[1] + "之间的数字";}}return null;}}10下一版本开发计划z将验证规则表达式解析和执行部分独立出来作为核心引擎z兼容JDK 1.4 并提供独立调用的接口z提供Struts 1下的插件机制z提示文字国际化z增强前台验证, 提供时分秒的验证功能如果您对本项目有兴趣, 欢迎加入.。
一.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完成初始化操作。
一、发展历史及简介发展历史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入门初步需掌握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,在其中加入一个过滤器,过滤/*路径。
第一章Struts2系统架构本章主要介绍的Struts2的系统架构,让学员对Struts2框架在结构上有一个整体概念为我们以后更加详细的学习Struts2打下一个良好的基础。
第一节Struts2的系统架构及处理的主要流程1.Struts1简介Struts1的历史比较久远,Struts1是世界上第一个发布的MVC框架,目前市场率最高的框架。
下面将简单讲解Struts1的基本架构。
图1-1显示了Struts1的数据流图。
图1-1 Struts1数据流图Struts1框架以ActionServlet为核心控制器,ActionServlet获得客户端请求。
然后ActionServlet根据请求信息调用匹配的业务逻辑控制器(Action)处理用户请求。
请求处理完成后,业务逻辑处理器调用相应的JSP显示处理结果。
Struts1框架实现了MVC模式,下面我们了解一下Struts1是怎样实现MVC模式的。
Struts1框架中并没有提供Model层的实现。
在实际的企业应用中,通过一个JavaBean 实现一个业务逻辑,在功能比较复杂的应用中也采用EJB或WebService服务实现业务逻辑。
Struts1框架的View层采用JSP实现。
Struts1提供了大量丰富的标签库。
这些标签库与Struts的组件兼容的特别好,可以很容易的输出控制器的处理结果。
Struts1框架中,控制器是它的核心,Struts1的控制器由两部分组成:核心控制器(ActionServlet)和业务逻辑控制器(Action),核心控制器由Struts1框架提供。
业务逻辑控制器需要由用户自己继承Struts1框架提供的Action类实现。
在Struts1框架中,JSP/Servlet耦合非常紧密。
这种紧密关系促使Struts1存在各种缺陷。
下面我们分析一下Struts1中存在的缺陷。
●支持的表现层技术单一●耦合性强,不便于单元测试●代码依赖于Struts1 API,侵入性强2.WebWork简介WebWork出自于开源组织opensymphony,实际的创始人是Java领域的名人Rickard Oberg(JBoss和XDoclet的作者)。
Struts2讲义(1):web.xml配置在现在开发的Web项目中,大家都是使用web.xml来实现MVC框架的应用。
既然Struts2也属于MVC 框架,因此在web.xml中必定要配置Struts2用以实现应用。
技术要点本节代码说明Struts2基本配置。
1、如何加载FilterDispatcher过滤器。
2、如何使用FilterDispatcher过滤器拦截URL。
演示代码Java 代码1.<!--------------------------------------- 文件名: web.xml-------------------------------->2.<?xml version="1.0" encoding="GB2312"?>3.<web-app xmlns=/xml/ns/j2ee4. xmlns:xsi=/2001/XMLSchema-instance5. version="2.4"6.xsi:schemaLocation="/xml/ns/j2ee7./xml/ns/j2ee/web-app_2_4.xsd">8. <filter>9. <!-- 过滤器名字 -->10. <filter-name>struts2</filter-name>11. <!-- 过滤器支持的struts2类 -->12. <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>13. </filter>14.15. <filter-mapping>16. <!-- 过滤器拦截名字 -->17. <filter-name>struts2</filter-name>18. <!-- 过滤器拦截文件路径名字 -->19. <url-pattern>/*</url-pattern>20. </filter-mapping>21. <welcome-file-list>22. <welcome-file>index.jsp</welcome-file>23. </welcome-file-list>24.</web-app>代码解释(1)在Struts1中web.xml中对它的加载都是加载一个Servlet,但是在Struts2中,因为设计者为了实现AOP(面向方面编程)概念,因此是用filter来实现的。
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。