struts2入门(一)——Struts配置

struts2是基于webwork2(80%)和struts1(20%)生成

优点:

1.无需于servlet api整合,更容易测试
2.优雅的请求封装
3.灵活的视图技术
4.丰富的表达式语言 ognl el jstl
5.机动 灵活 简单的配置
6.线程安全的控制器action
7.霸气的插件


整个请求过程:

图片标题
当用户发送一个请求,传入后台,首先经过核心过滤器,核心控制器调用动作映射类判断是否需要调用action,如需调用则返回确认信息并创建动作映射类,动作映射类通过配置管理查看struts.xml确认调用那个action,确认后返回信息后通过拦截器,再执行目标action并返回结果,再执行一系列拦截器。


开发过程:

1.导入struts2基本包
图片标题
2.web.xml 配置,在这里添加struts2的核心过滤器,将所有请求转向struts.xml
图片标题
这里特别需要注意,如缺少struts.dtd就会发生错误,可以在下载的struts2包中示例项目文件中复制。此文件是struts的配置文件
图片标题
3.struts.xml配置
此配置文件需要自行创建,也可以通过示例项目复制到src目录下这里写代码片。
图片标题
只需要编辑红框部分:例如
一个登录action的name为login,注意此name需要与jsp页面中的action一致,class对应的是他的处理类,result是返回的结果,当为success时跳转至show.jsp。
struts.xml:

     <action name="login" class="com.it.struts.action.PersonAction">
      <result name="success">show.jsp</result>
      <result name="error">login.jsp</result>
      </action>

使用struts做一个简单的登录demo,struts.xml已给出
login.jsp

  <form action="login" method="post">
    <table>
       <tr>
       <td>用户名</td>
       <td><input type="text" name="pname"/> </td>
       </tr>
       <tr>
       <td>密码</td>
       <td><input type="password" name="pwd"></td>
       </tr>
       <tr>
       <td colspan="2">
       <input type="submit" value="提交"/>
       <input type="reset"/>
       </td>
       </tr>
    </table>
    </form>

PersonAction.java

 package com.it.struts.action;
    import com.opensymphony.xwork2.ActionSupport;
    public class PersonAction extends ActionSupport{
    private String pname;
     private String pwd;
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
     public String execute() {
         if("abc".equals(pname)&&"123".equals(pwd)) {
            return "success"; 
         }
         else {
             return "error";
         } 
     }
    }

show.jsp

 <body>
    hello:${pname}

    </body>

这里PersonAction继承了ActionSupport,他是一个工具类并且实现了Action接口,还有数据验证功能,一般在读取国际化信息,处理验证错误,处理类型转错误时使用。


此外Action接口:定义了5个常量,一个方法

 public interface Action {
        public static final String SUCCESS = "success";
        public static final String NONE = "none";
        public static final String ERROR = "error";
        public static final String INPUT = "input";
        public static final String LOGIN = "login";
        public String execute() throws Exception;
    }

struts2接收页面传值的方式有三种:

1、值模型:直接在action中写属性
2、域模型:将实体对象实例化,并进行set、get方法
3、模型驱动:实现ModelDriven(T) 这里的T即为实体类,再实现getModel()方法
例如:

  public class PersonAction1 extends ActionSupport implements ModelDriven<person>{

     person person = new person();

    @Override
    public person getModel() {
        // TODO Auto-generated method stub
        return person;
    }
}

猜你喜欢

转载自blog.csdn.net/hqh1129/article/details/81180494