Stuts2学习笔记(1):环境搭建及Demo

版权声明:欢迎转载,请注明原文地址:http://blog.csdn.net/c1481118216 https://blog.csdn.net/c1481118216/article/details/79504323

源码:

github: https://github.com/liaotuo/Struts2-Demo/tree/master/struts2-demo

环境搭建

下载struts2

官网下载:http://mirror.bit.edu.cn/apache/struts/2.3.34/struts-2.3.34-all.zip

注:本教程使用2.3.34版本

目录结构

这里写图片描述

所需基本jar包

解压apps下一个demo能够得到所需的基本jar包
这里写图片描述

创建web项目

创建一个web项目,并将所需jar包放入WEB-INFO/lib下面(web项目无需build-path)如下图:
这里写图片描述

编写Struts.xml配置文件

可以直接从struts-blank demo中Copy一个struts.xml 并删掉其中的配置,如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

</struts>

在web.xml中注册Struts2启动配置

往web.xml中加入如下配置

<filter>
    <filter-name>struts2</filter-name>
    <!-- 这个类全名不同版本不完全一样 可以从struts-core.jar 中找-->
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

至此环境搭建完毕,接下来创建一个demo


Demo

创建我的第一个action

package com.lt.action;

public class HelloAction {
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    /***
     * 默认的action执行方法为excute
     * @return 
     */
    public String excute() {
        this.setMsg("hello struts2...");
        return "success";
    }

    /***
     * 动态方法调用demo
     * @return
     */
    public String dynamic() {
        this.setMsg("hello struts2-dynamicMethod...");
        return "success";
    }
}

在struts.xml中注册Action

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <!-- 常量名可以从struts-core包下org.apache.struts2 下default.properties下查看 -->
    <!-- 配置启用动态方法调用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
    <!-- 需要继承自struts-default 执行默认的拦截器 -->
    <package name="basePakage" namespace="/" extends="struts-default">
        <!-- 配置action 默认method是excute可以不配置 -->
        <action name="helloAction" class="com.lt.action.HelloAction" method="execute">
             <result name="success">index.jsp</result>
        </action>
    </package>
</struts>

测试成功

注:访问路径需注意

这里写图片描述

deault-value

  • 未指定action 默认执行的Class是ActionSupport
  • 默认执行action中的execute() 方法
  • 没有指定result的name属性,默认值为success

动态方法调用的方式

开启常量

<!-- 配置启用动态方法调用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

这里写图片描述

通配符配置

修改action配置

<action name="helloAction_*" class="com.lt.action.HelloAction" method="{1}">
     <result name="success">index.jsp</result>
</action>

这里写图片描述

猜你喜欢

转载自blog.csdn.net/c1481118216/article/details/79504323
今日推荐