JavaEE strust 2 初试

什么是struts 2

Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互。Struts 2是Struts的下一代产品,是在 struts 1和WebWork的技术基础上进行了合并的全新的Struts 2框架。

所需架包

JavaEE strust 2 初试_第1张图片

下载地址:http://struts.apache.org/download.cgi

实现原理

JavaEE strust 2 初试_第2张图片
1. 客户端发送请求 请求被核心过滤器进行拦截 过滤器通过ActionMapper 该类自动封装好请求信息,返回给过滤器
2. 过滤器会将封装好的请求信息发送给actionProxy 然后根据请求信息会读取配置文件
3. ActionProxy把request请求传递给ActionInvocation
4. ActionInvocation依次调用action和interceptor
5. 根据action的配置信息 产生result Result信息返回给ActionInvocation 产生一个HttpServletResponse响应 在返回给客户端

配置实现struts2

web.xml 配置核心过滤器

<filter>
  <filter-name>struts2filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
  filter>
  <filter-mapping>
  <filter-name>struts2filter-name>
  <url-pattern>/*url-pattern>
  filter-mapping>

src 下配置 struts.xml 文件
头文件 在 struts2-core-2.3.24.jar -> struts-default.xml 下
下面配置 在 struts-default.xml -> org.apache.struts2 -> default.properties 下



<struts>
    // 常用的配置修改  配置信息 在 struts2-core-2.3.24.jar --> org.apache.struts2 --> default.properties
    中 下面介绍几个常用的默认配置
    
    <constant name="struts.action.extension" value="action,,">constant>
    
    <constant name="struts.devMode" value="true">constant>

    
    <package name="hello" namespace="/hello" extends="struts-default">
        <action name="HelloAction" class="com.james.hello.HelloAction" method="hello">
            <result name="success">/hello.jspresult>
        action>
    package>
    
    <include file="com/james/def/struts.xml">include>
    <include file="com/james/dynamic/struts.xml">include>
    <include file="com/james/test/struts.xml">include>
struts>
// 这里介绍一种 配置 动态方法 方法 
在 < action ... > 中使用下面方法代码替换
<action name="HelloAction*" class="com.lanou3g.dynamic.Demo02Action" method="{1}">
//访问的时候我们可以在访问地址后面直接加方法的名字就可以访问 Action类中的每一种方法

至此 struts 2 配置完成 写第一行代码吧!

public class Demo05Action extends ActionSupport{

    public String hello() {
        System.out.println("Hello world!");
        return SUCCESS;
    }
}
// 创建Action类 有很多种 一般我们使用上面这种方式创建 继承ActionSupport
// 其他的还有 实现 Action 接口
// 通过阅读ActionSupport 我们得知 该类已经实现了Action接口 同时还实现了众多接口 每个接口都有相应的功能
// 为了以最少的代码 实现最多的功能 我们选择 继承ActionSupport 创建Action

你可能感兴趣的:(java)