"SSH Advanced path" Step by step refactoring MVC to implement struts framework--completely remove the logic judgment (v)

Source: Internet
Author: User
Tags xml parser

Directory:

"SSH advanced Route" Struts Fundamentals + Implementation Simple Login (ii)

SSH Step-by-step refactoring MVC implementation struts framework-starting with a simple MVC (iii)

"SSH Advanced path" Step by step refactoring MVC implementation Struts framework-package business logic and jump Path (iv)

"SSH Advanced path" Step by step refactoring MVC to implement struts framework--completely remove the logic judgment (v)

"SSH Advanced path" Step by step refactoring MVC implementation struts framework-perfect Steering page, done (vi)

Struts ' second blog "SSH Advanced path" struts Fundamentals + Simple Login (b), we introduced the MVC model and the basic theory of struts, and compared them to learn the connection and the difference between them. From the third blog "SSH Advanced Path" step-by-step refactoring MVC implementation of struts framework-starting with a simple MVC (c), we implemented a simple MVC model and proposed three refactoring problems.

Previous Blog post "SSH Advanced path" Step by step refactoring MVC implementation Struts framework-package business logic and jump Path (iv) , we solved the first problem: encapsulating the business logic and the jump path. This blog we solve the second problem: Completely remove the logical judgment in the servlet.


Let's take a look at the Testservlet code in the previous blog:

