【Java EE (Struts2 + Spring + Hibernate)开发】: Struts2(一)基本用法(待续)

【Java EE (Struts2 + Spring + Hibernate)开发】: Struts2(一)基本用法
本文地址:http://blog.csdn.net/shanglianlm/article/details/49975429

1 MVC 的思想概述

这里写图片描述

2 Struts2 的下载和安装

为 Web 应用添加 Struts2 支持

  1. 下载 Struts2
    文件结构:

    这里写图片描述
    这里写图片描述

  2. 将 Struts2的 lib 文件夹下的 commons-fileupload-1.3.1,commons-io-2.2,freemarker-2.3.22,javassist-3.11.0.GA,ognl-3.0.6,struts2-core-2.3.24.1 和 xwork-core-2.3.24.1必须类库复制到 Web 应用的 WEB-INF/lib 路径下。如果需要在DOS或者Shell窗口下手动编译 Struts2 相关的程序,还应该将 struts2-core-2.3.24.1 和 xwork-core-2.3.24.1 添加到系统的CLASSPATH环境变量里。

  3. 编辑 Web 应用的 web.xml 配置文件,配置 Struts2 的核心 Filter。

这里写图片描述

在 Eclipse 中使用 Struts 2

增加登录处理

3 Struts2 的流程

这里写图片描述

4 Struts2 的常规配置

4-1 常量配置

struts2 除了可使用 struts.xml 文件来管理配置之外,还可以使用 struts.properties 文件来管理常量。
Struts2常量的具体用法实例

<!-- 指定Web应用的默认编码集,相当于调用HttpServletRequest的setCharacterEncoding方法 --> 
<constant name="struts.i18n.encoding" value="UTF-8" /> 
<!-- 国际化-把资源文件定为全局变量 baseName为名字-->
<constant name="struts.custom.i18n.resources" value="baseName" /> 
<!--该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。 如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开-->
<constant name="struts.action.extension" value="do,action,htm,html,jsp" /> 
<!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 --> 
<constant name="struts.serve.static.browserCache" value="false" /> 
 <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开--> 
<constant name="struts.configuration.xml.reload" value="true" /> 
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 --> 
<constant name="struts.devMode" value="true" /> 
<!-- 默认的视图主题 --> 
<constant name="struts.ui.theme" value="simple" /> 
<!-- spring 托管 --> 
<constant name="struts.objectFactory" value="spring" /> 
<!--指定加载struts2配置文件管理器,默认为org.apache.struts2.config.DefaultConfiguration 开发者可以自定义配置文件管理器,该类要实现Configuration接口,可以自动加载struts2配置文件--> 
<constant name="struts.configuration" value="org.apache.struts2.config.DefaultConfiguration" /> 
<!-- 设置默认的locale和字符编码 --> 
<constant name="struts.locale" value="zh_CN" /> 
<constant name="struts.i18n.encoding" value="GBK" /> 
<!--指定spring框架的装配模式,装配方式有: name, type, auto, and constructor (name是默认装配模式)--> 
<constant name="struts.objectFactory.spring.autoWire" value="name" /> 
<!-- 该属性指定整合spring时,是否对bean进行缓存,值为true or false,默认为true --> 
<cosntant name="struts.objectFactory.spring.useClassCache" value="true"/> 
<!-- 指定类型检查,包含tiger和notiger --> 
<cosntant name="struts.objectTypeDeterminer" value="tiger" /> 
<!-- 该属性指定处理 MIME-type multipart/form-data,文件上传 --> 
<constant name="struts.multipart.parser" value="cos" /> 
<constant name="struts.multipart.parser" value="pell" /> 
<constant name="struts.multipart.parser" value="jakarta" /> 
<!-- 指定上传文件时的临时目录,默认使用 javax.servlet.context.tempdir --> 
<constant name="struts.multipart.saveDir" value="/tmpuploadfiles" /> 
<!-- 该属性指定Struts 2文件上传中整个请求内容允许的最大字节数 --> 
<constant name="struts.multipart.maxSize" value="2097152" /> 
<!--该属性指定Struts2应用加载用户自定义的属性文件,该自定义属性文件指定的属性不会覆盖struts.properties文件中指定的属性。如果需要加载多个自定义属性文件,多个自定义属性文 件的文件名以英文逗号(,)隔开。(也就是说不要改写struts.properties!)  --> 
<constant name="struts.custom.properties"value="application,org/apache/struts2/extension/custom" /> 
<!-- 指定请求url与action映射器,默认为org.apache.struts2.dispatcher.mapper.DefaultActionMapper --> 
<constant name="struts.mapper.class"           value="org.apache.struts2.dispatcher.mapper.DefaultActionMapper" /> 
<!-- 设置是否支持动态方法调用,true为支持,false不支持. --> 
<constant name="struts.enable.DynamicMethodInvocation" value="true" /> 
<!-- 设置是否可以在action中使用斜线,默认为false不可以,想使用需设置为true. --> 
<constant name="struts.enable.SlashesInActionNames" value="true" /> 
<!-- 是否允许使用表达式语法,默认为true. --> 
<constant name="struts.tag.altSyntax" value="true" /> 
<!-- 设置当struts.xml文件改动时,是否重新加载 --> 
<cosntant name="struts.configuration.xml.reload" value="true" /> 

