struts2 进阶 深入Struts2的配置文件(一)_SambaGao的博客-程序员秘密

技术标签: exception  string  struts  servlet  action  login  

1.1.    包配置:
Struts2框架中核心组件就是Action、拦截器等,Struts2框架使用包来管理Action和拦截器等。每个包就是多个Action、多个拦截器、多个拦截器引用的集合。
在struts.xml文件中package元素用于定义包配置,每个package元素定义了一个包配置。它的常用属性有:
l name:必填属性,用来指定包的名字。
l extends:可选属性,用来指定该包继承其他包。继承其它包,可以继承其它包中的Action定义、拦截器定义等。
l namespace:可选属性,用来指定该包的命名空间。
<! DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd" >
< struts >
    <!-- struts2 action 必须放在一个指定的包空间下定义 -->
    < package name = "default" extends = "struts-default" >
    <!-- 定义处理请求 URL login.action Action -->
        < action name = "login" class = "org.qiujy.web.struts.action.LoginAction" >
        <!-- 定义处理结果字符串和资源之间的映射关系 -->
            < result name = "success" > /success.jsp </ result >
            < result name = "error" > /error.jsp </ result >
        </ action >
    </ package >
</ struts >
如上示例的配置,配置了一个名为default的包,该包下定义了一个Action。
1.2.    命名空间配置:
考虑到同一个Web应用中需要同名的Action,Struts2以命名空间的方式来管理Action,同一个命名空间不能有同名的Action。
Struts2通过为包指定namespace属性来为包下面的所有Action指定共同的命名空间。
把上示例的配置改为如下形式:
<! DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd" >
< struts >
    <!-- struts2 action 必须放在一个指定的包空间下定义 -->
    < package name = "qiujy" extends = "struts-default" >
    <!-- 定义处理请求 URL login.action Action -->
        < action name = "login" class = "org.qiujy.web.struts2.action.LoginAction" >
        <!-- 定义处理结果字符串和资源之间的映射关系 -->
            < result name = "success" > /success.jsp </ result >
            < result name = "error" > /error.jsp </ result >
        </ action >
    </ package >
   
    < package name = "my" extends = "struts-default" namespace = "/manage" >
    <!-- 定义处理请求 URL login.action Action -->
        < action name = "backLogin" class = "org.qiujy.web.struts2.action.LoginAction" >
        <!-- 定义处理结果字符串和资源之间的映射关系 -->
            < result name = "success" > /success.jsp </ result >
            < result name = "error" > /error.jsp </ result >
        </ action >
    </ package > </ struts >
如上配置了两个包:default和my,配置my包时指定了该包的命名空间为/manage。
对于包default:没有指定namespace属性。如果某个包没有指定namespace属性,即该包使用默认的命名空间,默认的命名空间总是""。
对于包my:指定了命名空间/manage,则该包下所有的Action处理的URL应该是“命名空间/Action名”。如上名为 backLogin的Action,它处理的URL为:
http://localhost:8080/userlogin_struts2 /manage/backLogin.action
Struts2的命名空间的作用等同于struts1里模块的作用。
1.3.    包含配置:
在Struts2中可以将一个配置文件分解成多个配置文件,那么我们必须在struts.xml中包含其他配置文件。
< struts >
    < include file = "struts-default.xml" />
    < include file = "struts-user.xml" />
    < include file = "struts-book.xml" />
    < include file = "struts-shoppingCart.xml" />
   
    ......
   </ struts >
1.4.    拦截器配置:
见后面章节介绍。
1.5.    常量配置:
Struts2框架有两个核心配置文件,其中struts.xml文件主要负责管理应用中的Action映射, 及Action处理结果和物理资源之间的映射关系。除此之外,Struts2框架还包含了一个struts.properties文件,该文件主义了Struts2框架的大量常量属性。但通常推荐也是在struts.xml文件中来配置这些常量属性。
如:后面会讲到Struts2的国际化,它的资源文件位置就用常量属性来指定:
< struts >
    ......
    < constant name = "struts.custom.i18n.resources" value = "messages" />
</ struts >
表示指定了资源文件的放置在classes目录下,基本名是messages,则在classes目录下您就应该放置类似messages_zh_CN.properties,message_en.properties名的文件。
2.    Struts2的Action
2.1.    实现Action类:
Struts2中Action是核心内容,它包含了对用户请求的处理逻辑,我们也称Action为业务控制器。
Struts2中的Action采用了低侵入式的设计,Struts2不要求Action类继承任何的Struts2的基类或实现Struts2接口。(但是,我们为了方便实现Action,大多数情况下都会继承com.opensymphony.xwork2.ActionSupport类,并重写此类里的public String execute() throws Exception方法。因为此类中实现了很多的实用接口,提供了很多默认方法,这些默认方法包括获取国际化信息的方法、数据校验的方法、默认的处理用户请求的方法等,这样可以大大的简化Action的开发。)
Struts2中通常直接使用Action来封装HTTP请求参数,因此,Action类里还应该包含与请求参数对应的属性,并且为属性提供对应的getter和setter方法。(当然,Action类中还可以封装处理结果,把处理结果信息当作一属性,提供对应的getter和setter方法)
修改第一部分的用户登录示例:把Action改成如下:
package org.qiujy.web.struts2.action;
 