Package Com.liang.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.liang.action.action;import com.liang.action.AddUserAction; Import Com.liang.action.deluseraction;import Com.liang.action.modifyuseraction;import com.liang.action.queryuseraction;/** * Use servlet to do related control, turn to multiple (V) view * @author Liang * */public class Testservlet extends Htt Pservlet {@Overrideprotected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//Get access to uristring Reqeuesturi = Request.getrequesturi (); System.out.println (Reqeuesturi);//intercept URI, get path string = reqeuesturi.substring (Reqeuesturi.indexof ("/", 1), Reqeuesturi.indexof (".")); SYSTEM.OUT.PRINTLN (path); Action action = null;//equals Add, call adduseractionif ("/servlet/adduser". Equals (Path)) {action = new adduseraction ();//equals Delete, Call Deluseraction}else if ("/servlet/delUser ". Equals (path) {action = new deluseraction ();//equals modify, call Modifyuseraction}else if ("/servlet/modifyuser ". Equals ( Path) {action = new modifyuseraction ();//equals query, call Queryuseraction}else if ("/servlet/queryuser". Equals (Path)) {action = New Queryuseraction ();} else {throw new RuntimeException ("request Failed");} String forward = null;//Returns a different steering page try {forward = Action.execute (request, response);} catch (Exception e) {E.printstacktrac E ();} Complete the steering Request.getrequestdispatcher (forward) according to the path. Forward (request, response); @Overrideprotected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget (request,response);}}
 

To analyze the code in the above Testservlet, we have found multiple logic to determine if. ELSE, the system is not flexible, when demand changes, violates the development of the closure principle, can not meet the demand. We know that when we configure connection database information, we make the database more flexible and use a configuration file.

We also intend to configure all the strings and the implementation classes of the business logic into the configuration file, and finally go to the corresponding page by implementing the method of the class to return to the jump path. Modify the configuration file when the requirements change.

So the configuration file is not only to match the string appearing in the servlet, but also to configure the implementation class of the corresponding action interface (we can use reflection to dynamically instantiate the class object, and then use the polymorphic mechanism to dynamically change all the properties and methods of the Class), and return the jump path string. In fact, at this point and the struts configuration file is consistent, we only need to implement a configuration file ourselves.


Web. XML, we configure Struts-config.xml to initialize when Tomacat is started

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <welcome-file-list> <welcome-file>index.jsp</ Welcome-file> </welcome-file-list> <!--configuration Testservlet class--<servlet><servlet-name> testservlet</servlet-name><!--configured as the path to the testservlet you wrote--><servlet-class> com.liang.servlet.testservlet</servlet-class><!--Tomacat is started, the configuration of Struts-config.xml is initialized-->< init-param><param-name>config</param-name><param-value>/web-inf/struts-config.xml</ Param-value></init-param><load-on-startup>0</load-on-startup></servlet> <!-- How to access the path of an action with JSP-<servlet-mapping> <servlet-name>TestServlet</servlet-name> <!-- As long as the. Do request arrives at the servlet--> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>

Com.liang.servlet.TestServlet, is our core servlet.


Struts-config.xml, configure the path path and the action's implementation class as a map structure

<?xml version= "1.0" encoding= "UTF-8"?><action-config><action-mappings><!--according to different path path, Access the respective action  --><action path= "/servlet/deluser" type= "Com.liang.action.DelUserAction" ></action ><action path= "/servlet/adduser" type= "com.liang.action.AddUserAction" ></action><action path= "/ Servlet/modifyuser "type=" com.liang.action.ModifyUserAction "></action><action path="/servlet/ Queryuser "type=" Com.liang.action.QueryUserAction "></action></action-mappings></action-config >

Below we only need to read the configuration file to implement the corresponding function. One of the most popular ways to read XML is to use DOM4J, where we have also implemented the example of dom4j reading XML, but after using dom4j to read the configuration file, we need to place the information where, without a doubt, we need a class for the map structure, Information for storing the path information and the Action implementation class (type), which requires a minimum of two parameters, as follows:

Actionmapping

Package Com.liang.action;public class Actionmapping {//path information private string Path;//action implementation class information private string Type;public String GetType () {return type;} public void SetType (String type) {this.type = type;} Public String GetPath () {return path;} public void SetPath (String path) {this.path = path;}}

configuration information, we have put in a map, at this time a request, we need to follow the testservlet in the above if statement, according to the intercepted URL request, to the map to obtain the corresponding action of the request to take out, but the action has multiple, We also need a map structure that distinguishes which action the URL request corresponds to at this point. So at this point we also need a map structure to store the action. (If you don't understand, it's OK, the following code has comments that can help you)

Mappings

Package Com.liang.action;import Java.util.hashmap;import Java.util.map;public class Mappings {public static MAP actions = new HashMap ();  }

at this point, we have finished the preparation, we need to use DOM4J read the configuration file, stored in the corresponding map structure.


Configinit

Struts-config.xml parser. To save the parsed node to actionmapping, Mappingaction is a class that we have encapsulated above. How to parse to see the code:

Package Com.liang.servlet;import Java.io.file;import Java.util.iterator;import org.dom4j.document;import Org.dom4j.element;import org.dom4j.io.saxreader;import com.liang.action.*;p ublic class ConfigInit {public static void Init (String config) {//Create Saxreader object Saxreader reader = new Saxreader (); File F = new file (config), try {//Read the XML file through the Read method, convert to Document Object doc = Reader.read (f);//Get the root node of the configuration file element root = Doc.getrootelement (); Element actionmappings = (Element) root.element ("action-mappings");//Parse all parameters for the action node for (Iterator j = Actionmappings.elementiterator ("action"); J.hasnext ();) {element am = (Element) J.next (); actionmapping actionmapping = new actionmapping ();//set path and Typeactionmapping.setpath for Actionmapping ( Am.attributevalue ("path")); Actionmapping.settype (Am.attributevalue ("type"));/* * The following Mappings.actions storage structure corresponds to the configuration file Struts-config.xml with mapping one by one * Map.put ("/servlet/deluser", actionmapping); * Map.put ("/servlet/adduser", actionmapping); * Map.put ("/servlet/modifyuser", Actionmapping); * Map.put ("/servlet/queryuser", actionmapping); */mappings.actions.put (String) am.attributevalue ("path"), actionmapping);}} catch (Exception e) {e.printstacktrace ();}}}


Finally, everything has a bad wind, we look at the most critical class Testservlet.

in fact, it is a common servlet. Through the map of the above Web. XML, as long as the. Do access is first filtered to the action you want to access. Because the servlet's load-on-startup is set to 0, the Init method is executed when Tomcat starts. The Configinit class is my struts-config.xml parser.

Testservlet

Package Com.liang.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.liang.action.action;import com.liang.action.ActionMapping; Import com.liang.action.mappings;/** * Use servlet to do related control, turn to multiple (V) view * @author Liang * */public class Testservlet extends Http Servlet {//required read filename protected static String config = "/web-inf/struts-config.xml";p ublic void Init () throws servletexception {//Get the path to the file//initialize ();//Obtain the true path of the file in the corresponding server by the directory mapped in Web. config = Getservletcontext (). Getrealpath ("/") + getinitparameter ("config");//parse Struts-config.xml configuration file Configinit.init (config);} Obtain the true path of the file in the corresponding server according to the directory mapped in Web.//private void Initialize () {//try {//config = Getservletcontext (). Getrealpath ("/") + getinitparameter ("config"),//} catch (Exception e) {//e.printstacktrace ();//}//} @Overrideprotected void Doget ( HttpServletRequest request, HttpServletResponse RespoNSE) throws Servletexception, IOException {//Get access to uristring Reqeuesturi = Request.getrequesturi ();//intercept URI, get path string Path = reqeuesturi.substring (Reqeuesturi.indexof ("/", 1), Reqeuesturi.indexof (".")); Mappings mapings = new Mappings ()//Based on the intercepted URL request, the action class actionmapping actionmapping = (actionmapping) corresponding to the request in the map is obtained.  Mapings.actions.get (path); Gets the full path of the action class corresponding to this request string type = Actionmapping.gettype (); COM.LIANG.ACTION.DELUSERACTION//uses reflection to dynamically instantiate actiontry {action action = (action) class.forname (type). newinstance (); /use polymorphic mechanism, dynamically invoke the Execute method in action, return to the steering path string forward = Action.execute (request, response);// Complete the steering Request.getrequestdispatcher (forward) according to the steering path. Forward (request, response);} catch (Instantiationexception e) {e.printstacktrace ();} catch (Illegalaccessexception e) {e.printstacktrace ();} catch (   ClassNotFoundException e) {e.printstacktrace ();} catch (Exception e) {e.printstacktrace ();} } @Overrideprotected void DoPost (HttpServletRequest request, httpservletresponse response) throws ServletException, IOException {doget (request,response);}} 


The Action implementation Class code, I only paste one add user, no other classes are changed, and the code is no longer duplicated.

Adduseraction

Package Com.liang.action;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.liang.servlet.usermanager;public class AddUserAction implements Action {@Overridepublic string execute (httpservletrequest req, HttpServletResponse resp) throws Exception {//Get parameter string Username = Req.getparameter ("username"); Usermanager Usermanager = new Usermanager ();//Call Business logic Usermanager.add (username);//Return to jump page return "/add_success.jsp";// The steering path can be read through the configuration file}}

Now we find all the If ... in Testservlet. Else statements are gone, and there is no business logic implementation class, more interface-oriented development, at this time our system is very flexible, but in order to better realize the prototype of the struts framework, we put forward a third problem, as shown in the code above, all the steering page is written dead, We need to show and control the separation, and if you want to change the view, modify the code of the action implementation class.

So far, we have achieved a prototype of the struts framework, just not yet perfect, the next blog, we continue to refine all the steering pages that will show and control the separation. Next Blog "SSH Advanced Path" step-by-step refactoring MVC implementation struts framework-perfect steering page, display and control separation (vi).


SOURCE download



"SSH Advanced path" Step by step refactoring MVC to implement struts framework--completely remove the logic judgment (v)

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.