框架入门1-struts2准备与原理

第一个问题: struts2 是什么?
 struts2 是一个用来开发MVC应用程序的框架,它提供web应用程序开发过程中得一些常见问题的解决方案
对页面导航活动进行管理
对来自用户的输入数据进行合法性验证
统一的布局
可扩展性
国际化和本地化
支持ajax
表单的重复提交
..
第一个struts2应用 准备步骤:
(1)创建javaweb工程
HelloWorldStruts2
(2)找到Struts应用需要的jar文件
到http ://struts.apache.org/download.cgi#struts2014 下载struts-2.x.x-all.zip
找到以下的jar包
 struts2-core-2.1.8.1.jar :Struts 2框架的核心类库
  xwork-core-2.1.6.jar :XWork类库,Struts 2在其上构建
  ognl-2.7.3.jar :对象图导航语言(Object Graph Navigation Language),
                        struts2框架通过其读写对象的属性
 freemarker-2.3.15.jar :Struts 2的UI标签的模板使用FreeMarker编写
 commons-logging-1.1.x.jar :ASF出品的日志包,Struts 2框架使用这个日志
                                                包来支持Log4J和JDK 1.4+的日志记录。
  commons-fileupload-1.2.1.jar 文件上传组件,2.1.6版本后需要加入此文件
 commons-io-1.3.2.jar,上传文件依赖的jar包
(3)创建jsp文件
在hellojsp下面创建一个world.jsp
在里面写一个超链接
<a href="${pageContext.request.contextPath} /helloaction/HelloWorldAction.action">helloworld</a><br>
(4)创建action文件
import com.opensymphony.xwork2.Action;
public class HelloWorldAction implements Action{
public String execute() throws Exception {
System.out.println("helloWorld");
//转到成功页面
return "success";
}
}
(5)编写strut2的配置文件
在src下创建一个struts.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
 <!--
     <a href="${pageContext.request.contextPath}//helloaction/helloWorldAction.action">helloWorld</a><br>
        package:包的名称,struts2中以包来管理action
        * name:包的名称,唯一的,主要作用用于继承
        * namespace:命名空间,包的唯一标识,相当于房间号
        * extends:继承其他的包,这里继承struts2-core-2.1.8.1.jar/struts-default.xml中的
               <package name="struts-default" abstract="true">包?
     action:客户端请求的action
        * name:请求的action的名称,一定要和请求的路径对应
        * class:action所在类的完整路径
     result:返回的结果
        * name: 与execute方法的返回值对应,唯一的
            public String execute() throws Exception {
               System.out.println("HelloWorldAction execute **");
              return "success";
             }
        * result标签的文本:转向的路径
   -->
  <package name="action" namespace="/helloaction" extends="struts-default">
      <!-- 配置当请求的路径找不到action的情况下,执行默认的action,这里执行helloWorldAction-->
      <default-action-ref name="helloWorldAction"/>
      <action name="helloWorldAction" class="com.HelloWorldAction">
        <result name="success">/hellojsp/world.jsp</result>
      </action>
      <!--
          /helloaction/actionNoClass.action
            * 如果没有为action指定class,则默认的class是com.opensymphony.xwork2.ActionSupport类型
            * 如果没有执行action指定的方法,默认执行execute()方法
                   public String execute() throws Exception {
                        return SUCCESS;
                    }
            * 如果没有为result指定name属性,默认是name属性的值是success
     -->
     <action name="actionNoClass">
        <result>/hellojsp/world.jsp</result>
     </action>
  </package>
</struts>
(6)在web.xml中加入strutsMVC框架启动配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
    <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>
</web-app>
在struts2框架中使用包来管理Action,包的作用和java中的类包是非常类似的,它主要用于管理一组业务功能相关的action。在实际应用中,我们应该把一组业务功能相关的Action放在同一个包下。
配置包时必须指定name属性,如果其他包要继承该包,必须通过该属性进行引用,注意:name名称是唯一 。包的namespace属性用于定义该包的命名空间。该属性可以不配置,对本例而言,如果不指定该属性,默认的命名空间为“/”
通常每个包都应该继承struts-default包, struts-default包是由struts内置的,它定义了struts2内部的众多拦截器和Result类型。而Struts2很多核心的功能都是通过这些内置的拦截器实现。如:从请求中把请求参数封装到action、文件上传和数据验证等等都是通过拦截器实现的。当包继承了struts-default包才能使用struts2为我们提供的这些功能。 struts-default包是在struts2-core-2.x.x.jar文件中的struts-default.xml中定义。 struts-default.xml也是Struts2默认配置文件。 Struts2每次都会自动加载 struts-default.xml文件。
包还可以通过abstract=“true”定义为抽象包,抽象包中不能包含action。
----------------------------------------------------------------------
只要按照上面的写下来就可以啦
下面讲讲原理
tomact启动会加载web.xml文件 可是 当它一看到  
<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>
 他就傻B啦 就开始去StrutsPrepareAndExecuteFilter 类里面找东西 当然会执行init方法
