最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Struts2 入门示例

旗下网站admin28浏览0评论

Struts2 入门示例

Struts2 入门示例

什么是Struts2?

  Struts2其实就是为我们封装了servlet,简化了jsp跳转的复杂操作,并且提供了易于编写的标签,可以快速开发view层的代码。

  过去,我们用jsp和servlet搭配,实现展现时,大体的过程是:

  1 jsp触发action   
  2 servlet接受action,交给后台class处理   
  3 后台class跳转到其他的jsp,实现数据展现

  现在有了struts2,实现过程变为

  1 、jsp出发action   
  2 、struts2拦截请求,调用后台action   
  3 、action返回结果,由不同的jsp展现数据

Struts2的工作原理

  一个请求在Struts2框架中的处理大概分为以下几个步骤 :
  1、客户端初始化一个指向Servlet容器(例如Tomcat)的请求
  2、这个请求经过一系列的过滤器(Filter)(这些过滤器中有一个叫做ActionContextCleanUp的可选过滤器,这个过滤器对于Struts2和其他框架的集成很有帮助,例如:SiteMesh Plugin)
  3、接着FilterDispatcher被调用,FilterDispatcher询问ActionMapper来决定这个请是否需要调用某个Action
  FilterDispatcher是控制器的核心,就是mvc中ctroller控制层的核心。下面粗略的分析下FilterDispatcher工作流程和原理,其核心方法doFilter
  doFilter()源码如下:

 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException ...{  
         HttpServletRequest request = (HttpServletRequest) req;  
         HttpServletResponse response = (HttpServletResponse) res;  
         ServletContext servletContext = filterConfig.getServletContext();  
         // 在这里处理了HttpServletRequest和HttpServletResponse。  
         DispatcherUtils du = DispatcherUtils.getInstance();  
         du.prepare(request, response);//正如这个方法名字一样进行locale、encoding以及特殊request parameters设置  
         try ...{  
             request = du.wrapRequest(request, servletContext);//对request进行包装  
         } catch (IOException e) ...{  
             String message = "Could not wrap servlet request with MultipartRequestWrapper!";  
             LOG.error(message, e);  
             throw new ServletException(message, e);  
         }  
         ActionMapperIF mapper = ActionMapperFactory.getMapper();//得到action的mapper  
         ActionMapping mapping = mapper.getMapping(request);// 得到action 的 mapping  
         if (mapping == null) ...{  
             // there is no action in this request, should we look for a static resource?  
             String resourcePath = RequestUtils.getServletPath(request);  
             if ("".equals(resourcePath) && null != request.getPathInfo()) ...{  
                 resourcePath = request.getPathInfo();  
             }  
             if ("true".equals(Configuration.get(WebWorkConstants.WEBWORK_SERVE_STATIC_CONTENT))   
                     && resourcePath.startsWith("/webwork")) ...{  
                 String name = resourcePath.substring("/webwork".length());  
                 findStaticResource(name, response);  
             } else ...{  
                 // this is a normal request, let it pass through  
                 chain.doFilter(request, response);  
             }  
             // WW did its job here  
             return;  
         }  
         Object o = null;  
         try ...{  
             //setupContainer(request);  
             o = beforeActionInvocation(request, servletContext);  
             //这个方法询问ActionMapper是否需要调用某个Action来处理这个(request)请求,如果ActionMapper决定需要调用某个Action,FilterDispatcher把请求的处理交给ActionProxy, 是Struts2最核心的方法
             du.serviceAction(request, response, servletContext, mapping);  
         } finally ...{  
             afterActionInvocation(request, servletContext, o);  
             ActionContext.setContext(null);  
         }  
     }  

  serviceAction()源码如下

