One: struts2 operating mechanism:
When Tomcat starts, some information is already loaded, such as those strut.xml loaded by Strutsprepareandexecutefilter and the class file for the action
1) The client enters a URL address in the browser, such as Http://localhost:8080/user!findUser.do.
2) This URL request is sent to Tomcat via the HTTP protocol.
3) Tomcat finds the Web. xml file within the corresponding project according to the URL.
4) A STRUTS2 configuration will be found in Web. Xml.
5) You will then find the corresponding Struts.xml configuration file for the struts2.
6) The corresponding class will be found by parsing the Struts.xml configuration file according to the URL.
7) After calling the class to return a string, return to the corresponding JSP according to Struts.xml.
Two: Struts2 operation principle (network excerpt)
The image above is from the official site of Struts2, which is the overall structure of struts 2.
The processing of a request in the STRUTS2 framework is roughly divided into the following steps:
1) The client initializes a request to the servlet container (for example, Tomcat).
2) This request passes through a series of filters (filter).
3) Then Filterdispatcher is called, Filterdispatcher asks Actionmapper to decide if it needs to invoke an action.
4) If Actionmapper decides to call a action,filterdispatcher to give actionproxy the processing of the request.
5) Actionproxy The config file of the framework through Configuration Manager to find the action class that needs to be called.
6) Actionproxy Create an instance of Actioninvocation.
7) The Actioninvocation instance is invoked using a naming pattern that involves a call to the relevant interceptor (Intercepter) before and after the action is invoked.
8) Once the action is executed, Actioninvocation is responsible for finding the corresponding return result based on the configuration in the Struts.xml.
The core of STRUTS2 is the interceptor. All the package in Struts.xml is extends= "Struts-default". Similarly, all Java classes are extends from object. Struts-default.xml inside is to do the above things.
Three: Below with everyone to customize the simple implementation of STRUTS2
1. Create a file containing the parsed struts and save the name and class as well as the map collection of result results
Package Com.s.bean;
Import Java.util.HashMap;
Import Java.util.Map;
public class Actionxml {
//corresponds to the stored name
private String name;
The corresponding class
private String clazz;
Corresponding to those stored result, save Resultxml Bean result
private MAP results = new HashMap ();
Public String GetName () {
return name;
}
public void SetName (String name) {
this.name = name;
}
Public String Getclazz () {
return clazz;
}
public void Setclazz (String clazz) {
this.clazz = clazz;
}
Public Map GetResults () {
return results;
}
public void SetResults (Map results) {
this.results = results;
}
}
2. Create a file that holds the parse struts and save the result file information
Package Com.s.bean;
public class Resultxml {
//name
private String name;
Value
private String value;
Public String GetName () {
return name;
}
public void SetName (String name) {
this.name = name;
}
Public String GetValue () {
return value;
}
public void SetValue (String value) {
this.value = value;
}
}
3. Create a class file that parses the XML
Package com.s.parse;
Import Java.io.File;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import org.dom4j.Element;
Import Org.dom4j.io.SAXReader;
Import Com.s.bean.actionxml;
Import Com.s.bean.resultxml;
public class Parsexml {private static map<string,actionxml> Map = new hashmap<string,actionxml> ();
Public Parsexml () {} public static map<string,actionxml> GetXML () {saxreader sax = new Saxreader ();
Document doc = null;
try {doc = Sax.read (Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream ("Struts.xml"));
} catch (Documentexception e) {//TODO auto-generated catch block E.printstacktrace ();
}//Get root of Element root = Doc.getrootelement ();
Get all action configuration list List = Root.elements ();
for (Object obj:list) {actionxml ax = new Actionxml ();
Element a = (element) obj;
Ax.setname (A.attributevalue ("name")); Ax.setClazz (A.attributevalue ("class"));
Get all result List results = a.elements ();
for (Object obj1:results) {resultxml rx = new Resultxml ();
Element r = (element) obj1;
Rx.setname (R.attributevalue ("name"));
Rx.setvalue (R.gettext ());
Ax.getresults (). Put (Rx.getname (), Rx.getvalue ());
}//The configuration of all actions is read out and put into a map map.put (Ax.getname (), Ax);
} return map; }/** * @param args */public static void main (string[] args) {//TODO auto-generated method stub Parsexml
. GetXML ();
}
}
4, create a filter, after Tomcat starts, the file in Struts.xml is parsed, and the corresponding class file entity is created, using reflection, equivalent to Filterdispatcher in struts2
Package com.s.filter;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.lang.reflect.InvocationTargetException;
Import Java.util.Map;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import com.s.bean.action;
Import Com.s.bean.actionxml;
Import Com.s.parse.parsexml;
Import Com.sun.org.apache.commons.beanutils.BeanUtils;
public class Dispatherfilter implements Filter {//specially configured map private static map<string,actionxml> map; public void DoFilter (ServletRequest arg0, Servletresponse arg1, Filterchain arg2) throws IOException, Servletexception
{//TODO auto-generated method stub httpservletrequest request = (httpservletrequest) arg0; Get the name of the form request, such as a StRing ActionName = Request.getrequesturi (). Split ("/") [2].split ("\ \")
[0];
The root of the form request finds the corresponding processing class Actionxml ax = Map.get (actionname);
String clazz = Ax.getclazz ();
String result = "";
try {Class cla = Class.forName (clazz); Object obj = Cla.newinstance ();//root clazz produces the object that receives and processes the data//the data in the form is given to the obj beanutils.populate (obj, request.getparamete
RMap ());
Action action = (action) obj; result = Action.execute ();//Execute method to get result//ROOT to find the corresponding interface to jump String resultpage = (string) ax.getresults (). Get (ResU
LT);
Root results page Jump Request.getrequestdispatcher (resultpage). Forward (arg0, arg1);
} catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
} catch (Instantiationexception e) {//TODO auto-generated catch block E.printstacktrace ();
} catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();
} catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace (); }} public void Destroy () {//TODO auto-generated method stubs} public void init (Filterconfig arg0) throws
servletexception {//TODO auto-generated method Stub map = Parsexml.getxml ();//Read Config}}
4. Define an Action interface class with only one Execute method
Package Com.s.bean;
Public interface Action {public
String execute ();
}
In this way, a small framework is completed, which contains the parsing of the Struts.xml file after Tomcat starts, and the entity of the action class, so that we can navigate the framework flexibly as long as we define our action implementation class and join our struts.xml.
5. Define Struts.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<struts>
<action name= "a" class= "Com.s.bean.users" >
<result name= ' success ' >/success.jsp</result>
<result name= ' fail ' >/fail.jsp</ result>
<result name= ' OK ' >/ok.jsp</result>
</action>
</struts>
6. Define the implementation class of our action
Package Com.s.bean;
Import java.io.Serializable;
public class Users implements serializable,action{
/**
* */
private static final long Serialversionuid = -4293478837686410970l;
private int uid;
Private String uname;
Private String upwd;
public int Getuid () {
return uid;
}
public void SetUid (int uid) {
this.uid = uid;
}
Public String Getuname () {
return uname;
}
public void Setuname (String uname) {
this.uname = uname;
}
Public String getupwd () {
return upwd;
}
public void Setupwd (String upwd) {
this.upwd = upwd;
}
method to process the data public
String execute () {
//operate the database here
if (uname.equals ("admin")) {
return "fail";
} else{
return "Success";}}
}
7, test the page, or use a hyperlink to test: http://localhost:8080/a.do?uname=aaa&upwd=bbb:
<form action= "a.do" method= "POST" >
username:<input type= "text" name= "uname"/><br>
Password:<input type= "text" name= "upwd"/><br>
<input type= "Submit" value= "Submit"/>
</ Form>
Analytical:
Tomcat is started, the Init method in Dispatherfilter is executed, the Struts.xml file is parsed, and the corresponding information is stored in the map of the global variable
When the user accesses http://localhost:8080/a.do?uname=aaa&upwd=bbb via hyperlinks, it is transferred to Dispatherfilter, Parse Hyperlink Request.getrequesturi () by Dispatherfilter. Split ("/") [2].split ("\ \") [0];, get name names in action, and then through the Parsexml class to get the corresponding class class, and then use the reflection mechanism to create its entity, the system by default executes the Execute method inside, get the corresponding string information, based on the returned string information, Find the corresponding result page by parsing the XML, and then pass Request.getrequestdispatcher (Resultpage). Forward (arg0, arg1); jump to the corresponding page to get the corresponding result
In combination with the struts2 principle, we find that the Filterdispatcher in Struts2 is quite the same as our custom dispatherfilter, and the actionmapper inside is our own definition of the global variable map, As for the actionproxy in Struts2, as well as the configuration Manager,actioninvocation and (Intercepter) We are not involved here, the user can be implemented in turn, Here is just a simple implementation of the principle of struts2, only for learning reference.
Source code Download: http://download.csdn.net/detail/harderxin/5229826