Struts2-01

来源:互联网 发布:金城学院继续教育jaVa 编辑:程序博客网 时间:2024/06/05 17:21

一、框架概述

1.框架的意义与作用

所谓框架,就是把一些繁琐的重复性代码封装起来,使程序员在编码中把更多的经历放到业务需求的分析和理解上面。

特点:封装了很多细节,程序员在使用的时候会非常简单。

2.三大框架

struts、hibernate、spring

3.学好框架

框架的细节很多,知识点比较零散,做好笔记尤为重要。

二、关于三层架构

三、struts2简介

1.struts2概述

struts1:也是apache开发的一套mvc的开源框架。在2005年之前非常流行。

 弊端:struts1的核心控制器就是一个servlet。随着使用者的增多,弊端开始出现。

struts2:在很久之前,有一个设计超前的框架XWork,后来推出了XWork1和WebWork2。struts2就是apache和OpenSymphony组织合并开发出来。里面包含了WebWork2的核心及struts的一些特性和功能。除此之外,和struts1没有任何关系了。

四、搭载struts2的开发环境

1.下载struts的开发包

http://struts.apache.org

2.开发包的目录结构

3.搭载开发环境

3.1拷贝jar包到classpath下

struts2所需要的jar包:

commons-beautils           : [beanutils工具包]

commons-filupload.ajr

commons-io.jar               :两个文件上传所需要的包

commons-lang                : [struts2对java.lang.*类的支持]

freemarker.jar                   : [视图显示技术]

javassit                              : [struts2对字节码运算的支持]

ognl.jar                              : [struts2对ognl表达式的支持]

struts2-core.jar                :[ struts2的核心包]

xwork-core.jar                  : [webwork框架的支持,struts2的前身就是webwork(对webwork的封装)]

3.2建立struts的配置文件

       注意:

                            1.文件名大小写。

                            2.创建位置。

                            3.该名称允许修改,但是我们一般不改。

3.3配置控制器

a、配置位置:在web.xml中

b、配置什么: struts2已经写好了的一个过滤器。

结论:struts2比struts1优秀的一个体现就是,它用了更为强大的过滤器作为控制器了。


struts2强大的过滤器:org.apache.struts2.dispatcher.ng.filter.StrutsprepareAndExecuteFilter

3.4验证是否成功

部署应用,启动Tomcat,不报错表示搭建成功。

五、struts2执行过程(重要)


文字说明:

tomcat启动加载web.xml,实例化并初始化过滤器:StrutsPrepareAndExecuteFilter,由前端过滤器加载struts.xml配置文件

客户端发送请求hello.action,请求到达前端过滤器,前端过滤器截取请求的动作名称并从struts.xml配置文件中找

找到后实例化动作类,调用对应的动作方法,方法返回一个值,根据返回值找到name取值对应的结果视图,最终找到jsp页面,响应浏览器,展示结果。


明确:


struts2的前端过滤器拦截action的时候会生成一个动作类的代理类ConfigurationManager,他会读取struts.xml配置文件确实能够执行哪个方法。(具体的源码分析改天再贴上去)

六、struts2的配置文件

1.加载时机

当应用被tomcat加载的时候,struts2的配置文件就已经被加载过了。

2.加载顺序

1.default.properties:

该配置文件中提供了常量,体现形式都是key=value。所有的struts2应用都会用到这些常量。

常用的:


