Struts Principles and Applications (III)

Source: Internet
Author: User
Tags tld
Chapter 5: struts Work Flow

Struts Principle and Practice

 

Is the struts workflow. As we mentioned above, all requests are submitted to the actionservlet for processing.

ActionservletIs a frontcontroller, which is a standard servlet that forwards requests to requestprocessor for processing,

ActionmappingIs a subclass of actionconfig, essentially a ing to the struts-config.xml, from which you can obtain all the configuration information

RequestprocessorObtain the corresponding actionforn and action from actionmapping Based on the submitted URL, such as *. Do. Then, the request parameter is mapped to actionform for form verification. If the verification succeeds, the execute () method of the action is called to execute the action, and the actionfoward is returned.

ActionfowardIs the packaging of a foward in mapping, corresponding to a URL

ActionformThe viewhelper mode is used to encapsulate the form in HTML. The validate method is used to verify the validity of form data. Actionform is a class that complies with the an specification. All attributes must correspond to get and set. For some complex systems, you can also use dynaactionform to construct a dynamic form, that is, generate a form by premade parameters. In this way, you can more flexibly extend the program.

ActionerrorsIs the packaging of error information. Once an exception occurs in the execution of action or form. Validate, an actionerror is generated and finally added to actionerrors. If an error occurs during form verification, the page is redirected to the input page again and an error is prompted.

ActionIs the requsesthandler used to execute business logic. Each action creates only one instance. Action is NOT thread-safe, so it is not necessary to access specific resources in action. In general, the Business Delegate mode should be used to access the business tier to remove coupling.

Struts provides multiple actions for you to choose from. A common action can only execute a task by calling execute, while a dispatchaction can be executed according to the configuration parameters, rather than simply entering the execute () function, so that multiple tasks can be executed. Such as insert and update. Lookupdispatchaction can be used to execute a function based on the name of the submit form button.

Let's go back to the example and understand the struts process.

Let's take a look at the example of struts:

Chapter 6: Example 2: Login Application

Struts Principle and Practice

Note: Example 2 is the example program provided by struts, which enables login, registration, and modification.

Struts taglib is widely used in the Code and the validator plug-in is used for form verification.

But the Code sets a bad example, that is, writing a large number of business logic into the action.

Some code is as follows:

Login: logon. jsp

 

<% @ Page contenttype = "text/html; charset = UTF-8 "Language =" Java "%> </P> <p> // declare taglib <br/> <% @ taglib uri ="/WEB-INF/struts-bean.tld "prefix = "Bean" %> <br/> <% @ taglib uri = "/WEB-INF/struts-html.tld" prefix = "html" %> </P> <p> <HTML: HTML locale = "true"> <br/> <pead> <br/> // bean is used to read i18n information from applicationresource. <br/> <title> <Bean: message key = "logon. title "/> </title> <br/> <HTML: base/> <br/> </pead> <br/> <body bgcolor = "white"> </P> <p> // error message <br/> <HTML: errors/> </P> <p> // log on to the form. The action is logion. DO <br/> <HTML: Form Action = "/logon" Focus = "username" <br/> onsubmit = "Return validatelogonform (this ); "> <br/> <Table border =" 0 "width =" 100% "> </P> <p> <tr> <br/> <TH align =" right"> <br/> <Bean: message key = "prompt. username "/>:< br/> </Th> <br/> <TD align =" Left "> <br/> <HTML: text property = "username" size = "16" maxlength = "18"/> <br/> </TD> <br/> </tr> </P> <p> <tr> <br/> <TH align = "right"> <br/> <Bean: message key = "prompt. password "bundle =" alternate "/>:< br/> </Th> <br/> <TD align =" Left "> <br/> <HTML: password property = "password" size = "16" maxlength = "18" <br/> redisplay = "false"/> <br/> </TD> <br/> </tr> </P> <p> <tr> <br/> <TD align = "right"> <br/> <HTML: submit value = "Submit"/> <br/> </TD> <br/> <TD align = "Left"> <br/> <HTML: reset/> <br/> </TD> <br/> </tr> </P> <p> </table> </P> <p> </ptml: form> </P> <p> // validator plug-in for Form Verification <br/> <HTML: javascript formname = "logonform" <br/> dynamicjavascript = "true" <br/> staticjavascript = "false"/> <br/> <script language = "javascript1.1" src =" staticjavascript. JSP "> </SCRIPT> </P> <p> </body> <br/> </ptml: HTML> </P> <p>