import com.opensymphony.xwork2.ActionSupport;
 
/**
  * @author qiujy
  * @version 1.0
  */
public class LoginAction extends ActionSupport {
    private String userName ;
    private String password ;
   
    private String msg ; // 结果信息属性
   
    /**
      * @return the msg
      */
    public String getMsg() {
        return msg ;
    }
    /**
      * @param msg the msg to set
      */
    public void setMsg(String msg) {
        this . msg = msg;
    }
    /**
      * @return the userName
      */
    public String getUserName() {
        return userName ;
    }
    /**
      * @param userName the userName to set
      */
    public void setUserName(String userName) {
        this . userName = userName;
    }
    /**
      * @return the password
      */
    public String getPassword() {
        return password ;
    }
    /**
      * @param password the password to set
      */
    public void setPassword(String password) {
        this . password = password;
    }
   
    /**
      * 处理用户请求的 excute() 方法
      * @return 结果导航字符串
      * @throws Exception
      */
    public String execute() throws Exception{
       if ( "test" .equals( this . userName ) &&
"test" .equals( this . password )){
           msg = " 登录成功,欢迎 " + this . userName ;
           return this . SUCCESS ;
       } else {
           msg = " 登录失败,用户名或密码错 " ;
           return this . ERROR ;
       }
    }
}
往success.jsp和error.jsp页面中添加  EL表达式来显示结果信息。则最终效果跟以前一样。
2.2.    Action访问Servlet API
Struts2中的Action并没有和任何Servlet API耦合,这样框架更具灵活性,更易测试。
但是,对于web应用的控制器而言,不访问Servlet API几乎是不可能的,例如跟踪HTTP Session状态等。Struts2框架提供了一种更轻松的方式来访问Servlet API。Struts2中提供了一个ActionContext类(当前Action的上下文对象),通过这个类可以访问Servlet API。下面是该类中提供的几个常用方法:
l public static ActionContext getContext() :获得当前Action的ActionContext实例。
l public Object get(Object key) :此方法类似于调用HttpServletRequest的getAttribute(String name)方法。
l public void put(Object key, Object value) :此方法类似于调用HttpServletRequest 的setAttribute(String name, Object o)。
l public Map getParameters() :获取所有的请求参数。类似于调用HttpServletRequest对象的getParameterMap() 方法。
l public Map getSession() :返回一个Map对象,该Map对象模拟了HttpSession实例。
l public void setSession(Map session) : 直接传入一个Map实例,将该Map实例里的key-value对转换成session的属性名-属性值对。
l public Map getApplication() :返回一个Map对象,该对象模拟了该应用的ServletContext实例。
l public void setApplication(Map application) :直接传入一个Map实例,将该Map实例里的key-value对转换成application的属性名-属性值对。
修改以上用户登录验证示例的Action类中的execute方法:
public String execute() throws Exception{
        if ( "test" .equals( this . userName ) && "test" .equals( this . password )){
            msg = " 登录成功,欢迎 " + this . userName ;
            // 获取 ActionContext 实例,通过它来访问 Servlet API
            ActionContext context = ActionContext.getContext();
            // session 中是否已经存放了用户名,如果存放了:说明已经登录了;
// 否则说明是第一次登录成功
            if ( null != context.getSession().get( "uName" )){
                msg = this . userName + " :你已经登录过了 !!!" ;
            } else {
                context.getSession().put( "uName" , this . userName );
            }
           
            return this . SUCCESS ;
        } else {
            msg = " 登录失败,用户名或密码错 " ;
            return this . ERROR ;
        }
    }
       Struts2中通过ActionContext来访问Servlet API,让Action彻底从Servlet API 中分离出来,最大的好处就是可以脱离Web容器测试Action。
       另外,Struts2中还提供了一个ServletActionContext类,Action只要继承自该类,就可以直接访问Servlet API。具体方法参看struts2的API文档。
