Struts2—项目创建

来源:互联网 发布:淘宝买家手机号 编辑:程序博客网 时间:2024/05/05 13:15

步骤

  1. 创建web 项目
  2. 导入jar包,可以从struts2的例子里面拷贝基本的jar包

    jar包

  3. 创建Action类

    //普通的java类,即使约定与Action结尾public class HelloAction {/** * 1. Action类中默认的执行方法,类似Servlet中的service()方法 * 2. 返回值可以与相应页面对应(需配置) * @return */    public String execute(){        return "ok";    }}
  4. 配置

    • 创建struts.xml配置文件

      • 文件名字固定:struts.xml
      • 路径固定:src下
    <?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>    <package name="demo" extends="struts-default" namespace="/">        <!-- name:访问名称 -->        <action name="hello" class="com.jeff.action.HelloAction">            <!-- 配置方法返回到页面 -->        <result name="ok">/hello.jsp</result>               </action>    </package></struts>
    • 在web.xml中配置Struts2的核心过滤器
    <!-- 配置Struts2的过滤器 --><filter>    <filter-name>struts2</filter-name>    <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>
  5. 访问路径

    域名/项目名称/action的路径.action

    • http://localhost:8080/strus2_study/hello.action

执行过程

1.请求URL

- http://localhost:8080/strus2_study/hello.action

2.请求通过过滤器(服务启动时执行),过滤器执行步骤及功能

- Step1:获取请求路径,并获取路径中的hello值- Step2:加载struts.xml配置文件,使用dom4j解析,得到xml文件中各个节点的内容         将hello值匹配action标签中name属性的值,判断是否一致- Step3: 若匹配action标签name属性中的值,获取class属性中的值,即Action类的全路径         使用反射功能,获取类中执行默认方法返回的值
            Class class = Class.forName("action标签中class属性的值");            Method method = class.getMethod("execute");            Object obj = method.invoke();
- Step4:得到action类中方法返回的值,并将该值与struts.xml中action标签里面的result标签         name属性的值匹配。如果一样,则调到指定的页面
0 0