struts2--Custom Frame! Mini version

Source: Internet
Author: User

feel this custom frame really crazy ... Followed once again, oneself again 1 times, altogether looked 5 times, now put out for the reference--, but also gives oneself later to see

The following is the approximate process, do very simple bags, interceptors are not

Filter    , parse configuration file (map user request to action),  
set user-submitted data to action---   process result set

1. Import Struts2core Package +dom4j package (used to read XML configuration file)

Commons-fileupload-1.3.2.jar
commons-io-2.4.jar
commons-lang3-3.4.jar
Dom4j-1.6.1.jar
Freemarker-2.3.23.jar
javassist-3.20.0-ga.jar
log4j-api-2.7.jar
Ognl-3.1.12.jar
Struts2-core-2.5.8.jar

2. Create the framework (custom). XML configuration File

<?xml version= "1.0" encoding= "UTF-8"?>

<framework>
    <action name= "Hello" class= " Com.action.HelloAction ">
        <result>/index.jsp</result>
    </action>

    <action Name = "Login" class= "com.action.LoginAction" >
        <result>/success.jsp</result>
        <result name= " Login >/login.jsp</result>
    </action>
</framework>

3. Create Com.core Package (Action, Result, Actionmapper Class)

1, Action.java

public class Action {//property declaration private String name;
    Private String Classurl; Private String method= "execute";//default property//Here use Map to install result set private map<string, result> resultmap=new HashMap

    <String,Result> ();
        Construction method Public action () {} public action (string name, String classurl) {super ();
        THIS.name = name;
    This.classurl = Classurl;
        Public Action (string name, String Classurl, String method) {super ();
        THIS.name = name;
        This.classurl = Classurl;
    This.method = method;
    }//get, set method public String GetName () {return name;
    } public void SetName (String name) {this.name = name;
    } public String Getclassurl () {return classurl;
    } public void Setclassurl (String classurl) {this.classurl = Classurl;
    } public String GetMethod () {return method;
     } public void Setmethod (String method) {   This.method = method;
    } public map<string, Result> Getresultmap () {return resultmap;
    } public void Setresultmap (map<string, result> resultmap) {this.resultmap = Resultmap;
 }
}

2, Result.java

public class Result {//property declaration private String Name= "success";