## $Id: default.properties 1532467 2013-10-15 18:20:43Z lukaszlenart $## Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements.  See the NOTICE file# distributed with this work for additional information# regarding copyright ownership.  The ASF licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License.  You may obtain a copy of the License at##  http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied.  See the License for the# specific language governing permissions and limitations# under the License.#### START SNIPPET: complete_file### Struts default properties###(can be overridden by a struts.properties file in the root of the classpath)###### Specifies the Configuration used to configure Struts### one could extend org.apache.struts2.config.Configuration### to build one's customize way of getting the configurations parameters into Struts# struts.configuration=org.apache.struts2.config.DefaultConfiguration### This can be used to set your default locale and encoding scheme# struts.locale=en_USstruts.i18n.encoding=UTF-8### if specified, the default object factory can be overridden here### Note: short-hand notation is supported in some cases, such as "spring"###       Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here# struts.objectFactory = spring### specifies the autoWiring logic when using the SpringObjectFactory.### valid values are: name, type, auto, and constructor (name is the default)struts.objectFactory.spring.autoWire = name### indicates to the struts-spring integration if Class instances should be cached### this should, until a future Spring release makes it possible, be left as true### unless you know exactly what you are doing!### valid values are: true, false (true is the default)struts.objectFactory.spring.useClassCache = true### ensures the autowire strategy is always respected.### valid values are: true, false (false is the default)struts.objectFactory.spring.autoWire.alwaysRespect = false### if specified, the default object type determiner can be overridden here### Note: short-hand notation is supported in some cases, such as "tiger" or "notiger"###       Alternatively, you can provide a com.opensymphony.xwork2.util.ObjectTypeDeterminer implementation name here### Note: By default, com.opensymphony.xwork2.util.DefaultObjectTypeDeterminer is used which handles type detection###       using generics. com.opensymphony.xwork2.util.GenericsObjectTypeDeterminer was deprecated since XWork 2, it's###       functions are integrated in DefaultObjectTypeDeterminer now.###       To disable tiger support use the "notiger" property value here.#struts.objectTypeDeterminer = tiger#struts.objectTypeDeterminer = notiger### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data# struts.multipart.parser=cos# struts.multipart.parser=pellstruts.multipart.parser=jakarta# uses javax.servlet.context.tempdir by defaultstruts.multipart.saveDir=struts.multipart.maxSize=2097152### Load custom property files (does not override struts.properties!)# struts.custom.properties=application,org/apache/struts2/extension/custom### How request URLs are mapped to and from actions#struts.mapper.class=org.apache.struts2.dispatcher.mapper.DefaultActionMapper### Used by the DefaultActionMapper### You may provide a comma separated list, e.g. struts.action.extension=action,jnlp,do### The blank extension allows you to match directory listings as well as pure action names### without interfering with static resources, which can be specified as an empty string### prior to a comma e.g. struts.action.extension=, or struts.action.extension=x,y,z,,struts.action.extension=action,,### Used by FilterDispatcher### If true then Struts serves static content from inside its jar.### If false then the static content must be available at <context_path>/strutsstruts.serve.static=true### Used by FilterDispatcher### This is good for development where one wants changes to the static content be### fetch on each request.### NOTE: This will only have effect if struts.serve.static=true### If true -> Struts will write out header for static contents such that they will###             be cached by web browsers (using Date, Cache-Content, Pragma, Expires)###             headers).### If false -> Struts will write out header for static contents such that they are###            NOT to be cached by web browser (using Cache-Content, Pragma, Expires###            headers)struts.serve.static.browserCache=true### Set this to false if you wish to disable implicit dynamic method invocation### via the URL request. This includes URLs like foo!bar.action, as well as params### like method:bar (but not action:foo).### An alternative to implicit dynamic method invocation is to use wildcard### mappings, such as <action name="*/*" method="{2}" class="actions.{1}">struts.enable.DynamicMethodInvocation = false### Set this to true if you wish to allow slashes in your action names.  If false,### Actions names cannot have slashes, and will be accessible via any directory### prefix.  This is the traditional behavior expected of WebWork applications.### Setting to true is useful when you want to use wildcards and store values### in the URL, to be extracted by wildcard patterns, such as### <action name="*/*" method="{2}" class="actions.{1}"> to match "/foo/edit" or### "/foo/save".struts.enable.SlashesInActionNames = false### Disables support for action: prefixstruts.mapper.action.prefix.enabled = false### Blocks access to actions in other namespace than current with action: prefixstruts.mapper.action.prefix.crossNamespaces = false### use alternative syntax that requires %{} in most places### to evaluate expressions for String attributes for tagsstruts.tag.altSyntax=true### when set to true, Struts will act much more friendly for developers. This### includes:### - struts.i18n.reload = true### - struts.configuration.xml.reload = true### - raising various debug or ignorable problems to errors###   For example: normally a request to foo.action?someUnknownField=true should###                be ignored (given that any value can come from the web and it###                should not be trusted). However, during development, it may be###                useful to know when these errors are happening and be told of###                them right away.struts.devMode = false### when set to true, resource bundles will be reloaded on _every_ request.### this is good during development, but should never be used in productionstruts.i18n.reload=false### Standard UI theme### Change this to reflect which path should be used for JSP control tag templates by defaultstruts.ui.theme=xhtmlstruts.ui.templateDir=template#sets the default template type. Either ftl, vm, or jspstruts.ui.templateSuffix=ftl### Configuration reloading### This will cause the configuration to reload struts.xml when it is changedstruts.configuration.xml.reload=false### Location of velocity.properties file.  defaults to velocity.propertiesstruts.velocity.configfile = velocity.properties### Comma separated list of VelocityContext classnames to chain to the StrutsVelocityContextstruts.velocity.contexts =### Location of the velocity toolboxstruts.velocity.toolboxlocation=### used to build URLs, such as the UrlTagstruts.url.http.port = 80struts.url.https.port = 443### possible values are: none, get or allstruts.url.includeParams = none### Load custom default resource bundles# struts.custom.i18n.resources=testmessages,testmessages2### workaround for some app servers that don't handle HttpServletRequest.getParameterMap()### often used for WebLogic, Orion, and OC4Jstruts.dispatcher.parametersWorkaround = false### configure the Freemarker Manager class to be used### Allows user to plug-in customised Freemarker Manager if necessary### MUST extends off org.apache.struts2.views.freemarker.FreemarkerManager#struts.freemarker.manager.classname=org.apache.struts2.views.freemarker.FreemarkerManager### Enables caching of FreeMarker templates### Has the same effect as copying the templates under WEB_APP/templatesstruts.freemarker.templatesCache=false### Enables caching of models on the BeanWrapperstruts.freemarker.beanwrapperCache=false### See the StrutsBeanWrapper javadocs for more informationstruts.freemarker.wrapper.altMap=true### maxStrongSize for MruCacheStorage for freemarker, when set to 0 SoftCacheStorage which performs better in heavy loaded application### check WW-3766 for more detailsstruts.freemarker.mru.max.strong.size=0### configure the XSLTResult class to use stylesheet caching.### Set to true for developers and false for production.struts.xslt.nocache=false### Whether to always select the namespace to be everything before the last slash or notstruts.mapper.alwaysSelectFullNamespace=false### Whether to allow static method access in OGNL expressions or notstruts.ognl.allowStaticMethodAccess=false### Whether to throw a RuntimeException when a property is not found### in an expression, or when the expression evaluation failsstruts.el.throwExceptionOnFailure=false### Logs as Warnings properties that are not found (very verbose)struts.ognl.logMissingProperties=false### Caches parsed OGNL expressions, but can lead to memory leaks### if the application generates a lot of different expressionsstruts.ognl.enableExpressionCache=true### Indicates if Dispatcher should handle unexpected exceptions by calling sendError()### or simply rethrow it as a ServletException to allow future processing by other frameworks like Spring Securitystruts.handle.exception=true### END SNIPPET: complete_file

