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

Source: Internet
Author: User

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)


Fourth blog "SSH Advanced path" Step by step refactoring MVC implementation struts framework-encapsulating business logic and jump Path (iv), we solved the first problem: encapsulating the business logic and the jump path. Fifth blog "SSH Advanced path" Step by step refactoring MVC to implement struts framework--completely remove the logic judgment in the servlet (v), we solve the second problem: Completely remove the logical judgment in the servlet. In this article we solve the last problem, perfect the Turn page, show and control the separation.


For example, adding user logic, success can not only return to Success page, failure can also return to the failure page, the code is as follows:


Adduseraction

Package Com.liang.action;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.liang.manager.usermanager;public class AddUserAction implements Action {@Overridepublic string execute (httpservletrequest req, HttpServletResponse resp) throws Exception {//Get parameter string Username = Req.getparameter ("username");//Invoke business logic Usermanager Usermanager = new Usermanager (); try{// Added business logic usermanager.add (username);} catch (Exception e) {//Returns Add failed interface return "/add_error.jsp";//The steering path can be read through the configuration file}//return to add a successful interface return "/add_success.jsp"; The steering path can be read through the configuration file}}

from the previous blog, we know that if you want the system to become flexible, all changes are configured in the configuration file, modify the configuration file can be modified. Therefore, we only need to configure the steering page in Struts-config.xml, not only to have a successful steering page, but also to have a failed turn page.


Let's change it . Struts-config.xml, the code is as follows:

<?xml version= "1.0" encoding= "UTF-8"?><action-config><action-mappings> <!--according to different path path, Access the respective action--<action path= "/servlet/adduser" type= "com.liang.action.AddUserAction" ><!--Steering page-- <forward name= "Success" Path= "/add_success.jsp" ></forward><forward name= "error" path= "/add_ error.jsp "></forward></action><action path="/servlet/deluser "type=" Com.liang.action.DelUserAction "><forward name=" Success "Path="/del_success.jsp "></forward>< Forward name= "error" path= "/del_error.jsp" ></forward></action><action path= "/servlet/modifyuser "Type=" com.liang.action.ModifyUserAction "><forward name=" Success "Path="/modify_success.jsp "></ Forward><forward name= "error" path= "/modify_error.jsp" ></forward></action><action path= "/ Servlet/queryuser "type=" com.liang.action.QueryUserAction "><forward name=" Success "Path="/query_success.jsp ">/</forward><forWard name= "error" path= "/query_error.jsp" ></forward></action></action-mappings></ Action-config>

We modify the configuration file, use DOM4J to read the configuration, and the configuration information needs to be placed in a map structure, we need a map to store the steering information, so add a map to the actionmapping.


Actionmapping

Package Com.liang.action;import Java.util.hashmap;import Java.util.map;public class Actionmapping {private String path ;p rivate String type;//Store steering information mapmap forward = new HashMap ();p ublic Map Getforward () {return forward;} public void Setforward (Map forward) {this.forward = forward;} 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;}}

the read configuration needs to change, but we have an example of the previous blog post, which is not difficult to modify.

Configinit

Package Com.liang.servlet;import Java.io.file;import Java.util.hashmap;import java.util.iterator;import Java.util.map;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")); Map forward = new HashMap ();//Parse all parameters for the forward node for (Iterator k = Am.elementiterator ("forward"), K.hasnext ();) {element fo = (element) k.next (); ForwaRd.put (String) fo.attributevalue ("name"), (String) fo.attributevalue ("path");} Set forward//If add actionmapping is stored as follows;/* * actionmapping{path= "/servlet/adduser"; * type= " Com.liang.action.AddUserAction "<span style=" White-space:pre "></span> *forwardmap{* <span style=" White-space:pre "></span>key=" Success ", value="/add_success.jsp "* <span style=" White-space:pre "> </span>key= "Error", value= "/add_error.jsp"} <span style= "White-space:pre" ></span> *} */ Actionmapping.setforward (forward); */* The storage structure above mappings.actions corresponds to mapping configuration information to map 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 ();}}}

our Testservlet only need to add one sentence, as follows:


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 the steering path string result = Action.execute (request, response);//Get real Turn page string forward = ( String) Actionmapping.getforward (). Get (Result), or//Turn request.getrequestdispatcher (forward) to complete 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);}}


Finally, let's look at the adduseraction has become very flexible.

Package Com.liang.action;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.liang.manager.usermanager;public class AddUserAction implements Action {@Overridepublic string execute (httpservletrequest req, HttpServletResponse resp) throws Exception {//Get parameter string Username = Req.getparameter ("username");//Invoke business logic Usermanager Usermanager = new Usermanager (); try{// Added business logic usermanager.add (username);} catch (Exception e) {//Returns Add failed interface return "error";//and configuration file configuration consistent}//return add successful interface return "success";//and configuration file configuration consistent}}


If we want to change the view, we just need to modify a configuration file. Let's review the course of our refactoring and encapsulation with a class diagram.


so far, we've done all the steps to refactor MVC to implement the struts framework. It is not difficult to find, in fact, the framework is not difficult, just a look at the special mystery, when we step-by-step reconstruction, continuous encapsulation, continuous improvement, the embryonic form of struts has been shown in front of us. The framework is the encapsulation of the height of the abstraction of the height of.

Of course, since it is a prototype there is absolutely imperfect place, for example, we do not like struts encapsulated actionform, automatic completion of data type conversion, of course, we can from now on the basis of further improvement, but we do not go down, we understand its basic idea is good, Besides, we have more difficult tasks behind us.

After several blog refactoring, we realized a struts prototype, it can let us know the similarities and differences between the MVC and struts, as well as the package process of struts, we have more depth of struts buried the foreshadowing. The next blog "SSH Advanced Road" struts detailed implementation process, in-depth struts (vii), through learning the struts process, further into struts. See the next blog post!



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

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.