struts2 会默认加载类加载路径下的 struts.xml, struts-default.xml, struts-plugin.xml 三类文件,其中 struts.xml 是开发者默认配置文件, struts-default.xml 是 struts2 框架自带的配置文件,而 struts-plugin.xml 则是 struts2 插件的默认配置文件。

struts2配置常量总共有三种方式:
- 通过 struts.properties 文件。
- 通过 struts.xml 文件。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
  <!-- 通过 constant 元素配置 struts2 的属性 -->
  <constant name="struts.custom.i18n.resources" value="mess" />
</struts>
  • 通过 Web 应用的 web.xml 文件。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <?xml version="1.0" encoding="UTF-8" ?>
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
    <init-param>
      <param-name>struts.custom.i18n.resources</param-name>
      <param-value>mess</param-value>
    </init-param>
</filter>
</web-app>

一个完整的 struts.xml 实例

<?xml version = "1.0" encoding = "UTF-8"?>
<!--下面是Struts2配置文件的DTD信息 -->
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<!--struts是struts2配置文件的跟元素 -->
<struts>
    <!--下面的元素可以出现0次,也可以出现无限多次 -->
    <constant name="" value="" />
    <!--下面的元素可以出现0次,也可以出现无限多次 -->
    <bean type="" name="" class="" scope="" static="" optional="" />
    <!--下面的元素可以出现0次,也可以出现无限多次 -->
    <include file="" />
    <!--package元素是struts配置文件的核心,该元素可以出现0次,或者是无限多次 -->
    <package name="必填的包名" extends="" namespace="" abstract="" externalReferenceResovler>
        <!--以下该元素可以出现,也可以不出现,最多出现一次 -->
        <result-types>
            <!--以下该元素必须出现,可以出现无数多次 -->
            <result-type name="" class="" default="true\false">
                <!--下面的元素可以出现0次,也可以出现无限多次 -->
                <param name="参数名">参数值 </param>
            </result-type>
        </result-types>
        <!--以下的该元素可以出现,也可以不出现,但最多出现1次 -->
        <interceptors>
            <!--interceptors元素的子元素interceptor元素和interceptor-stack至少出现其中之一,也可以两者都出现 -->
            <!--下面的元素可以出现0次,也可以出现无限多次 -->
            <interceptor name="" class="">
                <!--下面的元素可以出现0次,也可以出现无限多次 -->
                <param name="参数名">参数值 </param>
            </interceptor>
            <!--下面的元素可以出现0次,也可以出现无限多次 -->
            <interceptor-stack name="">
                <!-- 下面的元素必须出现,可以出现无数多次 -->
                <interceptor-ref name="">
                    <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
                    <param name="参数名">参数值</param>
                </interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
        <default-interceptor-ref name="">
            <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
            <param name="参数名">参数值</param>
        </default-interceptor-ref>
        <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
        <default-action-ref name="">
            <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
            <param name="参数名">参数值</param>
        </default-action-ref>
        <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
        <global-results>
            <!-- 该元素必须出现,可以出现无限多次 -->
            <result name="" type="">
                <!-- 该字符串内容可以出现0次或者多次 -->
                映射资源
                <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
                <param name="参数名">参数值</param>
            </result>
        </global-results>
        <!-- 下面的元素可以出现0次,也可以出现多次 -->
        <global-exception-mappings>
            <!-- 该元素必须出现,可以出现多次 -->
            <exception-mapping name="" exception="" result="">
                异常处理资源
                <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
                <param name="参数名">参数值</param>
            </exception-mapping>
        </global-exception-mappings>
        <action name="" class="" method="" convertor="">
            <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
            <param name="参数名">参数值</param>
            <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
            <result name="" type="">
                映射资源
                <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
                <param name="参数名">参数值</param>
            </result>
            <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
            <interceptor-ref name="">
                <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
                <param name="参数名">参数值</param>
            </interceptor-ref>
            <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
            <exception-mapping name="" exception="" result="">
                异常处理资源
                <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
                <param name="参数名">参数值</param>
            </exception-mapping>
        </action>
    </package>
