Implementation of Struts framework in Java _java

Source: Internet
Author: User

This article mainly simple and rough implementation of Struts request forwarding function. Other functions will be followed up slowly.

Recently in the study of the content of Javassist, see an article we write together MVC the main simple description of the workflow of MVC, while the implementation of a simple struts2 function.

This is modeled after a simple struts2 framework, coupled with some of their own understanding.

This article mainly simple and rough implementation of Struts request forwarding function. Other functions will be followed up slowly.

First of all, in the STRUTS2 framework, the implementation of the request, the jump is mainly through the relevant configuration in Struts.xml. A <action> tag represents the definition of a request, which contains the name of the ① request "name", the ② request corresponding to the implementation class "Class", and ③ also customizes the method of execution through the "methods" attribute. If the default execution Execute0 method is not configured. The <result label defines the type "name" of the ① result, including ' SUCCESS ', ' NONE ', ' LOGIN ', ' INPUT ', ' ERROR '; ② requested type "type", including ' Dispatcher (default) ', ' Chain ', ' redirect ', ' redirectaction ', ' stream '; ③ the result of the jump. After the Struts.xml is configured, the form in the interface can find the corresponding action tag by matching the action attribute to the Name property value of the action definition, thus finding the appropriate class and the method to execute. The string string returned by the execution method is then matched to the name in the result label, and the next request is made based on the type of the definition.

Well, after understanding how the Struts2 interface request is connected to the program function, we implement this part of the function through our own code.

So, how are we supposed to do that?

We will need to implement the function of simple divided into two parts ①action part ②result part

Action section

① we need to find the corresponding class and the method of execution according to the request of the interface

Result part

① we need to return a string of the type ' SUCCESS ', ' NONE ', ' LOGIN ', ' INPUT ', ' ERROR ', according to the logic executed by the method

② need to specify different next request addresses for different return types

③ needs to define the type of request, including ' Dispatcher (default) ', ' Chain ', ' redirect ', ' redirectaction ', ' stream '

In this article, the return type of result only implements the ' SUCCESS ', ' LOGIN ', and the request type is not considered, and the default dispatcher request forwarding type is implemented. The perfect function will be replenished later.

So, let's look at the code to see how to implement the function as above.

First, you define the Actionannotation and resultannotation two custom annotations to request the corresponding method and the corresponding jump request for the string returned by the method.

 
/** 
 * Action Note: ActionName equivalent to web.xml configuration url-pattern  
 * @author linling * * * * 
/@Retention ( Retentionpolicy.runtime) 
@Target (elementtype.method) public 
@interface actionannotation 
{ 
  String ActionName () Default ""; 
  Resultannotation[] Results () default {}; 
}
 
  /** 
   * Returns the annotation object: name corresponds to the name of result in the struts configuration, including ' SUCCESS ', ' NONE ', ' ERROR ', ' INPUT ', ' LOGIN '; value corresponds to return jump content in struts configuration 
   * @author linling 
   * * * 
  /@Retention (Retentionpolicy.runtime) 
  @Target (elementtype.method) public 
  @interface resultannotation 
  { 
    resulttype name () default resulttype.success; 
    String value () default "index.jsp"; 
  } 
 

Then we define a Actioncontext class to hold the content that a request requires

/** * Implementation simulation struts to jump to action according to the configuration file the content needed in the appropriate method * @author linling * * * Public CLA 
    
  SS Actioncontext {/** * is equivalent to Url-pattern in Web.xml, unique/private String Url; 
    
  /** * actionannotation annotation corresponding method, i.e. the method to be executed in action * * Private String methods; result in/** * actionannotation corresponding to the type returned by the action method. 
    
  For example: Key: ' SUCCESS '; Value: ' index.jsp '/private map<resulttype, string> results; 
    
  /** * Action of the class * * Private class<?> ClassType; 
    
  /** * Action Object * * Private object action; 
    
  /** * Method Parameter type * * Private class<?>[] paramstype; 
    
  /** * The name of the method parameter, note that the method name needs to correspond to the above Paramtype parameter one by one * can be understood to be the attribute of the action in Struts/private string[] actionparamsname; 
    
  /** * This request httpservletrequest * * Private httpservletrequest requests; 
 
 
/** * This request httpservletresponse * * Private httpservletresponse response; 

Analysepackage is the method you need to assemble Actioncontext

  /** * Traversing the class file under Scan_package package, will use Actionannotation annotation method to parse, assemble into Actioncontext object and put into UrlMap @param real_pa TH * @param scan_package * @throws classnotfoundexception * @throws instantiationexception * @thro WS illegalaccessexception * @throws notfoundexception */public static void Analysepackage (String real_pa Th, 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 err or! 
            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); 
 
 
 } 
        } 
      } 
    }

The

Getparams gets an array of request parameters based on the contents of the request in the HttpServletRequest request, which is the parameter contents of the calling method body

  /** * Requests Request build parameters are parsed based on parameter type Parastype and parameter name Actinparamsname object[] * @param request * @param param Stype * @param actionparamsname * @return * @throws instantiationexception * @throws illegalaccess Exception * @throws illegalargumentexception * @throws invocationtargetexception * @throws Nosuchmethode Xception * @throws SecurityException */public static object[] Getparams (httpservletrequest request, Clas S<?>[] Paramstype, string[] actionparamsname) throws Instantiationexception, Illegalaccessexception, IllegalArgumentException, InvocationTargetException, Nosuchmethodexception, SecurityException {Object[] Objec 
      ts = new Object[paramstype.length]; 
        for (int i = 0; i < paramstype.length i++) {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; 
 
 
 }

Okay, next. We can implement the action method

 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; } 
  } 
 
 

Next, what we need to do is to get the program to iterate through the methods of all the classes in the working directory at startup, and we'll use the Actionannotation method to assemble the Actioncontext, which is the method we're asking to execute. So when the request is made we can find the corresponding Actioncontext according to the requested address and invoke the method through the mechanism of reflection.
 
We have two servlet set. One for executing the initialization program. One to filter all the action requests

  <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 implements filtering of the action requests that are used, and enables them to perform the corresponding action method, as well as the next jump

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 (), Actioncont 
        Ext.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"; 
 
 } 
          
      }

OK, now that we have implemented the simplest STRUT2 framework request forwarding function. The function is very rough, a lot of things have not been taken into account, I hope we have a lot of guidance ~

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.