常量的覆盖有三种:

第一种:以键值对的形式写在struts.properties配置文件中



第二种:在struts.xml文件中覆盖常量

使用<constant name=""value=""></constant>元素进行覆盖


第三种:在web.xml中配置过滤器参数


2.struts-default.xml:



<?xml version="1.0" encoding="UTF-8" ?><!--/* * $Id: struts-default.xml 1485719 2013-05-23 14:12:24Z lukaszlenart $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *  http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. */--><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"><struts>    <bean class="com.opensymphony.xwork2.ObjectFactory" name="xwork" />    <bean type="com.opensymphony.xwork2.ObjectFactory" name="struts" class="org.apache.struts2.impl.StrutsObjectFactory" />    <bean type="com.opensymphony.xwork2.FileManager" class="com.opensymphony.xwork2.util.fs.DefaultFileManager" name="system" scope="singleton"/>    <bean type="com.opensymphony.xwork2.FileManagerFactory" class="com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory" name="xwork" scope="singleton"/>    <bean type="com.opensymphony.xwork2.FileManagerFactory" class="com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory" name="struts" scope="singleton"/>    <bean type="com.opensymphony.xwork2.ActionProxyFactory" name="xwork" class="com.opensymphony.xwork2.DefaultActionProxyFactory"/>    <bean type="com.opensymphony.xwork2.ActionProxyFactory" name="struts" class="org.apache.struts2.impl.StrutsActionProxyFactory"/>    <bean type="com.opensymphony.xwork2.conversion.ObjectTypeDeterminer" name="tiger" class="com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer"/>    <bean type="com.opensymphony.xwork2.conversion.ObjectTypeDeterminer" name="notiger" class="com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer"/>    <bean type="com.opensymphony.xwork2.conversion.ObjectTypeDeterminer" name="struts" class="com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer"/>    <bean type="com.opensymphony.xwork2.util.PatternMatcher" name="struts" class="com.opensymphony.xwork2.util.WildcardHelper" />    <bean type="com.opensymphony.xwork2.util.PatternMatcher" name="namedVariable" class="com.opensymphony.xwork2.util.NamedVariablePatternMatcher"/>    <bean type="com.opensymphony.xwork2.util.PatternMatcher" name="regex" class="org.apache.struts2.util.RegexPatternMatcher"/>    <bean type="org.apache.struts2.dispatcher.mapper.ActionMapper" name="struts" class="org.apache.struts2.dispatcher.mapper.DefaultActionMapper" />    <bean type="org.apache.struts2.dispatcher.mapper.ActionMapper" name="composite" class="org.apache.struts2.dispatcher.mapper.CompositeActionMapper" />    <bean type="org.apache.struts2.dispatcher.mapper.ActionMapper" name="restful" class="org.apache.struts2.dispatcher.mapper.RestfulActionMapper" />    <bean type="org.apache.struts2.dispatcher.mapper.ActionMapper" name="restful2" class="org.apache.struts2.dispatcher.mapper.Restful2ActionMapper" />    <bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest" name="struts" class="org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest" scope="default"/>    <bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest" name="jakarta" class="org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest" scope="default" />    <constant name="struts.multipart.parser" value="jakarta" />    <bean type="org.apache.struts2.views.TagLibrary" name="s" class="org.apache.struts2.views.DefaultTagLibrary" />    <bean class="org.apache.struts2.views.freemarker.FreemarkerManager" name="struts" />    <bean class="org.apache.struts2.views.velocity.VelocityManager" name="struts" optional="true" />    <bean class="org.apache.struts2.components.template.TemplateEngineManager" />    <bean type="org.apache.struts2.components.template.TemplateEngine" name="ftl" class="org.apache.struts2.components.template.FreemarkerTemplateEngine" />    <bean type="org.apache.struts2.components.template.TemplateEngine" name="vm" class="org.apache.struts2.components.template.VelocityTemplateEngine" />    <bean type="org.apache.struts2.components.template.TemplateEngine" name="jsp" class="org.apache.struts2.components.template.JspTemplateEngine" />    <bean type="com.opensymphony.xwork2.conversion.impl.XWorkConverter" name="struts" class="com.opensymphony.xwork2.conversion.impl.XWorkConverter" />    <bean type="com.opensymphony.xwork2.conversion.ConversionPropertiesProcessor" name="struts" class="com.opensymphony.xwork2.conversion.impl.DefaultConversionPropertiesProcessor" />    <bean type="com.opensymphony.xwork2.conversion.ConversionFileProcessor" name="struts" class="com.opensymphony.xwork2.conversion.impl.DefaultConversionFileProcessor" />    <bean type="com.opensymphony.xwork2.conversion.ConversionAnnotationProcessor" name="struts" class="com.opensymphony.xwork2.conversion.impl.DefaultConversionAnnotationProcessor" />    <bean type="com.opensymphony.xwork2.conversion.TypeConverterCreator" name="struts" class="com.opensymphony.xwork2.conversion.impl.DefaultTypeConverterCreator" />    <bean type="com.opensymphony.xwork2.conversion.TypeConverterHolder" name="struts" class="com.opensymphony.xwork2.conversion.impl.DefaultTypeConverterHolder" />    <bean class="com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter" />    <bean type="com.opensymphony.xwork2.conversion.impl.CollectionConverter" name="struts" class="com.opensymphony.xwork2.conversion.impl.CollectionConverter" scope="singleton"/>    <bean type="com.opensymphony.xwork2.conversion.impl.ArrayConverter" name="struts" class="com.opensymphony.xwork2.conversion.impl.ArrayConverter" scope="singleton"/>    <bean type="com.opensymphony.xwork2.conversion.impl.DateConverter" name="struts" class="com.opensymphony.xwork2.conversion.impl.DateConverter" scope="singleton"/>    <bean type="com.opensymphony.xwork2.conversion.impl.NumberConverter" name="struts" class="com.opensymphony.xwork2.conversion.impl.NumberConverter" scope="singleton"/>    <bean type="com.opensymphony.xwork2.conversion.impl.StringConverter" name="struts" class="com.opensymphony.xwork2.conversion.impl.StringConverter" scope="singleton"/>    <bean type="com.opensymphony.xwork2.TextProvider" name="struts" class="com.opensymphony.xwork2.TextProviderSupport" scope="default" />    <bean type="com.opensymphony.xwork2.LocaleProvider" name="struts" class="com.opensymphony.xwork2.DefaultLocaleProvider" scope="singleton" />    <bean type="org.apache.struts2.components.UrlRenderer" name="struts" class="org.apache.struts2.components.ServletUrlRenderer"/>    <bean type="org.apache.struts2.views.util.UrlHelper" name="struts" class="org.apache.struts2.views.util.DefaultUrlHelper"/>    <bean type="com.opensymphony.xwork2.util.ValueStackFactory" name="struts" class="com.opensymphony.xwork2.ognl.OgnlValueStackFactory" />    <bean type="com.opensymphony.xwork2.util.reflection.ReflectionProvider" name="struts" class="com.opensymphony.xwork2.ognl.OgnlReflectionProvider" />    <bean type="com.opensymphony.xwork2.util.reflection.ReflectionContextFactory" name="struts" class="com.opensymphony.xwork2.ognl.OgnlReflectionContextFactory" />    <bean type="com.opensymphony.xwork2.TextProvider" name="system" class="com.opensymphony.xwork2.DefaultTextProvider" />    <bean type="com.opensymphony.xwork2.conversion.NullHandler" name="java.lang.Object" class="com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler" />    <bean type="com.opensymphony.xwork2.validator.ActionValidatorManager" name="struts" class="com.opensymphony.xwork2.validator.AnnotationActionValidatorManager" />    <bean type="com.opensymphony.xwork2.validator.ActionValidatorManager" name="no-annotations" class="com.opensymphony.xwork2.validator.DefaultActionValidatorManager" />    <bean type="com.opensymphony.xwork2.validator.ValidatorFactory" class="com.opensymphony.xwork2.validator.DefaultValidatorFactory"/>    <bean type="com.opensymphony.xwork2.validator.ValidatorFileParser" class="com.opensymphony.xwork2.validator.DefaultValidatorFileParser" />    <bean class="com.opensymphony.xwork2.ognl.OgnlUtil" />    <bean type="com.opensymphony.xwork2.util.TextParser" name="struts" class="com.opensymphony.xwork2.util.OgnlTextParser" scope="singleton"/>    <bean type="ognl.PropertyAccessor" name="com.opensymphony.xwork2.util.CompoundRoot" class="com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor" />    <bean type="ognl.PropertyAccessor" name="java.lang.Object" class="com.opensymphony.xwork2.ognl.accessor.ObjectAccessor" />    <bean type="ognl.PropertyAccessor" name="java.util.Iterator" class="com.opensymphony.xwork2.ognl.accessor.XWorkIteratorPropertyAccessor" />    <bean type="ognl.PropertyAccessor" name="java.util.Enumeration" class="com.opensymphony.xwork2.ognl.accessor.XWorkEnumerationAccessor" />    <bean type="ognl.PropertyAccessor" name="java.util.List" class="com.opensymphony.xwork2.ognl.accessor.XWorkListPropertyAccessor" />    <bean type="ognl.PropertyAccessor" name="java.util.Set" class="com.opensymphony.xwork2.ognl.accessor.XWorkCollectionPropertyAccessor" />    <bean type="ognl.PropertyAccessor" name="java.util.Map" class="com.opensymphony.xwork2.ognl.accessor.XWorkMapPropertyAccessor" />    <bean type="ognl.PropertyAccessor" name="java.util.Collection" class="com.opensymphony.xwork2.ognl.accessor.XWorkCollectionPropertyAccessor" />    <bean type="ognl.PropertyAccessor" name="com.opensymphony.xwork2.ognl.ObjectProxy" class="com.opensymphony.xwork2.ognl.accessor.ObjectProxyPropertyAccessor" />    <bean type="ognl.MethodAccessor" name="java.lang.Object" class="com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor" />    <bean type="ognl.MethodAccessor" name="com.opensymphony.xwork2.util.CompoundRoot" class="com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor" />    <bean class="org.apache.struts2.views.jsp.ui.OgnlTool" />    <bean type="org.apache.struts2.dispatcher.StaticContentLoader" class="org.apache.struts2.dispatcher.DefaultStaticContentLoader" name="struts" />    <bean type="com.opensymphony.xwork2.UnknownHandlerManager" class="com.opensymphony.xwork2.DefaultUnknownHandlerManager" name="struts" />    <!--  Silly workarounds for OGNL since there is currently no way to flush its internal caches -->    <bean type="ognl.PropertyAccessor" name="java.util.ArrayList" class="com.opensymphony.xwork2.ognl.accessor.XWorkListPropertyAccessor" />    <bean type="ognl.PropertyAccessor" name="java.util.HashSet" class="com.opensymphony.xwork2.ognl.accessor.XWorkCollectionPropertyAccessor" />    <bean type="ognl.PropertyAccessor" name="java.util.HashMap" class="com.opensymphony.xwork2.ognl.accessor.XWorkMapPropertyAccessor" />    <package name="struts-default" abstract="true">        <result-types>            <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>            <result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>            <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>            <result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>            <result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>            <result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>            <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>            <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>            <result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>            <result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" />        </result-types>        <interceptors>            <interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>            <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>            <interceptor name="chain" class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/>            <interceptor name="conversionError" class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/>            <interceptor name="cookie" class="org.apache.struts2.interceptor.CookieInterceptor"/>            <interceptor name="cookieProvider" class="org.apache.struts2.interceptor.CookieProviderInterceptor"/>            <interceptor name="clearSession" class="org.apache.struts2.interceptor.ClearSessionInterceptor" />            <interceptor name="createSession" class="org.apache.struts2.interceptor.CreateSessionInterceptor" />            <interceptor name="debugging" class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />            <interceptor name="execAndWait" class="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/>            <interceptor name="exception" class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/>            <interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>            <interceptor name="i18n" class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>            <interceptor name="logger" class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/>            <interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>            <interceptor name="scopedModelDriven" class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/>            <interceptor name="params" class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>            <interceptor name="actionMappingParams" class="org.apache.struts2.interceptor.ActionMappingParametersInteceptor"/>            <interceptor name="prepare" class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/>            <interceptor name="staticParams" class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>            <interceptor name="scope" class="org.apache.struts2.interceptor.ScopeInterceptor"/>            <interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>            <interceptor name="timer" class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/>            <interceptor name="token" class="org.apache.struts2.interceptor.TokenInterceptor"/>            <interceptor name="tokenSession" class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/>            <interceptor name="validation" class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>            <interceptor name="workflow" class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/>            <interceptor name="store" class="org.apache.struts2.interceptor.MessageStoreInterceptor" />            <interceptor name="checkbox" class="org.apache.struts2.interceptor.CheckboxInterceptor" />            <interceptor name="profiling" class="org.apache.struts2.interceptor.ProfilingActivationInterceptor" />            <interceptor name="roles" class="org.apache.struts2.interceptor.RolesInterceptor" />            <interceptor name="annotationWorkflow" class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor" />            <interceptor name="multiselect" class="org.apache.struts2.interceptor.MultiselectInterceptor" />            <!-- Basic stack -->            <interceptor-stack name="basicStack">                <interceptor-ref name="exception"/>                <interceptor-ref name="servletConfig"/>                <interceptor-ref name="prepare"/>                <interceptor-ref name="checkbox"/>                <interceptor-ref name="multiselect"/>                <interceptor-ref name="actionMappingParams"/>                <interceptor-ref name="params">                    <param name="excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>                </interceptor-ref>                <interceptor-ref name="conversionError"/>            </interceptor-stack>            <!-- Sample validation and workflow stack -->            <interceptor-stack name="validationWorkflowStack">                <interceptor-ref name="basicStack"/>                <interceptor-ref name="validation"/>                <interceptor-ref name="workflow"/>            </interceptor-stack>            <!-- Sample file upload stack -->            <interceptor-stack name="fileUploadStack">                <interceptor-ref name="fileUpload"/>                <interceptor-ref name="basicStack"/>            </interceptor-stack>            <!-- Sample model-driven stack  -->            <interceptor-stack name="modelDrivenStack">                <interceptor-ref name="modelDriven"/>                <interceptor-ref name="basicStack"/>            </interceptor-stack>            <!-- Sample action chaining stack -->            <interceptor-stack name="chainStack">                <interceptor-ref name="chain"/>                <interceptor-ref name="basicStack"/>            </interceptor-stack>            <!-- Sample i18n stack -->            <interceptor-stack name="i18nStack">                <interceptor-ref name="i18n"/>                <interceptor-ref name="basicStack"/>            </interceptor-stack>            <!-- An example of the paramsPrepareParams trick. This stack                 is exactly the same as the defaultStack, except that it                 includes one extra interceptor before the prepare interceptor:                 the params interceptor.                 This is useful for when you wish to apply parameters directly                 to an object that you wish to load externally (such as a DAO                 or database or service layer), but can't load that object                 until at least the ID parameter has been loaded. By loading                 the parameters twice, you can retrieve the object in the                 prepare() method, allowing the second params interceptor to                 apply the values on the object. -->            <interceptor-stack name="paramsPrepareParamsStack">                <interceptor-ref name="exception"/>                <interceptor-ref name="alias"/>                <interceptor-ref name="i18n"/>                <interceptor-ref name="checkbox"/>                <interceptor-ref name="multiselect"/>                <interceptor-ref name="params">                    <param name="excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>                </interceptor-ref>                <interceptor-ref name="servletConfig"/>                <interceptor-ref name="prepare"/>                <interceptor-ref name="chain"/>                <interceptor-ref name="modelDriven"/>                <interceptor-ref name="fileUpload"/>                <interceptor-ref name="staticParams"/>                <interceptor-ref name="actionMappingParams"/>                <interceptor-ref name="params">                    <param name="excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>                </interceptor-ref>                <interceptor-ref name="conversionError"/>                <interceptor-ref name="validation">                    <param name="excludeMethods">input,back,cancel,browse</param>                </interceptor-ref>                <interceptor-ref name="workflow">                    <param name="excludeMethods">input,back,cancel,browse</param>                </interceptor-ref>            </interceptor-stack>            <!-- A complete stack with all the common interceptors in place.                 Generally, this stack should be the one you use, though it                 may do more than you need. Also, the ordering can be                 switched around (ex: if you wish to have your servlet-related                 objects applied before prepare() is called, you'd need to move                 servletConfig interceptor up.                 This stack also excludes from the normal validation and workflow                 the method names input, back, and cancel. These typically are                 associated with requests that should not be validated.                 -->            <interceptor-stack name="defaultStack">                <interceptor-ref name="exception"/>                <interceptor-ref name="alias"/>                <interceptor-ref name="servletConfig"/>                <interceptor-ref name="i18n"/>                <interceptor-ref name="prepare"/>                <interceptor-ref name="chain"/>                <interceptor-ref name="scopedModelDriven"/>                <interceptor-ref name="modelDriven"/>                <interceptor-ref name="fileUpload"/>                <interceptor-ref name="checkbox"/>                <interceptor-ref name="multiselect"/>                <interceptor-ref name="staticParams"/>                <interceptor-ref name="actionMappingParams"/>                <interceptor-ref name="params">                    <param name="excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>                </interceptor-ref>                <interceptor-ref name="conversionError"/>                <interceptor-ref name="validation">                    <param name="excludeMethods">input,back,cancel,browse</param>                </interceptor-ref>                <interceptor-ref name="workflow">                    <param name="excludeMethods">input,back,cancel,browse</param>                </interceptor-ref>                <interceptor-ref name="debugging"/>            </interceptor-stack>            <!-- The completeStack is here for backwards compatibility for                 applications that still refer to the defaultStack by the                 old name -->            <interceptor-stack name="completeStack">                <interceptor-ref name="defaultStack"/>            </interceptor-stack>            <!-- Sample execute and wait stack.                 Note: execAndWait should always be the *last* interceptor. -->            <interceptor-stack name="executeAndWaitStack">                <interceptor-ref name="execAndWait">                    <param name="excludeMethods">input,back,cancel</param>                </interceptor-ref>                <interceptor-ref name="defaultStack"/>                <interceptor-ref name="execAndWait">                    <param name="excludeMethods">input,back,cancel</param>                </interceptor-ref>            </interceptor-stack>       </interceptors>        <default-interceptor-ref name="defaultStack"/>        <default-class-ref class="com.opensymphony.xwork2.ActionSupport" />    </package></struts>