</struts>

4-2 包含其他配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
  <!-- 通过 include 元素导入其他配置文件 -->
  <include file="struts-part1.xml" />
</struts>

5 实现 Action

5-1 Action 接口 和 ActionSupport 基类

public interface Action {

    //定义Action接口里包含的一些结果字符串
    public static final String ERROR = "error";
    public static final String INPUT = "input";
    public static final String LOGIN = "login";
    public static final String NONE = "none";
    public static final String SUCCESS = "success";

    //定义处理用户请求的execute()方法
    public String execute() throws Exception;
}

ActionSupport是一个默认的Action实现类,该类里已经提供了许多默认方法,这些方法包括获取国际化信息的方法、数据校验的方法、默认的处理用户请求的方法等,实际上,ActionSupport是Struts2的默认的Action处理类,如果让开发者的Action类继承该ActionSupport类,则会大大简化Action的开发。

package com.opensymphony.xwork2;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
* Provides a default implementation for the most common actions.
* See the documentation for all the interfaces this class implements for more detailed information.
*/
public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {
protected static Logger LOG = LoggerFactory.getLogger(ActionSupport.class);
private final ValidationAwareSupport validationAware = new ValidationAwareSupport();
private transient TextProvider textProvider;
private Container container;

public void setActionErrors(Collection<String> errorMessages) {
   validationAware.setActionErrors(errorMessages);
}
public Collection<String> getActionErrors() {
   return validationAware.getActionErrors();
}
public void setActionMessages(Collection<String> messages) {
   validationAware.setActionMessages(messages);
}
public Collection<String> getActionMessages() {
   return validationAware.getActionMessages();
}
/**
* @deprecated Use {@link #getActionErrors()}.
*/
@Deprecated
public Collection<String> getErrorMessages() {
   return getActionErrors();
}
/**
* @deprecated Use {@link #getFieldErrors()}.
*/
@Deprecated
public Map<String, List<String>> getErrors() {
   return getFieldErrors();
}
//设置表单域校验错误信息
public void setFieldErrors(Map<String, List<String>> errorMap) {
   validationAware.setFieldErrors(errorMap);
}
//返回表单域错误校验信息
public Map<String, List<String>> getFieldErrors() {
   return validationAware.getFieldErrors();
}
//控制locale的相关信息
public Locale getLocale() {
   ActionContext ctx = ActionContext.getContext();
   if (ctx != null) {
      return ctx.getLocale();
   } else {
      LOG.debug("Action context not initialized");
   return null;
   }
}
public boolean hasKey(String key) {
   return getTextProvider().hasKey(key);
}
public String getText(String aTextName) {
   return getTextProvider().getText(aTextName);
}
//返回国际化信息的方法
public String getText(String aTextName, String defaultValue) {
   return getTextProvider().getText(aTextName, defaultValue);
}
public String getText(String aTextName, String defaultValue, String obj) {
   return getTextProvider().getText(aTextName, defaultValue, obj);
}
public String getText(String aTextName, List<Object> args) {
   return getTextProvider().getText(aTextName, args);
}
public String getText(String key, String[] args) {
   return getTextProvider().getText(key, args);
}
public String getText(String aTextName, String defaultValue, List<Object> args) {
   return getTextProvider().getText(aTextName, defaultValue, args);
}
public String getText(String key, String defaultValue, String[] args) {
   return getTextProvider().getText(key, defaultValue, args);
}
public String getText(String key, String defaultValue, List<Object> args, ValueStack stack) {
   return getTextProvider().getText(key, defaultValue, args, stack);
}
public String getText(String key, String defaultValue, String[] args, ValueStack stack) {
   return getTextProvider().getText(key, defaultValue, args, stack);
}
//用于访问国际化资源包的方法
public ResourceBundle getTexts() {
   return getTextProvider().getTexts();
}
public ResourceBundle getTexts(String aBundleName) {
   return getTextProvider().getTexts(aBundleName);
}
//添加错误信息
public void addActionError(String anErrorMessage) {
   validationAware.addActionError(anErrorMessage);
}
public void addActionMessage(String aMessage) {
   validationAware.addActionMessage(aMessage);
}
添加字段校验的错误信息
public void addFieldError(String fieldName, String errorMessage) {
   validationAware.addFieldError(fieldName, errorMessage);
}
//默认Input方法,直接访问input字符串
public String input() throws Exception {
   return INPUT;
}
public String doDefault() throws Exception {
   return SUCCESS;
}
/**
* A default implementation that does nothing an returns "success".
* <p/>
* Subclasses should override this method to provide their business logic.
* <p/>
* See also {@link com.opensymphony.xwork2.Action#execute()}.
*
* @return returns {@link #SUCCESS}
* @throws Exception can be thrown by subclasses.
*/
//默认处理用户请求的方法,直接返回SUCCESS字符串
public String execute() throws Exception {
   return SUCCESS;
}
public boolean hasActionErrors() {
   return validationAware.hasActionErrors();
}
public boolean hasActionMessages() {
   return validationAware.hasActionMessages();
}
public boolean hasErrors() {
   return validationAware.hasErrors();
}
public boolean hasFieldErrors() {
   return validationAware.hasFieldErrors();
}
/**
* Clears field errors. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
*/
public void clearFieldErrors() {
   validationAware.clearFieldErrors();
}
/**
* Clears action errors. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
*/
public void clearActionErrors() {
   validationAware.clearActionErrors();
}
/**
* Clears messages. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
*/
public void clearMessages() {
   validationAware.clearMessages();
}
/**
* Clears all errors. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
*/
public void clearErrors() {
   validationAware.clearErrors();
}
/**
* Clears all errors and messages. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
*/
//清理错误信息的方法
public void clearErrorsAndMessages() {
   validationAware.clearErrorsAndMessages();
}
/**
* A default implementation that validates nothing.
* Subclasses should override this method to provide validations.
*/
//包含空校验的方法
public void validate() {
}
@Override
public Object clone() throws CloneNotSupportedException {
   return super.clone();
}
/**
* <!-- START SNIPPET: pause-method -->
* Stops the action invocation immediately (by throwing a PauseException) and causes the action invocation to return
* the specified result, such as {@link #SUCCESS}, {@link #INPUT}, etc.
* <p/>
* <p/>
* The next time this action is invoked (and using the same continuation ID), the method will resume immediately
* after where this method was called, with the entire call stack in the execute method restored.
* <p/>
* <p/>
* Note: this method can <b>only</b> be called within the {@link #execute()} method.
* <!-- END SNIPPET: pause-method -->
*
* @param result the result to return - the same type of return value in the {@link #execute()} method.
*/
public void pause(String result) {
}
/**
* If called first time it will create {@link com.opensymphony.xwork2.TextProviderFactory},
* inject dependency (if {@link com.opensymphony.xwork2.inject.Container} is accesible) into in,
* then will create new {@link com.opensymphony.xwork2.TextProvider} and store it in a field
* for future references and at the returns reference to that field
*
* @return reference to field with TextProvider
*/
private TextProvider getTextProvider() {
if (textProvider == null) {
   TextProviderFactory tpf = new TextProviderFactory();
    if (container != null) {
      container.inject(tpf);
    }
   textProvider = tpf.createInstance(getClass(), this);
  }
return textProvider;
}
@Inject
public void setContainer(Container container) {
  this.container = container;
 }
}

