Struts2的安装

安装Struts 2 ,并开发一个简单 Model

1、下载Struts 2

  在Struts 2 官网下载:http://struts.apache.org ,下载 struts-2.3.16.3-all.zip 。

2、添加Struts 2 .jar文件

  将 struts-2.3.16.3-all.zip 中 lib 目录下的所有不以struts 2*命名开头的.jar包、struts 2-core-2.3.16.jar 复制到项目:WebContent/WEB-INF/lib 目录下。

(其实只要导入基本包就行:

  struts2-core-2.0.11.jar、 xwork-2.0.4.jar、 ognl-2.6.11.jar、 jstl.jar、 freemarker-2.3.8.jar、commons-logging-1.0.4.jar 

;可以导入以下包:

3、添加Struts 2 配置文件

  下载默认配置文件,将以下文件复制到 src 目录下:

    struts.properties

    struts.xml

    commons-logging.properties

    log4j.properties

    simplelog.properties

  修改 struts.properties 文件 struts.action.extension=action 为  struts.action.extension=do (为了让Struts 2 接收 *.do 形式的请求)

4、添加Struts 2 过滤器( web.xml 文件)

  配置 web.xml 文件,添加以下代码:

        <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>   

5、编写输入表单页面.jsp 文件

  如以下代码:

<form action="test.do" method="post">
    <input type="text" name="str1">
    <input type="text" name="str2">
    <input type="submit">
</form>

6、配置 struts.xml 

  如添加以下代码:

    <package name="main" extends="struts-default">
        <action name="test" class="com.demo.struts2.actions.TestAction">
            <result name="success">success.jsp</result>
            <result name="input">index.jsp</result>
        </action>
    </package>    

7、编写处理器类 TestAction.java

package com.demo.struts2.actions;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class TestAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    
    private String str1;
    private String str2;
    
    public String execute() throws Exception {
        
        if (!str1.equals("") && !str2.equals("")) {
            ActionContext.getContext().getSession().put("str1", str1);
            ActionContext.getContext().getSession().put("str2", str2);
            return Action.SUCCESS;
        } else {
            //super.addActionError(super.getText("login.message.failed"));
            return Action.INPUT;
        }
        
    }

    public String getStr1() {
        return str1;
    }

    public void setStr1(String str1) {
        this.str1 = str1;
    }

    public String getStr2() {
        return str2;
    }

    public void setStr2(String str2) {
        this.str2 = str2;
    }
}

8、编写返回页面 

  如以下内容:

<table width="300" border="1">
    <tr>
        <td>str1=<%=(String) session.getAttribute("str1")%></td>
    </tr>
    <tr>
        <td>str2=<%=(String) session.getAttribute("str2")%></td>
    </tr>
    <tr>
        <td><a href="index.jsp">[Back]</a></td>
    </tr>
</table>

最后完成简单的Struts 2 框架模型,可以在此基础上添加功能。

  

原文地址:https://www.cnblogs.com/blueherb/p/3949289.html