3.struts-plugin.xml:

<?xml version="1.0" encoding="UTF-8" ?><!--/* * $Id: struts-plugin.xml 1221225 2011-12-20 12:22:28Z jogep $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *  http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. */--><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd">    <struts>    <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />        <!--  Make the Spring object factory the automatic default -->    <constant name="struts.objectFactory" value="spring" />    <constant name="struts.class.reloading.watchList" value="" />    <constant name="struts.class.reloading.acceptClasses" value="" />    <constant name="struts.class.reloading.reloadConfig" value="false" />    <package name="spring-default">        <interceptors>            <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>        </interceptors>    </package>    </struts>

七、xml配置文件的主要元素

1.package元素

1.1作用:在struts2的配置文件中引入了面向对象思想,使用了分包管理。易于管理动作类。便于模块化开发动作类。

1.2属性

name:包的名称。必须写。且必须唯一。

extends:一般情况下需要继承struts-default包,但不是必须的。不过如果不继承的话,将无法使用struts2提供的核心功能。struts-default.xml中定义着struts-default这个包。而struts-default.xml是在我们的struts.xml加载之前加载。

abstract:把包声明为抽象包,抽象包就是用来被继承的。只要是没有<action>元素的包,就可以声明为抽象包。

namespace:名称空间。名称空间  +     动作名称  =     访问路径