5-2 Action 访问 Servlet API (一般推荐使用,IOC方式,只能获得request,而response则得不到)

Struts2框架提供了一种更轻松的方式来访问Servlet API。在web应用中通常要访问Servlet API的就是HttpServletRequest、HttpSession和ServletContext,这三个类别分别代表JSP内置对象中的request、session和application。

Struts2提供了一个ActionContext类,Struts2的Action通常可以通过该类来访问Servlet API。下面是ActionContext类中包含的几个常用方法:
(1)Object get(Object key): 该方法类似于调用 HttpServletRequest 的getAttribute(String name) 方法。
(2)Map getApplication():返回一个Map对象,该对象模拟了该应用的 ServletContext实例。
(3)static ActionContext getContext():静态方法,获取系统的 ActionContext 实例。
(4)Map getparameters():获取所有的请求参数,类似于调用 HttpServletRequest 对象的 getParameterMap() 方法。
(5)Map getSession():返回一个 Map 对象,该对象模拟一个 HttpSession 实例。
(6)void setApplication(Map application):直接传入一个Map 实例,该 Map 实例里面的 key-value 对转换成 application 的属性名、属性值。
(7)void setSession(Map session):直接传入一个 Map 实例,该Map实例里面的 key-value 对转换成 session 的属性名、属性值。

