当前位置: 移动技术网 > IT编程>开发语言>Java > java中struts 框架的实现

java中struts 框架的实现

2019年07月22日  | 移动技术网IT编程  | 我要评论
该文章主要简单粗暴的实现了struts的请求转发功能。 其他的功能后续会慢慢补上。 最近在学习javassist的内容,看到一篇文章  大家一起写mvc&nbs

该文章主要简单粗暴的实现了struts的请求转发功能。 其他的功能后续会慢慢补上。

最近在学习javassist的内容,看到一篇文章  大家一起写mvc  主要简单的描述了mvc的工作流程,同时实现了简单的struts2功能。

这里仿照的写了个简单的struts2框架,同时加上了自己的一些理解。

该文章主要简单粗暴的实现了struts的请求转发功能。 其他的功能后续会慢慢补上。

首先,在struts2框架中,请求的实现、跳转主要是通过在struts.xml进行相关配置。 一个<action>标签表示一个请求的定义,action中包含了①请求的名称“name”;②请求对应的实现类“class” ;③同时还可通过“method”属性自定义执行的方法,若没配置默认执行execute0方法。<result》标签定义了①结果的类型“name”,包括'success'、'none'、'login'、'input'、'error';②请求的类型“type”,包括'dispatcher(默认)'、'chain'、'redirect'、'redirectaction'、'stream';③结果的跳转。 在配置完struts.xml后,界面中的表单就可以通过action属性与action定义的name属性值相匹配找到对应的action标签,从而找到对应的class以及执行的方法。再根据执行方法返回的string字符串同result标签中的name相匹配,根据定义的type类型,进行下一步请求操作。

好了,在了解了struts2是怎么将界面请求同程序功能相连接后,我们通过自己的代码来实现这部分的功能。

那么,我们该如何下手了?

我们将需要实现的功能简单的分为两部分 ①action部分 ②result部分

   action部分

       ①我们需要根据界面的请求找到对应的类以及执行的方法

    result部分

        ①我们需要根据方法执行的逻辑返回'success'、'none'、'login'、'input'、'error'这类型的字符串
 
        ②需要对不同的返回类型,指定不同的下一步请求地址
 
        ③需要定义请求的类型,包括'dispatcher(默认)'、'chain'、'redirect'、'redirectaction'、'stream'

在本文章中,result的返回类型只实现了'success'、'login'两种,并且暂不考虑请求类型,实现的是默认的dispatcher请求转发类型。完善的功能后期会再补充。

那么,下面我们来通过代码看怎么实现如上功能。 

首先定义了actionannotation和resultannotation 两个自定义注解来请求需要对应的方法以及方法返回的字符串对应的跳转请求

 
/** 
 * action注解:actionname相当于web.xml配置中的url-pattern  
 * @author linling 
 * 
 */ 
@retention(retentionpolicy.runtime) 
@target(elementtype.method) 
public @interface actionannotation 
{ 
  string actionname() default ""; 
  resultannotation[] results() default {}; 
}
 
  /** 
   * 返回注解对象:name相当于struts配置中的result的name,包括'success'、'none'、'error'、'input'、'login';value相当于struts配置中对应返回跳转内容 
   * @author linling 
   * 
   */ 
  @retention(retentionpolicy.runtime) 
  @target(elementtype.method) 
  public @interface resultannotation 
  { 
    resulttype name() default resulttype.success; 
    string value() default "index.jsp"; 
  } 
 

然后我们定义一个actioncontext类,来保存一个请求所需要的内容

 
/** 
 * 实现模拟struts根据配置文件跳转至action执行相应方法中需要的内容 
 * @author linling 
 * 
 */ 
public class actioncontext 
{ 
  /** 
   * 相当于web.xml中url-pattern,唯一的 
   */ 
  private string url; 
    
  /** 
   * actionannotation注解对应方法,也就是action中要执行的方法 
   */ 
  private string method; 
    
  /** 
   * actionannotation中的result,对应action方法返回的类型。例如:key:'success';value:'index.jsp' 
   */ 
  private map<resulttype, string> results; 
    
  /** 
   * action的类 
   */ 
  private class<?> classtype; 
    
  /** 
   * action的对象 
   */ 
  private object action; 
    
  /** 
   * 方法参数类型 
   */ 
  private class<?>[] paramstype; 
    