1.3package中的namespace详解

namespace的默认值:

                                                 a.不写该属性

                                                 b.写了该属性,取值是一个"".

                                                 注意:默认值不是/

动作类的搜索顺序:


2.action元素

2.1

作用:   配置动作用的。

2.2属性:

name:动作名称

class:动作类全名。默认的动作类是:com.opensymphony.xwork2.ActionSupport,是在struts-default.xml中定义的。



要想替换默认动作类:

                                          在应用的struts.xml中,package中加入:


method:动作类中的方法名称。默认是public String execute(){}

要求:

1.public的

2.返回值必须是String

3.没有参数

2.3、struts2的Action三种使用方式:

第一种方式:不实现Action接口

/** * 第一种方式:不需要实现或继承任何接口或类 * @author APPle * */public class UserAction2 {public String login()throws Exception{System.out.println("UserAction2.login()");return "success";}}
第二种方式,实现Action接口      
/** * 第二种方式:实现Action接口 * 1)定义了默认的execute方法的标准 *  2)提供了项目中常用的视图标记 * @author APPle * */public class UserAction implements Action {public String login() throws Exception {System.out.println("执行了UserAction的login方法");return SUCCESS;}public String execute() throws Exception {return null;}}
常量:给动作方法返回值用的。用常量可以使你的应用规范和统一。


