Struts principle and application (3)

zhaozj2021-02-11  180

Chapter 5: Struts Work Flow

Struts PrinciPle and Practice

The above figure is the workflow of Struts. We mentioned before, all requests are submitted to the ActionServlet.

ActionServlet is a FrontController that is a standard servlet, which forwards request to RequestProcessor,

Actionmapping is a subclass of ActionConfig, essentially a map of Struts-Config.xml, which can get all configuration information from it.

RequestProcessor Gets the appropriate actionforn and action from ActionMapping based on the submitted URL, such as * .do. Then correspond to the parameters of the Request to ActionForm, perform Form verification. If verification is called an action () method () method to perform an action, eventually returns ActionFoward.

ActionFoward is a packaging of a foward in mapping, corresponding to a URL

Actionform uses viewhelper mode and is a package for Form in HTML. It includes a validate method for verifying the effectiveness of the FORM data. ActionForm is a class that meets the JavaBean specification, all attributes should meet GET and SET. For some complex systems, DynaActionForm can also be used to construct a dynamic Form, which is generated by a prefabricated parameter. This makes a more flexible extension program.

ActionerRORS is a packaging for error messages, once an exception occurs in execution or form.validate, you can generate an actionerror and eventually add to ActionerRors. During the Form verification, if there is ERROR, the page will be re-directed to the input page, and the error is prompted.

Action is the REQUSESTHANDLER for performing business logic. Each Action only establishes an instance. Action is not a thread safe, so you should not access specific resources in the action. In general, the business delegate mode should be changed to access the business tier to unprepose.

Struts provides a variety of Action for selection. Ordinary Action can only perform a task by calling Execute, and DispatchAction can be performed according to the configuration parameters, not only enter the execute () function, which can perform a variety of tasks. Such as INSERT, UPDATE, etc. The LookUpdispatchaction can perform a function according to the name of the submitting form button.

We can go back to the examples just now, understand the Struts process.

Let's take a look at the EXAMPLE example of Struts:

Chapter 6: Example 2: Login Application Struts PrinciPle And Practice Description: The example 2 is the Struts comes with the example program that implements a large number of Struts Taglibs in the login, registration, and modify the function code, and use the Validator plugin for Form verification but the code Establish a bad example, that is, write a lot of business logic in an action. Part of the code is as follows: Logon.jsp

<% @ page contenttype = "text / html; charset = uTF-8" Language = "java"%>

// Declare taglib <% @ taglib URI = "/ Web-inf / struts-bean.tld" prefix = "bean"%>

<% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%>

// bean is used to read I18n information from ApplicationResource