package org.apache.struts2.dispatcher.ng.filter;
public class StrutsPrepareAndExecuteFilter
  implements StrutsStatics, Filter
{
  protected PrepareOperations prepare;
  protected ExecuteOperations execute;
  protected List<Pattern> excludedPatterns;

  public StrutsPrepareAndExecuteFilter()
  {
    this.excludedPatterns = null; }

  public void init(FilterConfig filterConfig) throws ServletException {
    InitOperations init = new InitOperations();
    try {
      FilterHostConfig config = new FilterHostConfig(filterConfig);
      init.initLogging(config);
      Dispatcher dispatcher = init.initDispatcher(config);
      init.initStaticContentLoader(config, dispatcher);

      this.prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
      this.execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
      this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

      postInit(dispatcher, filterConfig);
    } finally {
      init.cleanup();
    }
  }
  protected void postInit(Dispatcher dispatcher, FilterConfig filterConfig)
  {
  }
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
    throws IOException, ServletException
  {
    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;
    try
    {
      this.prepare.setEncodingAndLocale(request, response);
      this.prepare.createActionContext(request, response);
      this.prepare.assignDispatcherToThread();
      if ((this.excludedPatterns != null) && (this.prepare.isUrlExcluded(request, this.excludedPatterns))) {
        chain.doFilter(request, response);
      } else {
        request = this.prepare.wrapRequest(request);
        ActionMapping mapping = this.prepare.findActionMapping(request, response, true);
        if (mapping == null) {
          boolean handled = this.execute.executeStaticResourceRequest(request, response);
          if (!(handled))
            chain.doFilter(request, response);
        }
        else {
          this.execute.executeAction(request, response, mapping);
        }
      }
    } finally {
      this.prepare.cleanupRequest(request);
    }
  }

  public void destroy() {
    this.prepare.cleanupDispatcher();
  }
}
学过过滤器的童鞋们都知道 他先会调用init方法而在init方法中 如果我猜的没错 他就会去项目的跟目录下面找一个叫struts.xml的配置配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>

    <!-- 配置struts2的主题,修改为简单主题,对所有的jsp页面都启作用-->
    <constant name="struts.ui.theme" value="simple"/>
   
    <!--配置struts2是否支持动态方法调用(默认值true)支持,false不支持-->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

    <!-- 配置struts2的请求后缀,如果有多个用,隔开-->
    <constant name="struts.action.extension" value="action"></constant>

    <!--配置当国际化资源文件发生变化,是否自动加载国际化资源文件(默认是false)  true:重新加载 -->
    <!-- <constant name="struts.i18n.reload" value="true"></constant> -->
   
    <!--配置当struts2配置文件发生变化时,是否重新加载配置文件(默认是false) true:重新加载-->
    <!-- <constant name="struts.configuration.xml.reload" value="true"></constant>-->
    <!--设置struts2的模式,
           * 默认是false(生产模式),当项目交付后,要设置为生产模式
           * true(开发模式),开发阶段,设置为开发模式 ,可以打印出更过的调试信息
               * 包含如下两个功能:
                  struts.i18n.reload = true
                  struts.configuration.xml.reload = true
      -->
    <constant name="struts.devMode" value="true"/>
    <!-- 配置加载自定义的国际化资源文件,如果有多个用","隔开
           * cn.itcast.upload.fileupload 加载fileupload.properties资源文件
           * cn.itcast.model.token   加载token.properties资源文件
           * cn.itcast.i18n.resource 加载处理国际化的资源文件
    -->
    <constant name="struts.custom.i18n.resources"
              value="cn.itcast.upload.fileupload,
                     cn.itcast.model.token"></constant>
    
    <!-- 引入其他的配置文件 -->
    <include file="cn/itcast/primer/struts_primer.xml"></include>
    <include file="cn/itcast/resulttype/struts_resulttype.xml"></include>
    <include file="cn/itcast/pattern/struts_pattern.xml"></include>
    <include file="cn/itcast/converter/struts_converter.xml"></include>
    <include file="cn/itcast/context/struts_context.xml"></include>
    <include file="cn/itcast/upload/struts_upload.xml"></include>
    <include file="cn/itcast/aop/struts_aop.xml"></include>
    <include file="cn/itcast/validate/struts_validate.xml"></include>
    <include file="cn/itcast/ognl/struts_ognl.xml"></include>
    <include file="cn/itcast/ui/struts_ui.xml"></include>
    <include file="cn/itcast/model/struts_model.xml"></include>
     <include file="cn/itcast/i18n/struts_i18n.xml"></include>
</struts>
上面这个struts是我老师写的  如果不幸碰到啦拦截器(以后我会细说的) 就会进入拦截器对应的类中 进行处理 处理之后继续往下走 如果有碰到啦拦截器 那就在...
在这个文件中你可以配置主题 配置拦截器 配置常量. 很多很多 所以说他可扩展行狠强  他都是可拔插的 如果您不幸配到了 <include>标签 他就会吧inclued中得配置文件也加载到tomcat中
现在你知道问什么用struts2时启动tomcat特别慢了把 他做啦很多事情
当这些事情都做完啦 init方法也就完啦 他就进入啦doFilter方法中 如果我没有猜错的话  在这个方法里面他对request 和response 等等 servlet 进行啦 包装..
为什么老师说 struts2会不依赖于servletapi 可能就是这个缘故把
我猜想在这他好像还做了一件事 就是对您的 输入进行啦判断 如果您再web.xml中得mapping中写的是您的拦截的...action 条件 他就会在这进行判断和放行.
之类的把..老师也没讲 全靠我猜的..
这样初始化的工作也就完成啦 他往你内存中写啦很多数据 还有他吧页面 还有action 完全都控制住啦 都放到了他的actionContext容器中 你可以随放随去 所以就方便啦
我觉得把! 其实只要懂啦这些原理 到以后也就好调试啦  可是现在很多人都不跟你说原理 我也没听别人说我 我都是自己猜的 如果哪位高手看到觉得不对那请原谅啊



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值