public void serviceAction(HttpServletRequest request, HttpServletResponse response, String namespace, String actionName, Map requestMap, Map parameterMap, Map sessionMap, Map applicationMap) ...{   
        HashMap extraContext = createContextMap(requestMap, parameterMap, sessionMap, applicationMap, request, response, getServletConfig());  //实例化Map请求 ,询问ActionMapper是否需要调用某个Action来处理这个(request)请求  
        extraContext.put(SERVLET_DISPATCHER, this);   
        OgnlValueStack stack = (OgnlValueStack) request.getAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY);   
        if (stack != null) ...{   
            extraContext.put(ActionContext.VALUE_STACK,new OgnlValueStack(stack));   
        }   
        try ...{   
            ActionProxy proxy = ActionProxyFactory.getFactory().createActionProxy(namespace, actionName, extraContext);   
//这里actionName是通过两道getActionName解析出来的, FilterDispatcher把请求的处理交给ActionProxy,下面是ServletDispatcher的 TODO:   
            request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY, proxy.getInvocation().getStack());   
            proxy.execute();   
            //通过代理模式执行ActionProxy  
            if (stack != null)...{   
                request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY,stack);   
            }   
        } catch (ConfigurationException e) ...{   
            log.error("Could not find action", e);   
            sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e);   
        } catch (Exception e) ...{   
            log.error("Could not execute action", e);   
            sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);   
        }   
}  

  4、如果ActionMapper决定需要调用某个Action,FilterDispatcher把请求的处理交给ActionProxy
  5、ActionProxy通过ConfigurationManager询问框架的配置文件,找到需要调用的Action类 ,这里,我们一般是从struts.xml配置中读取。
  6、ActionProxy创建一个ActionInvocation的实例。
  7、ActionInvocation实例使用命名模式来调用,在调用Action的过程前后,涉及到相关拦截器(Intercepter)的调用。
  ActionInvocation是Xworks 中Action 调度的核心。而对Interceptor 的调度,也正是由ActionInvocation负责。ActionInvocation 是一个接口,而DefaultActionInvocation 则是Webwork 对ActionInvocation的默认实现。
  Interceptor将很多功能从我们的Action中独立出来,大量减少了我们Action的代码,独立出来的行为具有很好的重用性。XWork、WebWork的许多功能都是有Interceptor实现,可以在配置文件中组装Action用到的Interceptor,它会按照你指定的顺序,在Action执行前后运行。
  
  Interceptor的调度流程大致如下:

  1.ActionInvocation初始化时,根据配置,加载Action相关的所有Interceptor。
  2. 通过ActionInvocation.invoke方法调用Action实现时,执行Interceptor。
  在struts2中自带了很多拦截器,在struts2-core-2.1.8.jar这个包下的struts-default.xml中我们可以发现:

<interceptors>  
           <interceptor name="alias"class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>  
           <interceptor name="autowiring"class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>  
           <interceptor name="chain"class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/>  
           <interceptor name="conversionError"class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/>  
           <interceptor name="clearSession"class="org.apache.struts2.interceptor.ClearSessionInterceptor"/>  
           <interceptor name="createSession"class="org.apache.struts2.interceptor.CreateSessionInterceptor"/>  
           <interceptor name="debugging"class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor"/>  
           <interceptor name="externalRef"class="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor"/>  
           <interceptor name="execAndWait"class="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/>  
           <interceptor name="exception"class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/>  
           <interceptor name="fileUpload"class="org.apache.struts2.interceptor.FileUploadInterceptor"/>  
           <interceptor name="i18n"class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>  
           <interceptor name="logger"class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/>  
           <interceptor name="modelDriven"class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>  
           <interceptor name="scopedModelDriven"class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/>  
           <interceptor name="params"class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>  
           <interceptor name="actionMappingParams"class="org.apache.struts2.interceptor.ActionMappingParametersInteceptor"/>  
           <interceptor name="prepare"class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/>  
           <interceptor name="staticParams"class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>  
           <interceptor name="scope"class="org.apache.struts2.interceptor.ScopeInterceptor"/>  
           <interceptor name="servletConfig"class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>  
           <interceptor name="sessionAutowiring"class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/>  
           <interceptor name="timer"class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/>  
           <interceptor name="token"class="org.apache.struts2.interceptor.TokenInterceptor"/>  
           <interceptor name="tokenSession"class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/>  
           <interceptor name="validation"class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>  
           <interceptor name="workflow"class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/>  
           <interceptor name="store"class="org.apache.struts2.interceptor.MessageStoreInterceptor"/>  
           <interceptor name="checkbox"class="org.apache.struts2.interceptor.CheckboxInterceptor"/>  
           <interceptor name="profiling"class="org.apache.struts2.interceptor.ProfilingActivationInterceptor"/>  
           <interceptor name="roles"class="org.apache.struts2.interceptor.RolesInterceptor"/>  
           <interceptor name="jsonValidation"class="org.apache.struts2.interceptor.validation.JSONValidationInterceptor"/>  
           <interceptor name="annotationWorkflow"class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/>  