5-3 Action 直接访问 Servlet API (不推荐,麻烦,非IOC方式,与Servlet API耦合大)

虽然Struts2提供了ActionContext来访问Servlet API,但这种访问不能直接获得Servlet API,为了在Action中直接访问Servlet API,Struts2还提供了以下接口。

  1. ServletContextAware:实现该接口的Action可以直接访问Web应用的ServletContext实例;
  2. ServletRequestAware:实现该接口的Action可以直接访问用户请求对象的HttpServletRequest的实例;
  3. ServletResponseAware:实现该接口的Action可以直接访问服务器响应的HttpServletResponse的实例;

5-4 使用 ServletActionContext 访问 Servlet API (非IOC方式,强烈推荐使用)

Struts2还提供了一个ServletActionContext,其静态方法有:getPageContext()、getRequest() 、getResponse()、getServletContext()。
1. HttpServletRequest request=ServletActionContext.getRequest();
2. HttpServletResponse response=ServletActionContext.getResponse();
3. request.getSession().setAttribute(“username”,”admin”);
4. request.setAttribute(“password”,”123456”);

6 配置 Action

6-1 包和命名空间

Struts2使用包来组织Action,Struts2框架中的核心组件就是Action和拦截器,Struts2框架使用包来管理Action和拦截器等,每个包就是多个Action、多个拦截器、多个拦截器引用的集合。

在struts.xml文件中,package 元素用于定义包配置,每个package元素定义一个包配置,定义package时可以指定如下几个属性:
1. name: 这是一个必须的属性,该属性指定该包的名字,该名字是该包被其他包引用的key。
2. extends: 该属性是一个可选属性,该属性指定该报继承其他包。继承其他包,就可以继承其他包中的 Action 定义、拦截器定义等。
3. namespace: 该属性是一个可选属性,该属性定义该包的命名空间。
4. abstract: 该属性是一个可选属性,他指定该包是否是一个抽象包,在抽象包中不能有package属性。
因为Struts2的配置文件时从上到下进行处理,所以父包应该在子包的前面定义。

下面是一个简单的struts.xml文件配置文件范例。在下面的struts.xml文件中配置两个包,其中名为default的包,继承了Struts2框架的默认包:struts-default。

<?xml version = "1.0" encoding = "UTF-8"?>
    <!--下面是Struts2配置文件的DTD信息 -->  
