Struts Principles and Practices (2)

xiaoxiao2021-03-06  105

Below, we will start from a simplest login example to have some intuitive and clear understanding of the main parts of Struts. This example is very simple, assumes that there is a user named LHB. The password is awave. The task to be completed is to present a login interface to the user. If the user entered the name and password, return a welcome page to the user, Otherwise, returning to the login page requires the user to log in and display the corresponding error message. This example is repeated when we tell the foundation of Struts. The reason why this simple program is used as an example because it doesn't want to make too complicated business logic to dilute our theme. Because Struts is based on the framework in the MVC design mode, you can comply with the standard development steps to develop your Struts web application, which can be roughly described as follows: 1 Defining and generating various views of all user interfaces representing the application, Generate all ActionForms used by these Views and add them to the struts-config.xml file. 2 Add the necessary MessageResources project 3 generates the controller of the application in the ApplicationResource.properties file. 4 Define the relationship between Views and Controller in the struts-config.xml file. 5 Generate the Model component 6 required to apply, run your application. Below, we will follow the steps mentioned in step by step to complete our app: The first step, our application's views section contains two A .jsp page: One is login page logon.jsp, and the other is the user function page main.jsp after the user logs in success. This page is just a simple welcome page. Among them, the Logon.jsp code list is as follows:

<% @ Page ContentType = "Text / HTML; Charset = UTF-8"%>

<% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%>

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