</interceptors> 

  8、一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果。返回结果通常是(但不总是,也可能是另外的一个Action链)一个需要被表示的JSP或者FreeMarker的模版。在表示的过程中可以使用Struts2 框架中继承的标签。在这个过程中需要涉及到ActionMapper

  在上述过程中所有的对象(Action,Results,Interceptors,等)都是通过ObjectFactory来创建的。

Struts2和Struts1的比较

  struts2相对于struts1来说简单了很多,并且功能强大了很多,我们可以从几个方面来看:
  从体系结构来看:struts2大量使用拦截器来出来请求,从而允许与业务逻辑控制器 与 servlet-api分离,避免了侵入性;而struts1.x在action中明显的侵入了servlet-api.
  从线程安全分析:struts2.x是线程安全的,每一个对象产生一个实例,避免了线程安全问题;而struts1.x在action中属于单线程。
   性能方面:struts2.x测试可以脱离web容器,而struts1.x依赖servlet-api,测试需要依赖web容器。
   请求参数封装对比:struts2.x使用ModelDriven模式,这样我们 直接 封装model对象,无需要继承任何struts2的基类,避免了侵入性。
  标签的优势:标签库几乎可以完全替代JSTL的标签库,并且 struts2.x支持强大的ognl表达式。

Struts2 入门示例

  上面讲了这么多基础的概念,现在正是进入我们的正题。
  所需架包如下:
  
  ognl提供了OGNL表达式
  struts2-core提供struts2核心包
  xwork-core由于struts2很多事基于webwork的,因此也需要这个的核心包
  
web.xml配置

    <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
        <!-- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  --> 
      </filter-class>
   </filter>

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

login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><s:text name="loginPage"/></title>
</head>
<body>
<s:form action="login">
    <s:textfield name="username" key="user"/>
    <s:textfield name="password" key="pass"/>
    <s:submit key="login"/>
</s:form>
</body>
</html>

LoginAction.java

package com.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

    public String execute() throws Exception {
           return SUCCESS;
    }
}

Struts2.xml

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    ".1.7.dtd">
<struts>
    <!-- 指定全局国际化资源文件 -->
    <constant name="struts.custom.i18n.resources" value="mess"/>
    <!-- 指定国际化编码所使用的字符集 -->    
    <constant name="struts.i18n.encoding" value="UTF-8"/>
    <!-- 所有的Action定义都应该放在package下 -->
    <package name="test" extends="struts-default">
        <action name="login" class="com.action.LoginAction">
            <result name="success">/login.jsp</result>
        </action>
    </package>
</struts>

mess_en.properties

loginPage=loginPage
errorPage=errorPage
succPage=succPage
failTip=sorry,login failed
succTip=welcome{0},login success
user=username
pass=password
login=login

mess_zh_CN.properties

loginPage=登陆界面
errorPage=失败界面
succPage=成功界面
failTip=对不起,您不能登录!
succTip=欢迎,{0},您已经登录!
user=用户名
pass=密 码
login=登陆

项目结构:

运行结果:

发布评论

评论列表(0)

  1. 暂无评论