  /** 
   * 方法参数的名称,注意这里方法名称需要和上面paramtype参数一一对应 
   * 可以理解为是struts中action中的属性 
   */ 
  private string[] actionparamsname; 
    
  /** 
   * 本次请求的httpservletrequest 
   */ 
  private httpservletrequest request; 
    
  /** 
   * 本次请求的httpservletresponse 
   */ 
  private httpservletresponse response; 
 
 

analysepackage是在组装actioncontext需要的方法

  /** 
     * 遍历scan_package包下的class文件,将使用了actionannotation注解的方法进行解析,组装成actioncontext对象 并放入urlmap中 
     * @param real_path 
     * @param scan_package 
     * @throws classnotfoundexception 
     * @throws instantiationexception 
     * @throws illegalaccessexception 
     * @throws notfoundexception 
     */ 
    public static void analysepackage(string real_path, string scan_package) throws classnotfoundexception, instantiationexception, illegalaccessexception, notfoundexception 
    { 
      file file = new file(real_path); 
      if(file.isdirectory()) 
      { 
        file[] files = file.listfiles(); 
        for(file f : files) 
        { 
          analysepackage(f.getabsolutepath(),scan_package); 
        } 
      } 
      else 
      { 
        string str = real_path.replaceall("/", "."); 
        if (str.indexof("classes." + scan_package) <= 0 || !str.endswith(".class")) 
        { 
          return; 
        } 
        string filename = str.substring(str.indexof(scan_package),str.lastindexof(".class")); 
        class<?> classtype = class.forname(filename); 
        method[] methods = classtype.getmethods(); 
        for(method method : methods) 
        { 
          if(method.isannotationpresent(actionannotation.class)) 
          { 
            actioncontext actioncontext = new actioncontext(); 
            actionannotation actionannotation = (actionannotation)method.getannotation(actionannotation.class); 
            string url = actionannotation.actionname(); 
            resultannotation[] results = actionannotation.results(); 
            if(url.isempty() || results.length < 1) 
            { 
              throw new runtimeexception("method annotation error! method:" + method + " , actionname:" + url + " , result.length:" + results.length); 
            } 
            actioncontext.seturl(url); 
            actioncontext.setmethod(method.getname()); 
            map<resulttype, string> map = new hashmap<resulttype, string>(); 
            for(resultannotation result : results) 
            { 
              string value = result.value(); 
              if(value.isempty()) 
              { 
                throw new runtimeexception("result name() is null"); 
              } 
              map.put(result.name(), value); 
            } 
            actioncontext.setresults(map); 
            actioncontext.setclasstype(classtype); 
            actioncontext.setaction(classtype.newinstance()); 
            actioncontext.setparamstype(method.getparametertypes()); 
            actioncontext.setactionparamsname(getactionparamsname(classtype, method.getname())); 
            urlmap.put(url, actioncontext); 
          } 
        } 
      } 
    } 
 
 

getparams是根据httpservletrequest请求中的请求内容获得请求参数数组,该参数数组为调用方法体的参数内容

  /** 
     * 根据 参数类型parastype 和 参数名actinparamsname 来解析请求request 构建参数object[] 
     * @param request 
     * @param paramstype 
     * @param actionparamsname 
     * @return 
     * @throws instantiationexception 
     * @throws illegalaccessexception 
     * @throws illegalargumentexception 
     * @throws invocationtargetexception 
     * @throws nosuchmethodexception 
     * @throws securityexception 
     */ 
    public static object[] getparams(httpservletrequest request, class<?>[] paramstype, string[] actionparamsname) throws instantiationexception, illegalaccessexception, illegalargumentexception, invocationtargetexception, nosuchmethodexception, securityexception 
    { 
      object[] objects = new object[paramstype.length]; 
      for(int i = 0; i < paramstype.length; i++) 
      { 
        object object = null; 
        if(paramsutils.isbasictype(paramstype[i])) 
        { 
          objects[i] = paramsutils.getparam(request, paramstype[i], actionparamsname[i]); 
        } 
        else 
        { 
          class<?> classtype = paramstype[i]; 
          object = classtype.newinstance(); 
          field[] fields = classtype.getdeclaredfields(); 
          for(field field : fields) 
          { 
            map<string, string[]> map = request.getparametermap(); 
            for(iterator<string> iterator = map.keyset().iterator(); iterator.hasnext();) 
            { 
              string key = iterator.next(); 
              if(key.indexof(".") <= 0) 
              { 
                continue; 
              } 
              string[] strs = key.split("\\."); 
              if(strs.length != 2) 
              { 
                continue; 
              } 
              if(!actionparamsname[i].equals(strs[0])) 
              { 
                continue; 
              } 
              if(!field.getname().equals(strs[1])) 
              { 
                continue; 
              } 
              string value = map.get(key)[0]; 
              classtype.getmethod(convertofieldtosetmethod(field.getname()), field.gettype()).invoke(object, value); 
              break; 
            } 
          } 
          objects[i] = object; 
        } 
      } 
      return objects; 
    } 
 
 

好了,接下来。我们可以来实现action方法了