第三种方式, 继承ActionSupport类(推荐)

/** * 第三种方式: 继承ActionSupport类(推荐使用) * 好处:  * 1)提供了常用的视图标记 * 2)提供了数据校验功能 *  * @author APPle * */public class UserAction3 extends ActionSupport{public String login()throws Exception{System.out.println("UserAction3.login()");return SUCCESS;}}
2.4、动作的访问

a.使用通配符:


升级版:


优先级:绝对匹配优先。使用通配符的按照在配置文件中的先后顺序进行匹配的。

b.动态方法调用

动作名称!动作方法名称


<!-- struts2的动态方法调用: struts2提供的一种访问action的方法 访问action的路径规则:  user!login    action的名称!action的方法 --><!-- <action name="user" class="gz.itcast.c_constant.UserAction"><result name="success">/login.jsp</result></action> -->

八、结果类型视图(逻辑结果视图)

该部分内容指的就是struts配置文件中的result元素的使用

1.result元素

作用:为动作指定结果视图

属性:

name:逻辑视图的名称,对应着动作方法的返回值。默认值是success

type:结果类型,指的就是用什么方式转到定义的页面。默认是dispatcher

2.result元素中type的取值

type属性的取值在struts-default.xml中定义着。


         redirect:   重定向到页面

                                                                 dispatcher:转发到页面                 

                                                                 redirectAction:重定向到Action

                                                                 chain:    转发到Action