3.    一个Action内包含多个请求处理方法的处理
Struts1提供了DispatchAction,从而允许一个Action内包含多个请求处理方法。Struts2也提供了类似的功能。处理方式主要有以下三种方式:
3.1.    动态方法调用:
DMI:Dynamic Method Invocation 动态方法调用。
动态方法调用是指:表单元素的action不直接等于某个Action的名字,而是以如下形式来指定对应的动作名:
<form method="post" action="userOpt!login.action">
则用户的请求将提交到名为”userOpt”的Action实例,Action实例将调用名为”login”方法来处理请求。同时login方法的签名也是跟execute()一样,即为public String login() throws Exception。
注意:要使用动态方法调用,必须设置Struts2允许动态方法调用,通过设置struts.enable.DynamicMethodInvocation常量来完成,该常量属性的默认值是true。
3.1.1.      示例:
修改用户登录验证示例,多增加一个注册用户功能。
1.        修改Action类:
package org.qiujy.web.struts2.action;
 
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
 
/**
  * @author qiujy
  * @version 1.0
  */
public class LoginAction extends ActionSupport{
    private String userName ;
    private String password ;
   
    private String msg ; // 结果信息属性
   
    /**
      * @return the msg
      */
    public String getMsg() {
        return msg ;
    }
    /**
      * @param msg the msg to set
      */
    public void setMsg(String msg) {
        this . msg = msg;
    }
    /**
      * @return the userName
      */
    public String getUserName() {
        return userName ;
    }
    /**
      * @param userName the userName to set
      */
    public void setUserName(String userName) {
        this . userName = userName;
    }
    /**
      * @return the password
      */
    public String getPassword() {
        return password ;
    }
    /**
      * @param password the password to set
      */
    public void setPassword(String password) {
        this . password = password;
    }
   
    /**
      * 处理用户请求的 login() 方法
      * @return 结果导航字符串
      * @throws Exception
      */
    public String login() throws Exception{
        if ( "test" .equals( this . userName ) && "test" .equals( this . password )){
            msg = " 登录成功,欢迎 " + this . userName ;
            // 获取 ActionContext 实例,通过它来访问 Servlet API
            ActionContext context = ActionContext.getContext();
            // session 中是否已经存放了用户名,如果存放了:说明已经登录了;
// 否则说明是第一次登录成功
            if ( null != context.getSession().get( "uName" )){
                msg = this . userName + " :你已经登录过了 !!!" ;
            } else {
                context.getSession().put( "uName" , this . userName );
            }
           
            return this . SUCCESS ;
        } else {
            msg = " 登录失败,用户名或密码错 " ;
            return this . ERROR ;
        }
    }
   
    public String regist() throws Exception{
        // 将用户名,密码添加到数据库中
        //...
        msg = " 注册成功。 " ;
        return this . SUCCESS ;
    }
}
 
2.        struts.xml文件:没有什么变化,跟以前一样配置
<! DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd" >
< struts >
    < package name = "my" extends = "struts-default" namespace = "/manage" >
    <!-- 定义处理请求 URL login.action Action -->
        < action name = "userOpt" class = "org.qiujy.web.struts2.action.LoginAction" >
        <!-- 定义处理结果字符串和资源之间的映射关系 -->
            < result name = "success" > /success.jsp </ result >
            < result name = "error" > /error.jsp </ result >
        </ action >
    </ package >
</ struts >
3.        页面:
index.jsp
<%@ page language = "java" pageEncoding = "UTF-8" %>
< html >
  < head >
    < title > 用户登录页面 </ title >
  </ head >
 
  < body >
   < h2 > 用户入口 </ h2 >
   < hr >
    < form action = "manage/userOpt!login.action" method = "post" >
    < table border = "1" >
         < tr >
             < td > 用户名: </ td >
             < td >< input type = "text" name = "userName" /></ td >
         </ tr >
         < tr >
             < td > 密码: </ td >
             < td >< input type = "password" name = "password" /></ td >
         </ tr >
         < tr >
             < td colspan = "2" >
                 < input type = "submit" value = " 确定 " />
             </ td >
         </ tr >
    </ table >
    </ form >
  </ body >
</ html >
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/nihaozhangchao/article/details/5168418

智能推荐

react生命周期_Melanie_wu的博客-程序员秘密

react生命周期:生命周期函数是自动执行的,具体某个生命周期想干什么,需要我们自己去写react组件的生命周期过程常用生命周期:1.constructor(构造函数)2.getDerive的StateFromPropsstatic getDerivedStateFromProps(props, state)getDerive的StateFromProp会在render方法前调用,并且在初始挂在及后续更新时都会被调用,它应返回一个对象来更新state,如果返回nul..

python基础教程:python实现3D地图可视化_老程序员阿福的博客-程序员秘密

这篇文章主要为大家详细介绍了python实现3D地图可视化,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下基于python代码的3D地图可视化,供大家参考,具体内容如下介绍使用Python对地图进行3D可视化。以地图为地图,可以在三维空间对轨迹、点进行可视化。库我们使用了多个库:1.gdal;主要是用于读取地图信息,这个库在GIS中很常用,使用C++代码...

【C语言】输入三位数并逆序输出每一位(个、十、百)的值_c语言编写输入一个三位数输出它的每一位数_九九喵99的博客-程序员秘密

