常用框架之Struts2

    1. Struts2Strutswebwork的合并体,是一个基于MVC思想的控制层框架。采用了非侵入式设计,struts2有三大核心组件:Actionresult、拦截器
    2. Struts2开发流程

     

    1. 导包
    2. 编写web.xml文件
    3. 编写Action类(逻辑控制器,代替Servlet)
    4. 在src、struts.xml文件中配置action
    1. Struts2的主要控制器
      1. StrutsPreparedAndExecuteFilter

    Struts2的前端控制器,所有的请求都需要经过此控制器,只需要在xml文件中配置

    1. Action(存于Struts2的OGNL值栈中)

    后端控制器,纯的pojo对象。程序员开发的核心,主要方法:execute(),返回值类型为字符串,需要在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>

        <package name="default" namespace="/" extends="struts-default">

    <action name="user" class="com.oracle.action.UserAction">

    <result name="success">/success.jsp</result>

    </action>

        </package>

    </struts>

    1. <action>标签:

    name:action的请求名

    class:Action的类名(全路径)

    1. <result>标签:action的子标记,用来设置action的跳转路径及方式

    name:资源名

    /success.jsp资源地址

    1. struts逻辑时序图

     

     

    1. Action中如何访问Servlet API
      1. 原生的接口:注入的方法和利用上下文(由struts2提供)的方法
        1. ServletRequestAware
        2. ServletActionContext
      2. 解耦合方式:将域对象看做一个Map集合,建议使用。
        1. 实现SessionAware接口
        2. ActionContext.get方法(建议使用)
    2. 设置断点(在代码的左侧边框上双击鼠标左键)
      1. F6:单步执行
      2. F5:进入方法体
      3. F7:从方法中返回
      4. F8:进入到下一个断点,若果没有,则正常运行
    3. Action的配置
      1. 通配符的使用:

    action的name实行可以使用*作为通配符,只要匹配到name的格式,就会找到对应的方法,在method属性中可以使用{1}和{0};

    action中还可以配置exception-mapping,当action中出现异常的时候,将会将请求转发给对应的result。

    <action name="*User" class="com.oracle.action.UserAction" method="{1}">

    <result name="success">/success.jsp</result>

    <result name="index">/index.jsp</result>

    <result name="list">/list.jsp</result>

    </action>

    1. 异常的处理

    <global-results>

    <result name="error">/error.jsp</result>

    </global-results>

    <global-exception-mappings>

    <exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>

    </global-exception-mappings>

    1. 动态方法调用(了解)

    动态方法的调用可以简化action的配置,但不建议使用,因为不建议使用,默认struts2对此禁用。

    动态方法调用时,需要在url中包含方法,格式是actionName!methodName.action

    Struts.xml:

    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

    index.jsp:

    <form action="User!login.action" method="post">

    1. ActionSupport类

    该类实现了很多Action都需要实现的功能,一般来说在定义一个Action是,最好是继承此类。

    如果我们在配置Action时不指定class,name这个action将实例一个ActionSupport对象。

    1. Struts2结果(Result)的类型
      1. dispatcher常用):相当于forward,但只能转发给固定的资源,如jsp但不能转给另一个action
      2. chain:在<result>标签中设置属性type="chain",标签中为请求名。但存在提交数据时若刷新则出现重复提交的问题的问题。
      3. redirect:重定向到任何资源,包括action。参数有location等。

    <result name="list_action" type="redirect">

    <param name="location"><![CDATA[actionName]]></param>

    </result>

    <![CDATA[actionName]]>----此为CDATA结,在xml文件中因某些特殊字符或字节引发的解析错误提醒可用跳过解析,并其原样输出。

    1. redirectAction:专门用来重定向到另一个action 中,参数有actionName,namespace等

    <result name="list_action" type="redirectAction">

    <param name="actionName">listBook</param>

    </result>

    1. ModelDriven(参数组装)的方式(值栈的概念,action的属性在下,ModelDriven对象在上)
      1. 直接组装到Action的属性。
      2. 组装到action的一个实体对象中;要求表单的组件名应该是“对象名.属性名”。
      3. 通过ModelDriven接口返回一个对象。
    1. 类型转换——Struts2内置转换器

    Type Conversion is implemented by XWork.

    XWork will automatically handle the most common type conversion for you. This includes support for converting to and from Strings for each of the following:

    • String
    • boolean / Boolean
    • char / Character
    • int / Integer, float / Float, long / Long, double / Double
    • dates - uses the SHORT format for the Locale associated with the current request
    • arrays - assuming the individual strings can be coverted to the individual items
    • collections - if not object type can be determined, it is assumed to be a String and a new ArrayList is created
    1. OGNL(对象图导航语言)
      1. 独立于struts2的组件,是一种表达式语言,是EL表达式的增强版。Struts2集成了OGNL,所以可以在struts2中直接使用,若在非struts2下使用,导入ognl.jar包即可
      2. 基础:
        1. OGNLContext:类似域对象,即Map集合,相当于容器,用作存取值。
        2. 表达式
        3. 根元素

    OgnlContext context = new OgnlContext();

    //向OGNL上下文中存储数据

    context.put("username", "张三");

     

    User u = new User("lisi","444");

    context.put("user", u);

    List<String> list = Arrays.asList(new String[]{"刘备","关羽","张飞"});

    context.put("names", list);

    //设置根元素,是有特权的元素

    context.setRoot(user);

     

    //通过ognl来获取上下文中的数据

    Object name = Ognl.getValue("#userName",context,context.getRoot());

    System.out.println(name);

    1. ValueStack(校招易考)
      1. ValueStack实际是一个接口,在Struts2中利用OGNL时,实际上使用的是实现了该接口的OgnlValueStack类,这个类是Struts2利用OGNL的基础。OgnlValueStack类的主要属性关系图如下

                                      |--application

                                       |

                                      |--session

    ActionContext (聚合ValueStack)-  |

                                      |--value stack (OgnlValueStack的root属性,实际是个ArrayList)

                                      |

                                      |--request

                                      |

                                      |--parameters

                                      |

                                      |--attr (searches page, request, session, then application scopes)

    1. OgnlValueStack类包含两个重要的属性,一个root和一个context。其中root本质上是一个ArrayList,而context是一个Map(更确切的说是一个OgnlContext对象)。在这个OgnlContext对象(context)中,有一个默认的顶层对象root,OGNL访问context中这个默认顶层对象中的元素时,是不需要#号的,直接通过元素的名称来进行访问,而访问其他对象时,如request、session、attr等,则需要#号引用。Struts2将OgnlValueStack的root对象赋值给了context中的root对象,在OgnlValueStack的root对象中,保存着调用Action的实例,因此,在页面上通过Struts2标签访问Action的属性时,就不需要通过#号来引用。
    2. 当系统创建了Action实例后,该Action实例已经被保存到ActionInvocation的ValueStack中,故无须书写#即可访问Action属性。
    3. 在JSP中使用OGNL时取值时若Action与PO出现同名属性,则取得的值为栈顶元素值。
    1. 分清ActionContext 、ValueStack 、Stack Context
      1. ActionContext

    一次Action调用都会创建一个ActionContext,ActionContext是Action上下文,可以得到request, session ,application  ,

    调用:ActionContext context = ActionContext.getContext()

    1. ValueStack

    由OGNL框架实现,可以把它简单的看作一个栈(Stack),存放表单中的值。

    Stack Object:放入stack中的对象,一般是action。

    1. Stack Context(map):stack上下文,也是用来存值的 。

    它包含一系列对象,包括request/session/attr/application map等。

    1. EL:存取对象的任意属性,调用对象的方法,遍历整个对象结果…
    1. Struts2的拦截器(Interceptor)(重点!)
      1. 这是Struts2最重要的一个组件,Struts2的大部分功能都是通过拦截器来实现的,例如:文件上传,参数组装,重复提交,modelDriven等功能。拦截器是动态拦截Action调用的对象,类似于Servlet中的过滤器。在执行Action的业务逻辑处理方法( execute())之前,Struts2会首先执行在struts.xml中引用的拦截器。
      2. Struts2将它的核心功能放到拦截器中实现,而不是分散到Action中实现,有利于系统的解耦,使得功能的实现类似于个人电脑的组装,变成了可插拔的,需要某个功能就“插入”一个拦截器,不需要某个功能就“拔出”一个拦截器。你可以任意组合拦截器来为Action提供附加的功能,而不需要修改Action的代码。
      3. Struts2的拦截器分两种:
        1. 预定义的
        2. 自定义的
      1. Struts2拦截器的工作原理

    Struts2会根据struts.xml动态的创建一个代理对象,这个代理对象的名字是ActionProxy,它里面包含了n个拦截器和Action。

    class——ModelDrivenInterceptor

    public String intercept(ActionInvocation invocation) throws Exception {

            Object action = invocation.getAction();

     

            if (action instanceof ModelDriven) {

                ModelDriven modelDriven = (ModelDriven) action;

                ValueStack stack = invocation.getStack();

                Object model = modelDriven.getModel();

                if (model !=  null) {

                        stack.push(model);

                }

                if (refreshModelBeforeResult) {

                    invocation.addPreResultListener(new RefreshModelBeforeResult(modelDriven, model));

                }

            }

            return invocation.invoke();

        }

    1. token拦截器处理表单重复提交

    token在处理表单重复提交时,浏览器与服务器双方会统一生成相同的“令牌”,当第一次请求到达服务器时,相互令牌进行匹配,若匹配成功,服务器端令牌置空,相同请求再次重复提交时服务器端令牌已清空,故匹配失败,从而实现表单的重复提交。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值