常用结果类型介绍:

dispatcher:(默认值) 使用请求转发,转向一个页面。

redirect: 使用重定向,转向一个页面。


redirectAction:注意:使用的是重定向

a.重定向到另一个相同名称空间的动作。


b.重定向到不同名称空间的动作。


chain:注意: 使用的是请求转发。

a.转发到另一个相同名称空间的动作。


b.请求转发到不同名称空间的动作


3、result元素中param子元素

在转发或者重定向到不同包下的动作时,都用到了result元素的子元素param。

param元素的作用:依赖注入(Dependence Injection)思想

我们通过struts-default.xml中的resultTypes元素中配置可以看出,每个结果类型视图其实都是靠一个类来实现的。而param元素就是将配置的参数,注入到该类中。调用的是对应类的setter方法进行注入的。

例如:redirectAction结果视图


该类中肯定会有对actionName和namespace属性的注入方法(setter方法)。


再比如:默认结果视图dispatcher


4.自定义结果类型

通过前面的内容,我们看出,其实结果类型就是一个类,这些类都实现了com.opensymphony.xwork2.Result接口。

或者继承自该接口的实现类org.apache.struts2.dispatcher.StrutsResultSupport。 这些类都有一个doExecute方法,用于执行结果视图。

综上:我们也可以自己写一个结果视图。

例子:输出CAPTCHA图像的结果类型

CAPTCHA(CompletelyAutomated Public Turing Test to Tell Computers and Humans Apart 全自动区分计算机和人类的图灵测试)————>简称:验证码。

第一步:写一个类,实现接口或者继承接口的实现类


第二步:在struts.xml文件中配置结果类型    

第三步:在action配置时引用


最终结果:

扩展:通过可配置的参数,实现图像大小的调整

5.struts2的全局视图配置和默认配置

5.1 全局视图作用: 当该包下的所有action都使用到的一些视图就是可以放到全局视图配置中

注意:  当action中也有相同名称的视图,那么action的局部视图会覆盖全局视图。

<!-- 全局视图配置: 把该包下的所有action共用的视图都机集中在这里写 --><global-results><result name="success">/login.jsp</result></global-results>

5.2 action的默认配置