    private string Type= "dispatcher";//default property private string location;
        Construction method Public result () {} public result (String location) {super ();
    this.location = location;
        Public Result (String type, string location) {super ();
        This.type = type;
    this.location = location;
        Public Result (string name, String type, string location) {this.name = name;
        This.type = type;
    this.location = location;
    }//get, set method public String GetName () {return name;
    } public void SetName (String name) {this.name = name;
    } public String GetType () {return type;
    The public void SetType (String type) {this.type = type;
    } public String GetLocation () {return location;
    } public void setlocation (String location) {this.location = location;
 }
}

3, Actionmapper.java (read the file here with dom4j)

public class Actionmapper {//action container public static map<string, action> actionmap=new Hashmap<string,ac

    Tion> (); Parse profile public static void Parser () throws documentexception{//Read configuration file Framework.xml InputStream input
        Stream=actionmapper.class.getclassloader (). getResourceAsStream ("Framework.xml");
        Document document=new Saxreader (). read (InputStream);
        Gets the root element object of an element root=document.getrootelement ();
        System.out.println (Root.getname ());
        Gets the Action object list<element> listaction=root.elements ();
            for (Element itemaction:listaction) {Action action=new action ();
            Gets the Action property Action.setname (Itemaction.attributevalue ("name"));
            Action.setclassurl (Itemaction.attributevalue ("class"));
            String Method=itemaction.attributevalue ("method");
            if (method!=null) {Action.setmethod (method); }
            //Get Result object list<element> listresult=itemaction.elements ();
                for (Element itemresult:listresult) {result result=new result ();
                Gets the result property of String Nameresult=itemresult.attributevalue ("name");
                if (nameresult!=null) {result.setname (Nameresult);
                } String Typeresult=itemresult.attributevalue ("type");
                if (typeresult!=null) {result.settype (Typeresult);
                } result.setlocation (Itemresult.getstringvalue ());
            Adds a result object to the Action object Action.getresultmap (). Put (Result.getname (), result);
        }//Add the Action object to the ActionMap object Actionmap.put (Action.getname (), action);
 }
    }
}

4, create Com.filter package (Corefilter Class)
1, Corefilter.java (here is the key core, it's hard to fathom t.t)

public class Corefilter implements filter{@Override public void Destroy () {//TODO auto-generated method stub} @Override public void init (Filterconfig arg0) throws Servletexception {try {//parse config file is placed here (this method only

        Line once) Actionmapper.parser ();
        } catch (Documentexception e) {//TODO auto-generated catch block E.printstacktrace (); }}//Processing transactions are in DoFilter @Override public void DoFilter (ServletRequest request, servletresponse response, Fi Lterchain Filterchain) throws IOException, servletexception {httpservletrequest httprequst= (HttpServ
        letrequest) Request;
        HttpServletResponse httpresponse= (httpservletresponse) response;
        I blindly set the transcoding, currently can only pass the regular string httprequst.setcharacterencoding ("Utf-8");

Httpresponse.setcharacterencoding ("Utf-8");
        The following 5 steps are divided into separate methods to eat//1, map the request to Action action targetaction=reqtoaction (Httprequst); if (targetaction==null{//Skip Filterchain.dofilter (Request, response) if it is not an action request;
        return;
        }//system.out.println (Targetaction.getname () + "---" +targetaction.getclass ());
            try {//2, create action Object proxyaction=createproxyaction (Targetaction.getclassurl ());//3, set user-submitted property to action
SetProperty (Httprequst, proxyaction);
4. Execute Action String Resultname=execute (Proxyaction,targetaction.getmethod ());
            5, processing result result Result=targetaction.getresultmap (). get (Resultname);
        Resultexecute (httprequst,httpresponse,result,proxyaction);
        } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
        }}//Map request to Action Public action reqtoaction (HttpServletRequest HttpRequest) {//Get URL delivery request name
        String Path=httprequest.getrequesturi ();
            if (!path.endswith (". Action")) {//tests whether this string ends with the specified suffix.
        return null;
     }   System.out.println (Path.tostring ()); String reqname=path.substring (Path.lastindexof ("/") +1,path.lastindexof ("."));
        /Intercept Request name//SYSTEM.OUT.PRINTLN (reqname);
    Return ActionMapper.actionMap.get (Reqname); }//Create action public Object createproxyaction (String className) throws Exception {Class Clzz=class.forname
        (ClassName);
    return Clzz.newinstance ();
        }//Set user-submitted property to action on public void SetProperty (HttpServletRequest httprequst,object action) throws Exception {
        Create a Class class Clzz=action.getclass ();
        Map Parametermap=httprequst.getparametermap (); for (Iterator Iterator = Parametermap.keyset (). Iterator (); Iterator.hasnext ();)
            {Object key=iterator.next (); Find Field field Field=clzz.getdeclaredfield (Key.tostring ()) According to the submission parameters;//Returns the object of the specified field in this class if (Field==null)
            {continue;
            } field.setaccessible (True); Field.set(Action, Httprequst.getparameter (Key.tostring ()));
        System.out.println (key+ "-----" +httprequst.getparameter (key.tostring ())); }}//execute action Private String execute (Object proxyaction, String methodName) throws exception{Class
        Clzz=proxyaction.getclass ();
        Method Method=clzz.getdeclaredmethod (methodName);
    Return (String) Method.invoke (proxyaction); }//Processing result private void Resultexecute (HttpServletRequest httprequst, httpservletresponse httpresponse, result re Sult, Object proxyaction) throws Exception {if (Result.gettype () equals ("redirect")) {HT
            Tpresponse.sendredirect (Result.getlocation ());
        Return
        }//Set the action's property value to Httprequst's attribute Class clzz=proxyaction.getclass ();
        Field[] Fields=clzz.getdeclaredfields ();
            for (Field field:fields) {field.setaccessible (true); Httprequst.setattribute (Field.getname (), FIeld.get (proxyaction));
        Field.setaccessible (FALSE);
    } httprequst.getrequestdispatcher (Result.getlocation ()). Forward (Httprequst, HttpResponse);
 }
}

JSP page
1, login.jsp

    <form action= "Login.action" method= "POST" >
        account <input type= "text" name= "name" ><br>
        Password < Input type= "text" name= "pwd" ><br>
        <input type= "Submit" value= "Login" ><br>
    </form>

2, success.jsp

    

test Case Loginaction.java

public class Loginaction extends Actionsupport {

    private String name;
    Private String pwd;

    @Override public
    String execute () throws Exception {
        if (name.equals ("admin") &&pwd.equals ("000") {
            return SUCCESS;
        }
        return LOGIN;
    }

    Public String GetName () {
        return name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    Public String getpwd () {
        return pwd;
    }

    public void SetPwd (String pwd) {
        this.pwd = pwd;
    }
}

Effect Diagram

That's about it, stuts2.

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.