Struts-config.xml Configuration

<Form-beans> </P> <p> <! -- Logon form Bean --> <br/> <form-bean name = "logonform" <br/> type = "org. apache. struts. validator. dynavalidatorform "> <br/> <form-property name =" username "type =" Java. lang. string "/> <br/> <form-property name =" password "type =" Java. lang. string "/> <br/> </form-bean> </P> <p> <! -- Subterraform Bean --> <br/> <form-bean name = "subscriptionform" <br/> type = "org. apache. struts. webapp. example. subscriptionform "/> </P> <p> </form-beans> <br/> <action-mappings> </P> <p> <! -- Edit mail subtasks --> <br/> <action Path = "/editsubtasks" <br/> type = "org. apache. struts. webapp. example. editsubscriptionaction "<br/> attribute =" subscriptionform "<br/> scope =" request "<br/> validate =" false "> <br/> <forward name =" Failure "Path ="/mainmenu. JSP "/> <br/> <forward name =" success "Path ="/subscribe. JSP "/> <br/> </Action> <br/>... <br/>

SubscriptionformIs a standard actionform, the reset method is used to clear the form value, and the validate method is used to verify

Public final class subscriptionform extends actionform {<br/> // The Maintenance action we are using Ming (create or edit ). <br/> private string action = "CREATE"; <br/> // shocould we auto-connect at startup time? <Br/> private Boolean autoconnect = false; <br/> // The host name. <br/> private string host = NULL; <br/> private string Password = NULL; <br/> private string type = NULL; <br/> private string username = NULL; </P> <p> Public String getaction () {return (this. action) ;}< br/> Public void setaction (string action) {This. action = action ;}</P> <p> Public Boolean getautoconnect () {return (this. autoconne CT) ;}< br/> Public void setautoconnect (Boolean autoconnect) {This. autoconnect = autoconnect ;}</P> <p> Public String gethost () {return (this. host) ;}< br/> Public void sethost (string host) {This. host = Host ;}</P> <p> Public String GetPassword () {return (this. password) ;}< br/> Public void setpassword (string password) {This. password = PASSWORD ;}</P> <p> Public String GetType () {return (this. type) ;}< Br/> Public void settype (string type) {This. type = type ;}</P> <p> Public String GetUserName () {return (this. username) ;}< br/> Public void setusername (string username) {This. username = username ;}</P> <p>/** <br/> * reset all properties to their default values. <br/> * @ Param mapping the mapping used to select this instance <br/> * @ Param request the Servlet request we are processi Ng <br/> */<br/> Public void reset (actionmapping mapping, httpservletrequest request) {</P> <p> This. action = "CREATE"; <br/> This. autoconnect = false; <br/> This. host = NULL; <br/> This. password = NULL; <br/> This. type = NULL; <br/> This. username = NULL; </P> <p >}</P> <p>/** <br/> * validate the properties that have been set from this HTTP request, <br/> * and return an <code> actionerrors </code> O Bject that encapsulates any <br/> * validation errors that have been found. if no errors are found, return <br/> * <code> null </code> or an <code> actionerrors </code> object with no <br/> * recorded error messages. <br/> * @ Param mapping the mapping used to select this instance <br/> * @ Param request the Servlet request we are processing <br/> */ <br/> Public actionerrors validate (actionmapp Ing mapping, <br/> httpservletrequest request) {</P> <p> actionerrors errors = new actionerrors (); </P> <p> If (host = NULL) | (host. length () <1) <br/> errors. add ("host", <br/> New actionerror ("error. host. required "); <br/> If (username = NULL) | (username. length () <1) <br/> errors. add ("username", <br/> New actionerror ("error. username. required "); <br/> If (Password = NULL) | (password. leng Th () <1) <br/> errors. add ("password", <br/> New actionerror ("error. password. required "); <br/> If (type = NULL) | (type. length () <1) <br/> errors. add ("type", <br/> New actionerror ("error. type. required "); <br/> else if (! "IMAP". Equals (type )&&! "POP3 ". equals (type) <br/> errors. add ("type", <br/> New actionerror ("error. type. invalid ", type); </P> <p> return (errors ); </P> <p >}</P> <p>

Logonaction

Public final class logonaction extends action {<br/>/** <br/> * process the specified HTTP request, and create the corresponding HTTP <br/> * response (or forward to another Web component that will create it ). <br/> * return an <code> actionforward </code> instance describing where and how <br/> * control shocould be forwarded, or <code> null </code> If the response has <br/> * already been completed. <Br/> * <br/> * @ Param mapping the actionmapping used to select this instance <br/> * @ Param form the optional actionform bean for this request (if any) <br/> * @ Param request the HTTP request we are processing <br/> * @ Param response the HTTP response we are creating <br/> * @ exception exception If business logic throws an exception <br/> */<br/> Public actionforward execute (actionmappin G Mapping, <br/> actionform form, <br/> httpservletrequest request, <br/> httpservletresponse response) <br/> throws exception {</P> <p> // extract attributes we will need <br/> locale = getlocale (request ); <br/> messageresources messages = getresources (request); <br/> User user = NULL; </P> <p> // validate the Request Parameters specified by the user <br/> actionerrors errors = new actionerrors (); <B R/> string username = (string) <br/> propertyutils. getsimpleproperty (form, "username"); <br/> string Password = (string) <br/> propertyutils. getsimpleproperty (form, "password"); <br/> userdatabase database = (userdatabase) <br/> servlet. getservletcontext (). getattribute (constants. database_key); <br/> If (Database = NULL) <br/> errors. add (actionerrors. global_error, <br/> New actionerror ("error. databa Se. Missing "); <br/> else {<br/> User = getuser (Database, username); <br/> If (user! = NULL )&&! User. getPassword (). equals (password) <br/> User = NULL; <br/> If (user = NULL) <br/> errors. add (actionerrors. global_error, <br/> New actionerror ("error. password. mismatch "); <br/>}</P> <p> // report any errors we have discovered back to the original form <br/> If (! Errors. isempty () {<br/> saveerrors (request, errors); <br/> return (mapping. getinputforward (); <br/>}</P> <p> // Save Our logged-in user in the session <br/> httpsession session = request. getsession (); <br/> session. setattribute (constants. user_key, user); <br/> If (log. isdebugenabled () {<br/> log. debug ("logonaction: user'" + User. getUserName () + <br/> "'logged on in session" + session. GETID (); <BR/>}</P> <p> // remove the obsolete form bean <br/> If (mapping. getattribute ()! = NULL) {<br/> If ("request ". equals (mapping. getscope () <br/> request. removeattribute (mapping. getattribute (); <br/> else <br/> session. removeattribute (mapping. getattribute (); <br/>}</P> <p> // forward control to the specified success URI <br/> return (mapping. findforward ("success"); </P> <p >}</P> <p>/** <br/> * look up the user, throwing an exception to simulate business logic <br/> * Rule exceptions. <br/> * @ Param database in which to look up the user <br/> * @ Param username specified on the logon form <br/> * <br/> * @ exception moduleexception if a business logic rule is violated <br/> */<br/> public user getuser (userdatabase database, string username) <br/> throws moduleexception {</P> <p> // force an arithmeticexception which can be handled explicitly <br/> If ("arithmetic ". equals (username) {<br/> throw new arithmeticexception (); <br/>}</P> <p> // force an application-specific exception which can be handled <br/> If ("expired ". equals (username) {<br/> throw new expiredpasswordexception (username ); <br/>}</P> <p> // look up and return the specified user <br/> return (User) database. finduser (username); </P> <p >}< br/>

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.