<!-- 默认配置  name: 必填项 class: 可选项。默认配置:  ActionSupport类   该类继承自struts-default (<default-class-ref class="com.opensymphony.xwork2.ActionSupport" />) method: 可选。默认配置:execute result:    name: 可选。默认配置:success    type: 可选。默认配置:dispatcher --> <!-- 全部使用默认配置的action的作用:专门用于转发到WEB-INF下的页面 --> <action name="book"> <result>/WEB-INF/jsp/login.jsp</result> </action>

九、在动作类中访问Servlet的API

第一种方式:使用ServletActionContext类

文本说明:

动作类直接继承ActionSupport类,在该类的内部:

HttpServletRequest request = ServletActionContext.getRequest();

HttpServletResponse response = ServletActionContextResponse();

第二种方式:使用实现接口的方式

文本说明:

动作类继承ActionContext类实现request、response接口,在类的内部中注入HttpServletRequest、HttpServletResponse对象。使用的是注入的思想,在执行动作方法之前把request、response注入到action中。什么时候注入的呢?

九、分文件编写框架的配置文件

1.不分文件开发可能会产生的问题:就类似于我们在写java类时,所有代码都写在一个类里,甚至写在一个方法里。

当3个人都checkout了struts.xml文件时,第一个人提交了,后面的人在没有更新就提交时,第一个人写的可能就白写了。

2.分文件编写Struts2的配置文件



十、Struts2数据共享的三种方式

在web项目中都是使用域对象来共享数据。struts2提供给开发者使用域对象来共享数据的方法一共有三种。

第一种方式:

ServletActionContext类

getRequest(): 获取request对象

getRequest().getSession(): 获取session对象

getServletContext(): 获取ServletContext对象

注意:

1)该方式依赖servlet的api,耦合比较高

2)如果要通过域对象来获取域对象的相关信息必须使用该方式

// 用request,session,context域对象来共享数据/** * 1)strus2提供的第一种使用域对象的方法(如果单纯的使用域对象来存取数据 ,不推荐使用这种方式) *      ServletActionContext对象:可以在struts2的action方法中使用域对象 *    特点: 依赖servlet原生的api *//*//获取request域对象HttpServletRequest request = ServletActionContext.getRequest();request.setAttribute("request_list", list);//获取session域对象HttpSession session = ServletActionContext.getRequest().getSession(true);session.setAttribute("session_list", list);//获取ServletContext域对象ServletContext context = ServletActionContext.getServletContext();context.setAttribute("context_list", list);*///得到客户的请求的相关数据/** * 注意: 如果用到了request/session/servletcontext对象中的除存取数据以外的其他方法,就必须得使用ServletActionContext *     来获取数据。 */ServletActionContext.getRequest().getMethod();


第二种方式:

ActionContext类

getContextMap(): 获取操作request域对象数据的map集合

getSession() :       获取操作session域对象数据的map集合

getApplication()  获取操作context域对象数据的map集合

注意:

1)不依赖servlet的api,耦合性低

2)只能用在Action对象的一个方法中。不能在所有方法中都是用同一个ActionContext

/*ActionContext ac = ActionContext.getContext();*//** * strus2提供的第二种使用域对象的方法(Action对象方法少的时候,可以使用这种方式) *     ActionContext对象: action的上下文对象,在这个ActionContext对象中提供操作不同域对象数据的Map集合 *      *     特点: *     1) 不依赖servlet原生的api,方便测试 *     2)只能在action的某个业务方法中使用 *//*//得到操作request域的map集合(操作这个Map集合就等同于操作了request域的数据)Map<String,Object> requestMap = ac.getContextMap();requestMap.put("request_list", list); //存放到request域中//得到操作session域的map集合Map<String,Object> sessionMap = ac.getSession();sessionMap.put("session_list", list);//得到操作context域的map集合Map<String, Object> contextMap = ac.getApplication();contextMap.put("context_list", list);*/


第三种方式:

使用  RequestAware、 SessionAware、 ApplicationAware 接口

注入操作对应域对象数据的Map集合

注意:

1)不依赖servlet的api

2)可以在Action对象的所有方法中共享Map集合

public class BaseAction extends ActionSupport implements RequestAware,SessionAware,ApplicationAware{protected Map<String,Object> requestMap;protected Map<String,Object> sessionMap;protected Map<String,Object> contextMap;//struts2自动会把操作request域的map集合传入public void setRequest(Map<String, Object> request) {this.requestMap = request;}//struts2自动会把操作session域的map集合传入public void setSession(Map<String, Object> session) {this.sessionMap = session;}//struts2自动会把操作context域的map集合传入public void setApplication(Map<String, Object> application) {this.contextMap = application;}}

/** * strus2提供的第三种使用域对象的方法(当Action对象的方法比较多的时候,推荐使用这种方法) *   通过struts2提供的接口注入到Action对象中 *   特点:  *   1)必须依赖struts2接口 *   2)可以在action对象的所有业务方法中使用!! * @author APPle * */public class UserAction2 extends BaseAction{public String list()throws Exception{//1)从数据库得到数据List<String> list = new ArrayList<String>();list.add("eric");list.add("jacky");list.add("rose");//往request域存放数据requestMap.put("request_list", list);//往session域存放数据sessionMap.put("session_list", list);//往context域存放数据contextMap.put("context_list", list);return "success";}}























原创粉丝点击