<!DOCTYPE struts PUBLIC  
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    <!--struts是struts2配置文件的跟元素 -->
<struts>
    <!--配置第一个包,该包名为default,继承了struts-default-->
    <!--package元素是struts配置文件的核心,该元素可以出现0次,或者是无限多次 -->
    <package name="default" extends="struts-default">
        <!--下面定义了拦截器部分-->
        <!--以下的该元素可以出现,也可以不出现,但最多出现1次 -->
        <interceptors>
            <!--定义拦截器栈-->
            <!--下面的元素可以出现0次,也可以出现无限多次 -->
            <interceptor-stack name="crudeStack">
                <!-- 下面的元素必须出现,可以出现无数多次 -->
                <interceptor-ref name="params" />
                <interceptor-ref name="defaultStack" />
            </interceptor-stack>
        </interceptors>
        <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
        <default-action-ref name="showcase" />
        <!--定义一个Action,该Action直接映射到showcase.jsp页面-->
        <action name="showcase" class="" method="" convertor="">
            <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
            <param name="参数名">参数值</param>
            <!-- 下面的元素可以出现0次,也可以出现无限多次 -->
            <result>showcase.jsp</result>
        </action>
        <!--定义一个Action,该Action类为lee.DateAction-->
        <action name="Date" class="lee.DateAction">
            <result name="success">/date.jsp</result>
        </action>
    </package>

    <!--定义一个名为skill的包,该包直接继承default的包-->
    <package name="skill" extends="default" namespace="/skill">
        <!--定义默认的拦截器引用-->
        <default-interceptor-ref name="crudeStack" />
        <!--定义一个名为Edit的Action,该Action对应的处理类是lee.SkillAction-->
        <action name="edit" class="lee.SkillAction">
            <result>/empmanager/editskill.jsp</result>
            <interceptor-ref name="params" />
            <interceptor-ref name="basicStack" />
        </action>
        <!--定义一个名为Save的Action ,该Action对应的处理类lee.SkillAction,使用skill方法作为处理方法-->
        <action name="Save" class="lee.SkillAction">
            <result name="input">/empmanager/editSkill.jsp</result>
            <result name="redirect">edit.action?skillName=${currentSkill.name}
            </result>
        </action>
    </package>
</struts>  

6-2 Action 的基本配置

6-3 使用 Action 的动态方法 DMI(Dynamic Method Invocation)调用

可以在url地址中动态指定action执行那个方法。Url地址如下:

http://localhost:8080/Struts2_0500_ActionMethod/user/user!add

方法:action + ! + 方法名
注:只要Action对象中有这个方法,并且返回类型为String就可以调用。
这样Struts.xml配置文件中不需要配置methed属性。代码如下:

<action name="user" class="com.bjsxt.struts2.user.action.UserAction">
       <result>/user_add_success.jsp</result>
</action>

Action类:

public class UserAction extends ActionSupport {
    public String add() {
       return SUCCESS;
    }  
}

使用动态方法调用前必须设置 Struts2允许动态方法调用,设置
struts.enable.DynamicMethodInvocation 的常量值为 true 。

6-4 指定 method 属性及使用通配符

当我们配置 Action 时,实际上可以认为需要配置三个属性:
name 属性指定该 Action 处理怎样的请求,该属性不可省略;
class 属性指定该 Action 的处理类,默认使用 ActionSupport 作为处理类;
method 属性指定使用哪个方法处理请求,默认使用 execute 方法处理请求。

6-5 配置默认 Action

<package name="onepackage" extends="struts-default">

<!--指定默认的Action引用,如果该包下没有对应Action配置,则启用该配置-->
<default-action-ref name="helloWorldAction"></default-action-ref>
<!--下面是正常的Action-->
<action name="helloWorldAction" class="com.struts.hello.HelloWord">
<result name="su">show.jsp</result>
</action>
</package>

6-6 配置 Action 的默认处理类

<package name="" abstract="true">
    <!-- 配置 Action 的默认处理类 -->
    <default-class-ref class="com.opensymphony.xwork2.ActionSupport" />
</package>

7 配置处理结果

8 配置 Struts2 的异常处理

9 Convention 插件与“约定”支持

10 使用 Struts2 的国际化

11 使用 Struts2 的标签库

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值