题目输入:一个三位数输出:逆序输出这个三位数,输出个位、十位、百位,三个数字,用空格分开解答#include&lt;stdio.h&gt;int main(){ int num, ge,shi,bai; printf("Please enter a 3-digit number:"); scanf("%d",&amp;num); ge = num%10; shi = num/10%10; bai =

python 同花顺thstrader_GitHub - fswzb/THSTrader: 量化交易。同花顺免费模拟炒股软件客户端的python API。(Python3)..._weixin_39598135的博客-程序员秘密

THSTrader量化交易。同花顺免费模拟炒股软件客户端的python API。(Python3)为什么有这个项目本来看到了这个easytrader这个项目,不过这个客户端已经过时了(被强制更新)。于是乎,自己看了一遍easytrader的源码,写了一个自己的版本。看了 https://github.com/nladuo/THSTrader,觉得美中不足,所以自己从中优化了一个版本,更具有通用性,...

【Spring学习笔记四】-自动装配Bean_Kevin_zhai的博客-程序员秘密

上一次博客写到Spring有两种依赖注入的方式,设值注入和构造注入,详情点击这里:http://blog.csdn.net/kevin_zhai/article/details/52184901。上述两种注入方式的例子,都是通过XML配置文件来装配Bean的。除此之外,Spring提供了一种更加方便的装配Bean的方法,即利用@Autowired注解进行自动装配。一、@Autowired基本使

Could not create pool connection. The DBMS driver exception was: Io 异常: Broken pipe_深圳gg的博客-程序员秘密

现场同事反馈:中间件weblogic连不上数据库Oracle,发回日志可以看到:    Caused by: weblogic.common.ResourceException: weblogic.common.ResourceException: Could not create pool connection. The DBMS driver exception was: Io 异常: B

随便推点

VIP + keepalived 实现 nginx 的主从热备_nginx主从热备_老王头的笔记的博客-程序员秘密

准备工作:使用 virtualBox 安装了2台 centos7 环境的虚拟机。安装步骤完全参考:https://www.jianshu.com/p/18207167b1e7 步骤1安装完成,登录centos7 完全退出虚拟机。重新设置 -&gt; 网络,配置NAT(网卡1)+ Host-Only(网卡2)两种网络模式。NAT网卡保证虚拟机能联网,Host-Only保证虚拟机能和主机联通。(注意:设置网卡2 Host-Only需要在虚拟机完全安装完成后再设置,而不能在安装centos7过程中设置。这

【同步工具类:Phaser】_echo_huangshi的博客-程序员秘密

JUC同步工具类中的一个比较高级的类。本文首先介绍了其特性,然后简单和其他工具类比较。并分析了主要方法的源码。随后用Phaser来实现 CountDownLatch和CyclicBarrier的功能。希望能帮助大家更好的理解Phaser.

Openssl源码安装及升级_源码安装openssl_bestmem的博客-程序员秘密

Openssl源码安装及升级查看openssl当前版本:源码安装openssl-1.1.0升级openssl-1.1.1查看openssl当前版本:[[email protected] ~]# rpm -qa | grep opensslopenssl-libs-1.0.2k-16.el7.x86_64openssl-1.0.2k-16.el7.x86_64openssl-devel-1.0.2k...

云炬Android开发笔记 13购物车,订单,支付功能开发(包含支付宝支付和微信支付)_云炬学长的博客-程序员秘密

阅读目录1.购物车UI编写1.1 购物车布局1.2 recycleView中的item的布局2. 购物车数据结构分析、解析与转化2.1 解析的数据2.2 数据的转化2.3 数据适配器的添加3. 购物车逻辑梳理与实现3.1 是否选中的事件的响应3.2 全选按钮事件的响应3.3 闪屏bug3.4 删除按钮的功能实现3.5 清空购物车3.6 清空购物车之后的额外内容的显示3.7 左右加号减号的功能的实现3.8 结算功能的实现4.订单和支付逻辑梳理和处理4....

python一次性输入多个数_python中一次性输入多个数字并去重排序_weixin_39630095的博客-程序员秘密

先来两个数字举例子:a,b =input('输入a,b空格隔开:').split()#此时a,b为str型a,b =map(int,input('输入a,b空格隔开:').split())#此时a,b为int型输入多个数字写法:nums = list(map(int, input().split()))list1 = [] #定义一个空列表str1 = input("请输入数值,用空格隔开:")l...

EasyExcel填充导出及一些奇怪的问题_easyexcel合计_琉星夜的博客-程序员秘密

用esayExcel做的导出在本地跑无问题,到服务器上就找不到文件。这个问题可以用下面这行代码解决 InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("excel/" + templateName + ".xlsx"); //获取文件 URL url = this.getClass().getClassLoader().getResource("excel/" + templateNam

推荐文章

热门文章

相关标签