<bean: message key = "logon.title" /> </ title></p> <p><HTML: BASE /></p> <p></ hEAD></p> <p><body bgcolor = "white"></p> <p>// Error message section</p> <p><html: errors /></p> <p>// Log in to Form, Action is logion.do</p> <p><html: form action = "/ logon" FOCUS = "username"</p> <p>οnsubmit = "Return Validatelogonform (this);"></p> <p><Table Border = "0" width = "100%"></p> <p><tr></p> <p><TH align = "Right"></p> <p><bean: message key = "prompt.username" />:</p> <p></ tH></p> <p><TD align = "left"></p> <p><html: text property = "username" size = "16" maxlength = "18" /></p> <p></ td></p> <p></ TR></p> <p><tr></p> <p><TH align = "Right"></p> <p><bean: message key = "prompt.password" bundle = "alternate" />:</p> <p></ tH></p> <p><TD align = "left"></p> <p><html: password property = "password" size = "16" maxlength = "18"</p> <p>REDISPLAY = "false" /></p> <p></ td></p> <p></ TR></p> <p><tr></p> <p><TD align = "right"></p> <p><html: Submit value = "submit" /></p> <p></ td></p> <p><TD align = "left"></p> <p><html: reset /></p> <p></ td></p> <p></ TR></p> <p></ TABLE></p> <p></ html: form></p> <p>// Validator plugin for Form verification</p> <p><HTML: JavaScript Formname = "LogonForm"</p> <p>DynamicjavaScript = "true"</p> <p>StaticjavaScript = "false" /></p> <p><script language = "javascript1.1" src = "staticjavascript.jsp"> </ script> </ body></p> <p></ html: html></p> <p>Struts-config.xml configuration <form-beans></p> <p><! - logon form bean -></p> <p><form-bean name = "logonform"</p> <p>Type = "org.apache.struts.validator.dynavalidatorform"></p> <p><form-protety name = "username" type = "java.lang.string" /></p> <p><form-proty = "password" type = "java.lang.string" /></p> <p></ form-bean></p> <p><! - Subscription Form Bean -></p> <p><form-bean name = "subscriptionform"</p> <p>Type = "org.apache.struts.Webapp.example.subscriptionform" /></p> <p></ form-beans></p> <p><action-mappings></p> <p><! - Edit Mail Subscription -></p> <p><action path = "/ editscription"</p> <p>Type = "org.apache.struts.Webapp.Example.editsubscriptionaction"</p> <p>Attribute = "subscriptionform"</p> <p>Scope = "request"</p> <p>Validate = "false"></p> <p><forward name = "failure" Path = "/ mainmenu.jsp" /></p> <p><forward name = "success" Path = "/ subscription.jsp" /></p> <p></ action></p> <p>...</p> <p>SubscriptionForm is a standard Actionform, where the RESET method is used to clear the value of the FORM, and the Validate method is used to verify the public final class subscriptionform extends actionform {</p> <p>// The Maintenance Action We are Performing (CREATE OR).</p> <p>Private string anction = "create";</p> <p>// SHOULD WE Auto-Connect At Startup Time?</p> <p>Private Boolean AutoConnect = FALSE</p> <p>// The host name.</p> <p>Private string host = null;</p> <p>Private string password = null;</p> <p>PRIVATE STRING TYPE = NULL;</p> <p>Private string username = null;</p> <p>Public string getAction () {return (this.action);} public void setAction (string action) {this.action = action;}</p> <p>Public boolean getautoconnect () {returnnect;}</p> <p>Public void setAutoconnect (boolean autoconnect) {this.autoconnect = autoconnect;</p> <p>Public String gethost () {return (this.host);</p> <p>Public void sethost (string host) {this.host = host;}</p> <p>Public string getpassword () {return (this.password);</p> <p>Public void setpassword (string password) {this.password = password;}</p> <p>Public string gettype () {return (this.type);</p> <p>Public void settype (string type) {this.type = type;}</p> <p>Public String getUsername () {return (this.username);</p> <p>Public void setusername (string username) {this.username = usrname;}</p> <p>/ **</p> <p>* RESET All Properties to Their Default VALUES.</p> <p>*</p> <p>* @Param mapping the mapping use to select this instance</p> <p>* @Param Request The Servlet Request WE Are Processing</p> <p>* /</p> <p>Public void reset (actionMapping mapping, httpservletRequest request) {</p> <p>THIS.Action = "CREATE";</p> <p>THIS.AUTOCONNECT = FALSE;</p> <p>THIS.HOST = NULL;</p> <p>This.Password = NULL;</p> <p>THIS.TYPE = NULL;</p> <p>THIS.USERNAME = NULL;</p> <p>}</p> <p>/ **</p> <p>* Validate The Properties That Have Been Set from this Http Request,</p> <p>* And return AN <code> ActionerrorS </ code> Object That Encapsulates Any</p> <p>* Validation Errors That Have Been Found. if No Errors Are Found, Return</p> <p>* <code> null </ code> or an <code> actionerrors </ code> Object with no</p> <p>* Recorded Error Messages.</p> <p>*</p> <p>* @Param mapping the mapping use to select this instance</p> <p>* @Param Request The Servlet Request WE Are Processing</p> <p>* /</p> <p>Public ActionerRors Validate (ActionMapping Mapping, httpservletRequest Request) {</p> <p>ActionerroS Errors = new actionerrors ();</p> <p>IF ((Host == Null) || (Host.Length () <1))</p> <p>Errors.Add ("Host",</p> <p>New ActionError ("Error.host.Required"));</p> <p>IF ((username == null) || (username.length () <1))</p> <p>Errors.Add ("Username",</p> <p>New ActionError ("Error.userName.Required));</p> <p>IF ((Password == null) || (Password.Length () <1))</p> <p>Errors.Add ("password",</p> <p>New ActionError ("Error.Password.Required));</p> <p>IF ((type == null) || (Type.length () <1)))</p> <p>Errors.Add ("Type",</p> <p>New ActionError ("Error.Type.Required"));</p> <p>Else IF (! "il) .Equals (type) &&!" pop3 ".equals (type))</p> <p>Errors.Add ("Type",</p> <p>New ActionError ("Error.Type.invalid", Type);</p> <p>Return (Errors);</p> <p>}</p> <p>}</p> <p>LogonAction Public Final Class LogonAction Extends Action {</p> <p>/ **</p> <p>* Process The Specified Http Request, and Create The Corresponding HTTP</p> <p>* Response (or Forward to another Web Component That Will Create IT).</p> <p>* Return AN <code> Actionforward </ code> Instance Describing Where and how</p> <p>* Control SHOULD BE Forwarded, or <code> Null </ code> if The Response HAS</p> <p>* Already Been Completed.</p> <p>*</p> <p>* @Param mapping the actionMapping use to select this instance</p> <p>* @Param Form The Optional Actionform Bean for this Request (if any)</p> <p>* @Param Request The Http Request WE Are Processing</p> <p>* @Param Response The Http Response We Are Creating</p> <p>*</p> <p>* @Exception Exception if Business Logic THROWS AN Exception</p> <p>* /</p> <p>Public ActionForward Execute (ActionMapping Mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>Httpservletresponse response</p> <p>Throws exception {</p> <p>// Extract Attributes We Will Need</p> <p>Locale locale = getLocale (request);</p> <p>MessageResources Messages = GetResources (Request);</p> <p>User User = NULL;</p> <p>// Validate the Request Parameters Specified by The User</p> <p>ActionerroS Errors = new actionerrors ();</p> <p>String UserName = (String)</p> <p>PropertyUtils.getsimpleProperty (Form, "UserName");</p> <p>String password = (string)</p> <p>PropertyUtils.getsimpleProperty (Form, "Password");</p> <p>UserDatabase Database = (UserDatabase)</p> <p>Servlet.getServletContext (). getAttribute (constants.database_key);</p> <p>IF (Database == Null)</p> <p>Errors.Add (actionerroS.Global_ERROR,</p> <p>New ActionError ("Error.Database.missing")));</p> <p>Else {</p> <p>User = getUser (Database, UserName);</p> <p>IF ((user! = null) &&! user.getpassword (). Equals (password))</p> <p>User = NULL;</p> <p>IF (user == NULL)</p> <p>Errors.Add (actionerroS.Global_ERROR,</p> <p>New ActionError ("Error.Password.mismatch))));</p> <p>}</p> <p>// Report Any Erroors We Have Discovered Back to the Original Form</p> <p>IF (! errors.isempty ()) {</p> <p>SaveerRors (Request, Errors);</p> <p>Mapping.getInputForward ());</p> <p>}</p> <p>// Save Our Logged-in User In the session</p> <p>HttpSession session = request.getations ();</p> <p>Session.SetaTRibute (constants.user_key, user);</p> <p>IF (log.Indebugeload ()) {</p> <p>Log.debug ("logonaction: user '" user.getusername () </p> <p>"'logged on in session" session.getID ());</p> <p>}</p> <p>// Remove the Obsolete form bean</p> <p>IF (mapping.getattribute ()! = null) {</p> <p>IF ("REQUEST" .Equals (mapping.getscope ()))))</p> <p>Request.Removettribute (mapping.getattribute ());</p> <p>Else</p> <p>Session.Removettribute (mapping.getattribute ());</p> <p>}</p> <p>// forward control to the specified surcess URI</p> <p>Return (Mapping.FindForward ("Success"));</p> <p>/ **</p> <p>* Look Up The User, throwing an exception to simulate business logic</p> <p>* Rule Exceptions.</p> <p>*</p> <p>* @Param Database Database in Which to Look Up The User</p> <p>* @Param Username UserName Specified On The Logon Form</p> <p>*</p> <p>* @Exception ModuleException if a business logic rule is violated</p> <p>* /</p> <p>Public User Getuser (UserDatabase Database, String Username)</p> <p>THROWS MODULEXCEPTION {</p> <p>// force an archmeticexception Which can be Handled Explicitly</p> <p>IF ("AritHmetic" .Equals (username) {</p> <p>Throw new ArithmeticException ();</p> <p>}</p> <p>// force an application-specific Exception Which Can Be Handled</p> <p>IF ("expired" .Equals (username) {</p> <p>Throw new expiredpasswordpteption (username);</p> <p>}</p> <p>// Look Up and return The Specified User</p> <p>Return ((User) Database.finduser (username);</p> <p>}</p> <p>}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-4960.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="4960" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.051</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'SOBMVGawqS0hqzccVEe_2BCTFxytjx9EOQUEUoQAFfcaors7Q2w6AKRmFaK1QJCn1TRvflGRyTWM_2F9iHatx6wbtg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>