Configuration-based custom simple struts (understand struts Principles)

Source: Internet
Author: User

Configuration-based custom simple struts (understand struts Principles)

Struts's configuration-based action jump method is very convenient to use. I also mimic struts's action to implement a simple operation defined by myself through the configuration file:

First, we can know that sturts intercepts the requests sent by the browser through the filter, and then operates in the filter to implement this process.

Then, we also define a filter in our program:

 

public class StrutsFilter implements Filter{     public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws       IOException, ServletException {     {            }}


 

Similarly, all requests are intercepted and configured in web. xml:

 

 
     
  
   Struts Blank
      
          
   
    struts2
           
   
    com.yc.frame.filter.StrutsFilter
       
      
          
   
    struts2
           
   
    *
       
      
          
   
    index.jsp
       
  
 
Of course, the most important thing in struts is struts. the configuration file of xml can be analyzed here. struts must first parse the xml, store the parsed xml in a data structure, and use reflection to find the corresponding Action subclass, use reflection to activate the configuration method or the default execute method. Since the logic has come out, how can I set the data structure to store the files parsed by xml?

 

Struts. xml is as follows:

 

 
   
      
                   
   
    
A. jsp
                
   
    
A. jsp
            
       
  
 


 

Here, each node corresponds to a class. Because xml has a corresponding hierarchical relationship, the hierarchical relationship of these classes should also be reflected when designing these classes, in order to accurately process and operate the data:

 

// Node class corresponding to the package node, which should have a set of actioin node classes
Naturally, the getset method (get, set omitted) must be provided)

Public class PackageWrapper implements Serializable {/*****/private static final long serialVersionUID =-7700027765680530207L; private String namespace; private Map ActionMap = new HashMap ();
}
// Action node class, and also a node set of result class,
 
(Get, set omitted)

 

 

Public class ActionWrapper implements Serializable {
/**
*
*/
Private static final long serialVersionUID =-00006005261524671229l;
Private String className;
Private String methodName;
Private Map ResultMap = new HashMap ();
}
Package com. yc. frame. wrapper;

// Node class of the result Node

Public class ResultWrapper implements Serializable {

Private String type;
Private String value;
Public String getType (){
Return type;
}
Public void setType (String type ){
This. type = type;
}
Public String getValue (){
Return value;
}
Public void setValue (String value ){
This. value = value;
}
Therefore, you must first parse and save them before performing operations. Therefore, initialize and store them in the init method of filter. Here we use dom4j to parse it: (the parsing is omitted. If you need it, please leave a message to the source code !) 

 

The core step is to read the data and retrieve the entity class of the action, use reflection to find the corresponding method, execute the action method to get the returned value, and finally determine the type of the result, execute the jump page, is it clear?

 

// 1. resolution request HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponse response = (HttpServletResponse) arg1; String servletPath = request. getServletPath (); // This is the requested resource path name. // you can determine whether the request path is actionif (servletPath. lastIndexOf (. action) =-1) {arg2.doFilter (request, response);} else {try {// address format: cccc/user. action/user. actionint lastSlashIndex = servletPath. lastIndexOf (/); String requestActionName = servletPath. su Bstring (lastSlashIndex + 1); String nameSpaceName = servletPath. substring (0, lastSlashIndex); // This is the folder address next to the project. // 2. find this actionPackageWrapper packageWrapper = null in map; // TODO: // Why is this entry used here? For (Map. Entry
     
      
Entry: packagesMap. entrySet () {PackageWrapper pw = entry. getValue (); pw. getNamespace (). equals (nameSpaceName); packageWrapper = pw; break;} // 3. reflection: the object that generates the action // 4. activate the execute method of this action // 5. get the StringActionWrapper actionWrapper = packageWrapper returned by the execute Command. getActionMap (). get (requestActionName); String actionClassName = actionWrapper. getClassName (); Class c = Class. forName (actionClassName); Object obj1 = c. newInstance (); // TODO: // here, the packageWrapper is used to obtain the List of interceptor sets.
      
       
Interceptors = new ArrayList
       
        
(); List
        
         
Iw = packageWrapper. getInterceptorList (); if (iw. size ()> 0) {for (int I = 0; I
         
          
Map = parseRequest (request); // 2. find out each Method to be injected from c getMthod Method name Method [] MS = c. getMethods (); // 3. reverse activation Method, injection parameter for (Method m: ms) {String methodName = m. getName (); if (map. containsKey (methodName) {String [] values = map. get (methodName); if (values. length = 1) {String s = values [0]; String type = m. getParameterTypes () [0]. getName (); if (m. getParameterTypes () [0]. getName (). equals (java. lang. integer) | m. getParameterTypes () [0]. getName (). equals (int) {// activation method, input value m. invoke (obj, Integer. parseInt (s); continue;} else if (m. getParameterTypes () [0]. getName (). equals (java. lang. double) | m. getParameterTypes () [0]. getName (). equals (double) {m. invoke (obj, Double. parseDouble (s); continue;} else if (m. getParameterTypes () [0]. getName (). equals (java. lang. float) | m. getParameterTypes () [0]. getName (). equals (float) {m. invoke (obj, Float. parseFloat (s); continue;} else if (m. getParameterTypes () [0]. getName (). equals (java. lang. string) | m. getParameterTypes () [0]. getName (). equals (String) {m. invoke (obj, s); continue ;}}} private Map
          
            ParseRequest (HttpServletRequest request) {Map
           
             Map = new HashMap
            
              (); Enumeration
             
               Enu = request. getParameterNames (); while (enu. hasMoreElements () {String name = enu. nextElement (); String methodName = set + name. substring (0, 1 ). toUpperCase () + name. substring (1); map. put (methodName, request. getParameterValues (name);} return map;} public void init (FilterConfig config) throws ServletException {// read the configuration file Struts. xml = "Maprealpath = config. getServletContext (). getRealPath (/); packagesMap = parseStrutsXml ();}
             
            
           
          
         
        
       
      
     
Parsing the xml file is omitted. This is the simplest struts implemented by myself. Of course, the powerful struts is just an imitation of the fur. Welcome to discuss and learn from each other.

 

 

Related Article

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.