<bean: message key = "logon.jsp.title" /> </ title></p> <p><HTML: BASE /></p> <p></ HEAD></p> <p><Body></p> <p><h3> <bean: message key = "logon.jsp.page.Heading" /> </ h3></p> <p><html: errors /></p> <p><html: form action = "/ logonaction.do" FOCUS = "username"></p> <p><Table Border = "0" width = "100%"></p> <p><Tr></p> <p><Th align = "right"> <bean: message key = "logon.jsp.prompt.username" /> </ th></p> <p><TD align = "left"> <html: text protety = "username" /> </ td></p> <p></ TR></p> <p><Tr></p> <p><Th align = "right"> <bean: message key = "logon.jsp.prompt.password" /> </ tH> <TD align = "left"> <html: password property = "password" /> </ TD></p> <p></ TR></p> <p><Tr></p> <p><TD align = "right"></p> <p><html: submit> <bean: Message Key = "logon.jsp.prompt.submit" /> </ html: Submit></p> <p></ Td></p> <p><TD align = "left"></p> <p><html: reset> <bean: message key = "logon.jsp.prompt.reset" /> </ html: reset></p> <p></ Td></p> <p></ TR></p> <p></ Table></p> <p></ html: form></p> <p></ Body></p> <p></ Html></p> <p>The code list of main.jsp is as follows:</p> <p><% @ Page ContentType = "Text / HTML; Charset = UTF-8"%></p> <p><% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%></p> <p><% @ Taglib URI = "/ Web-INF / STRUTS-LOGIC.TLD" prefix = "logic"%></p> <p><Html></p> <p><HEAD></p> <p><Title> <bean: message key = "main.jsp.title" /> </ title></p> <p><HTML: BASE /></p> <p></ HEAD></p> <p><Body></p> <p><logic: present name = "userinfoform"></p> <p><H3></p> <p><bean: message key = "main.jsp.welcome" /></p> <p><bean: write name = "userinfoform" property = "username" />!</p> <p></ H3></p> <p></ logic: present></p> <p></ Body></p> <p></ Html></p> <p>First of all, let's take a look at the logon.jsp file, it will find that it has such a distinctive feature: First, the file head has, such as: <% @ taglib uri = "/ web-inf / struts-bean.tld" prefix = " Bean "%> <% @ Taglib URI =" / Web-inf / struts-html.tld "prefix =" html "%> Their role is to indicate a custom label for Struts to use Struts. The library URI is a logical reference, the location of the label library (TLD) is given in the web.xml file, see the configuration section of the next article. The Struts label library consists mainly of four sets of labels, which are: bean tags, the role is to manipulate the Bean Logic tab in JSP, the role is to process the HTML tag in JSP, and the function is to display a form template tag such as a form. Generating dynamic templates for specific functions and grammar for each type of label, due to space limitations, not here, you can refer to information such as Struts Manual. Just I have to understand what the so-called label is some class, this is some similar to bean, and they run in the rear end, generating a standard HTML tag to return to the browser. To use them, it is obvious to introduce their label library description files into our system, this is some .TLD as an extension file, we have to put them in / WebApps / MyStruts / Web-INF / directory. After introducing the Struts label, the original HTML tag is the label of the text box to become such a form.</p> <p>.</p> <p>The second feature of the JSP file is that the pages are not directly written for display, such as username, password, etc., but use</p> <p>This form appears. This feature has laid a solid foundation for international programming, and there will be special discussion on the articles behind international programming.</p> <p>The ActionForm used by this simple app is UserInfoform, the code list is as follows:</p> <p>Package Entity;</p> <p>Import org.apache.struts.Action.actionform;</p> <p>Import org.apache.struts.action.actionmapping;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Public Class UserInfoform Extends Actionform {</p> <p>PRIVATE STRING UserName;</p> <p>PRIVATE STRING Password;</p> <p>Public string getUsername () {</p> <p>Return (this.username);</p> <p>}</p> <p>Public void setusername (String username) {</p> <p>THIS.USERNAME = UserName;</p> <p>}</p> <p>Public string getpassword () {</p> <p>Return (this.password);</p> <p>}</p> <p>Public void setpassword (string password) {</p> <p>this.password = password;</p> <p>}</p> <p>}</p> <p>Built a CLASSES directory in your application's web-inf directory, build the following directory Entity in the newly built Classes directory, an action directory (for storing the Action class), bussness directory ( Used to store a business object class as a Model). The subdirectory in the class content is the so-called package, and will increase the corresponding package as needed. Now save UserInfoForm.java to the Entity directory.</p> <p>Add the following code to</p> <p>/webapps/mystruts/web-inf/struts-config.xml file</p> <p><form-beneans></p> <p><form-bean name = "userinfoform" type = "entity.userinfoform" /></p> <p></ form-beans></p> <p>It is especially to be reminded: About ActionForm's big lowercase, be sure to write in the above way to avoid unnecessary trouble.</p> <p>At this point, we have completed the first step.</p> <p>Step 2, we built a file called ApplicationResource.properties and put it in</p> <p>/ WebApps / MyStruts / Web-INF / CLASSES directory. It is in Struts-Config.xml configuration information. We have said in the end of the first article, that is:</p> <p>The content we joined in the ApplicationResource.properties file is:</p> <p>#Application resource for the logon.jsp</p> <p>Logon.jsp.title = the logon page</p> <p>Logon.jsp.page.Heading = Welcome World!</p> <p>Logon.jsp.prompt.username = Username:</p> <p>Logon.jsp.prompt.password = password:</p> <p>Logon.jsp.prompt.submit = SUBMIT</p> <p>Logon.jsp.prompt.reset = reset</p> <p>#Application resource for the main.jsp</p> <p>Main.jsp.title = the main page</p> <p>Main.jsp.welcome = Welcome:</p> <p>At this point, we have completed the second step.</p> <p>In the third step, we began to generate and configure the Controller component.</p> <p>In the previous we have mentioned that the Struts application consists of org.apache.struts.Action.ActionServlet and org.apache.struts.Action.Action class, where the former has been prepared by Struts, the latter Struts is just To provide us with a skeleton, we have to extend the Action class for the specific function of the application, the following is the code list of the Action class that implements our login program:</p> <p>Package action;</p> <p>Import java.io.ioException;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpsession;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import org.apache.struts.Action.action;</p> <p>Import org.apache.struts.Action.Actionerror;</p> <p>Import org.apache.struts.Action.Actionerro; import org.apache.struts.Action.Actionform;</p> <p>Import org.apache.struts.Action.actionForward;</p> <p>Import org.apache.struts.action.actionmapping;</p> <p>Import org.apache.struts.action.ActionServlet;</p> <p>Import bussness.userInfobo;</p> <p>Import entity.userinfoform;</p> <p>Public Final Class LogonAction Extends Action {</p> <p>Public ActionForward Execute (ActionMapping Mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>Httpservletresponse response</p> <p>THROWS IOException, servletexception {</p> <p>UserInfoform UserInfoform = (userInfoform) form;</p> <p>/ / Get username and password from the web layer</p> <p>String username = userinfoform.getuserName (). Trim ();</p> <p>String password = userinfoform.getPassword (). Trim ();</p> <p>// Statement error set object</p> <p>ActionerroS Errors = new actionerrors ();</p> <p>// Verify input</p> <p>IF (username.equals (")) {</p> <p>ActionError Error = New Actionerror ("Error.Missing.userName);</p> <p>Errors.Add (ActionerRors.global_Error, Error);</p> <p>}</p> <p>IF (Password.equals (")) {</p> <p>ActionError Error = New Actionerror ("Error.Missing.Password");</p> <p>Errors.Add (ActionerRors.global_Error, Error);</p> <p>}</p> <p>// Call business logic</p> <p>IF (errors.size () == 0) {</p> <p>String validated = ""</p> <p>Try {</p> <p>UserInfobo Userinfobo = New UserInfobo ();</p> <p>Validated = UserInfobo.validatePwd (username, password);</p> <p>IF (Validated.equals ("Match")) {</p> <p>// All the user information is saved and turned to the successful page</p> <p>HttpSession session = request.getations ();</p> <p>Session.setttribute ("UserInfoForm", FORM);</p> <p>Return mapping.findforward ("Success");</p> <p>}</p> <p>}</p> <p>Catch (throwable e) {</p> <p>// Process possible errors</p> <p>E.PrintStackTrace ();</p> <p>Actionerror Error = New ActionError (E.getMessage ());</p> <p>Errors.Add (ActionerRors.global_Error, Error);</p> <p>}</p> <p>}</p> <p>// Turn to the input page as an error, and display the corresponding error message</p> <p>SaveerRors (Request, Errors);</p> <p>Return New ActionForward (mapping.getinput ());</p> <p>}</p> <p>There are two error messages in this Action class to be added to the ApplicationResource.properties file, the list is as follows:</p> <p>#Application resource for the logonaction.java</p> <p>Error.Missing.username = <li> <font color = "red"> missing username </ font> </ li></p> <p>Error.Missing.password = <li> <font color = "red"> missing password </ font> </ li >></p> <p>Step 4: Define the relationship between Views and Controller in the struts-config.xml file, which is to configure so-called actionMApping. The positions in Struts-Config.xml are row</p> <p>...</p> <p>After the label, the configuration list of our login program is as follows:</p> <p><action-mappings></p> <p><action input = "/ logon.jsp" name = "userinfoform" path = "/ logonaction" scope = "session"</p> <p>TYPE = "action.logonaction" Validate = "false"></p> <p><forward name = "success" path = "/ main.jsp" /></p> <p></ action></p> <p></ action-mappings></p> <p>Step 5: Generate the Model component required by the application, which is where the application business logic is completed. Now my login program is very simple, it is to determine whether the user is LHB and its password is not awave if it is Returns a string "Match" that represents the match, otherwise, the error message will be thrown. The list of code is as follows:</p> <p>Package bussness;</p> <p>Import entity.userinfoform;</p> <p>Public class usrinfobo {</p> <p>Public userinfobo () {</p> <p>}</p> <p>Public String ValidatePwd (String UserName, String Password) {</p> <p>String validateresult = ""</p> <p>IF (username.equals ("lhb") && password.equals ("awave")) {</p> <p>Validateresult = "match";</p> <p>}</p> <p>Else {</p> <p>Throw new runtimeException ("error.nomatch");</p> <p>}</p> <p>Return validateresult;</p> <p>}</p> <p>}</p> <p>Place it in a bussness package.</p> <p>We also set it to the key value of the error message in the ApplicationResource.properties file, the list is as follows:</p> <p>#Application resource for the userinfobo.java</p> <p>Error.Nomatch = <li> <font color = "red"> no matched user </ font> </ li></p> <p>To this end, we have completed all components of this simple login program. Let's enjoy our labor results.</p> <p>In the sixth step, compile the running application.</p> <p>Regular practice is to assemble and deploy Struts applications with Ant. If this article will look very long, it is not much necessary, because, use an IDE generally easily generate an application. . Therefore, we use a simple way to compile our .java files directly. But here should pay attention to: Practice has proved that it is necessary to make a struts.jar file to copy a copy to</p> <p>/ Common / lib directory, and set ClassPath in the environment variables.</p> <p>/common/lib/struts.jar; you can compile the .java files under the Entity, Bussness, and Action directories, respectively. After the compilation is completed: open</p> <p>The server.xml file under the / conf directory, add a virtual directory for our application before adding the following statement:</p> <p><Context path = "/ mystruts" docbase = "mystruts" debug = "0"</p> <p>Reloadable = "True"></p> <p></ Context></p> <p>Start, Tomcat. Enter: http:// localhost: 8080 / mystruts / logon.jsp</p> <p>If the front step does not have a leak, a login screen shown in the figure will appear in front of you.</p> <p>If you don't enter anything, click the Submit button directly, return to logon.jsp and display missing username and missword error message; if you enter other content, you will return the NO matched user error; if the user name is LHB, The password is awave that the welcome page indicating successful login is displayed.</p> <p>Although it is a very simple application, the sparrow is small, the five flour is complete, and it is basically involved in the main components of Struts. Let's analyze the characteristics of the program and the basic working principle.</p> <p>First, when we entered the .jsp file in the browser, we will return the Struts's custom label "Translate" into a normal HTML tag to return to the browser, and some prompt information is as used as the input box Label, Password has a button. The prompt information is also error messages, etc., all from MessageResources, called the corresponding key value in the ApplicationResource.properties file. When we click on the Submit button, it can be seen from the configuration of Web.xml that the request will be intercepted by ActionServlet. It finds the corresponding in the struts-config.xml file through the Action parameters provided in the form.</p> <p>Item, if there is a corresponding ActionForm, it uses the data of the ActionForm in the form, and the actionform in this example is UserInfoform, the corresponding attribute is username and password, which is called instantiation ActionForm. Then, the control is given to the corresponding action. In this example, it is logonaction. It is the main job to do the username and password taken out of the ActionForm. This is just simply verify that it is empty (these simple formatting The verification should be placed on the client, and Struts also provides us with a good pattern, and later will be described in detail later). If you do not call the airline module UserInfobo, the user and the password are not called the regular business logic module, and it will capture the possible errors, then guide the program to a different page according to the result returned by the business logic. This example is returned if the business logic is returned in this example. The result is "match" based on</p> <p>Returns the main.jsp page to the browser to save the user's login information in the session object; otherwise, return the input page and display the corresponding error message, completed the four main responsibilities of its previous article.</p> <p>Everyone must notice that in this case, in the business logic module USERINFOBO, write the user and password in the program, and do not do this in a real application, those who need permanent saving, Username In the permanent media such as a database file, the password is saved, and the next article we will introduce how to access the database in Struts.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-125449.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="125449" 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.046</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 = 'ZFKy8vsSoHSNehPplbHzdoz0Ti9RH5oC6uFZXRU_2Fh_2B3vQ8tn03EE8IjZZPt_2BKeHkk8MSGFTi_2FlXNsTJ9sDNBcw_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>