  public class loginaction 
  { 
    @actionannotation(actionname="login.action",results={@resultannotation(name=resulttype.success,value="index.jsp"),@resultannotation(name=resulttype.login,value="login.jsp")}) 
    public resulttype login(string name, string password) 
    { 
      if("hello".equals(name) && "world".equals(password)) 
      { 
        return resulttype.success; 
      } 
      return resulttype.login; 
    } 
      
    @actionannotation(actionname="loginforuser.action",results={@resultannotation(name=resulttype.success,value="index.jsp"),@resultannotation(name=resulttype.login,value="login.jsp")}) 
    public resulttype loginforuser(int number, loginpojo loginpojo) 
    { 
      if("hello".equals(loginpojo.getusername()) && "world".equals(loginpojo.getpassword())) 
      { 
        return resulttype.success; 
      } 
      return resulttype.login; 
    } 
  } 
 
 

接下来,我们需要做的是让程序在启动的时候去遍历工作目录下所有类的方法,将使用了actionannotation的方法找出来组装成actioncontext,这就是我们请求需要执行的方法。这样在请求到了的时候我们就可以根据请求的地址找到对应的actioncontext,并通过反射的机制进行方法的调用。
 
我们定了两个servlet。一个用于执行初始化程序。一个用来过滤所有的action请求

  <servlet> 
    <servlet-name>strutsinitservlet</servlet-name> 
    <servlet-class>com.bayern.struts.one.servlet.strutsinitservlet</servlet-class> 
    <init-param> 
      <param-name>scan_package</param-name> 
      <param-value>com.bayern.struts.one</param-value> 
    </init-param> 
    <load-on-startup>10</load-on-startup> 
   </servlet> 
     
   <servlet> 
    <servlet-name>dispatcherservlet</servlet-name> 
    <servlet-class>com.bayern.struts.one.servlet.dispatcherservlet</servlet-class> 
   </servlet> 
   <servlet-mapping> 
    <servlet-name>dispatcherservlet</servlet-name> 
    <url-pattern>*.action</url-pattern> 
   </servlet-mapping> 

dispatcherservlet实现了对所用action请求的过滤,并使之执行对应的action方法,以及进行下一步的跳转

ublic void dopost(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception 
  { 
  
    request.setcharacterencoding("utf-8"); 
    string url = request.getservletpath().substring(1); 
    actioncontext actioncontext = dispatcherservletutil.urlmap.get(url); 
    if(actioncontext != null) 
    { 
      actioncontext.setrequest(request); 
      actioncontext.setresponse(response); 
      try 
      { 
        object[] params = dispatcherservletutil.getparams(request, actioncontext.getparamstype(), actioncontext.getactionparamsname()); 
        class<?> classtype = actioncontext.getclasstype(); 
        method method = classtype.getmethod(actioncontext.getmethod(), actioncontext.getparamstype()); 
        resulttype result = (resulttype)method.invoke(actioncontext.getaction(), params); 
        map<resulttype,string> results = actioncontext.getresults(); 
        if(results.containskey(result)) 
        { 
          string tourl = results.get(result); 
          request.getrequestdispatcher(tourl).forward(request, response); 
        } 
        else 
        { 
          throw new runtimeexception("result is error! result:" + result); 
        } 
          
      } 
 

好了,现在我们已经实现了最简单的strut2框架的请求转发的功能。功能写得很粗糙,很多情况都还未考虑进来,希望大家多多指点~

以上所述就是本文的全部内容了,希望大家能够喜欢。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网