The implementation of landing functions in the Java Struts Framework and the use of form processors _java

Source: Internet
Author: User
Tags throwable java web

Implement Struts Login
1. jar Package Copy
the first is to set up a Java Web project and then open our Strtus framework, Struts-1.2.9-bin folder and Struts-1.2.9.src source files folder. Copy the Struts jar package in the Lib file in the Bin folder and copy it to our own project Struts_login–>lib folder.

2, web.xml file configuration
find the struts-1.2.9-bin\webapps\ in the struts instance Struts-blank under Struts-1.2.9-bin-->webapps in Struts-1.2.9-bin Struts-blank\web-inf under the Web.xml file, replication configuration for the Actionservlet configuration, paste into our project Struts_login Web-inf under the Web.xml, the code is as follows. It is mainly to configure the Actionservlet with struts.

 <servlet> <servlet-name>action</servlet-name> <SERVLET-CLASS&G T;org.apache.struts.action.actionservlet</servlet-class> <init-param> <param-name>config</ param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-pa  
  ram> <param-name>debug</param-name> <param-value>2</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>2</param-value> ;/init-param> <load-on-startup>2</load-on-startup> </servlet> <!--Standard Action Ser Vlet Mapping--> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.d o</url-pattern> </servlet-mapping> 

3, in the project to establish their own actionform
Build Your own actionform in the project, inherit the Actionform already written in the Struts framework, set the data used in Actionform, and match the name set on our interface. Because when we submit the form, all requests are placed in the actionform. The Actionform,loginactionform.java code that establishes the login is shown below.

Package com.bjpowernode.struts; 
Import Org.apache.struts.action.ActionForm; 
  
/** 
 * Login Actionform, responsible for the form collection data. 
 * The properties of the form must match those of the get and set in Actionform. 
 * @author Summer 
 * * * 
/Public Classloginactionform extends Actionform { 
  
  //user name. 
  private stringusername; 
  Password. 
  private String password; 
   
  Set the password. Public 
  Voidsetpassword (stringpassword) { 
    this.password = password; 
  } 
  Get the user name. Public 
  Stringgetusername () {return 
    username; 
  } 
  Sets the user name. Public 
  Voidsetusername (stringusername) { 
    this.username = username; 
  } 
  Get the password. Public 
  Stringgetpassword () {return 
   
    password 
  } 
   
} 

4, establish its own action
to establish its own action, inheriting the org.apache.struts.action.Action in the struts framework, and overloading the parent class's Execute method. This completes the removal of the data in the form. by calactionformcalform= (Calactionform) (calactionform) Form (the Struts framework has already been encapsulated, we can use it) to get the values from the form. After the judgment, carries on the corresponding operation, jumps to the corresponding page. The function of the action is to take the form data and invoke the business logic after the page jump. Create login Action class, Loginaction.java class, invoke business logic class Usermanager login method. The code looks like this.

packagecom.bjpowernode.struts; 
Importjavax.servlet.http.HttpServletRequest; 
  
Importjavax.servlet.http.HttpServletResponse; 
Importorg.apache.struts.action.Action; 
Importorg.apache.struts.action.ActionForm; 
Importorg.apache.struts.action.ActionForward; 
  
importorg.apache.struts.action.ActionMapping; 
 /** * Login Action * is responsible for obtaining the form data, calling the business logic, and returning the steering information. * * * * @author Summer * */public classloginaction extendsaction {@Override public actionforward execute (A  Ctionmappingmapping,actionform form, httpservletrequest request, Httpservletresponseresponse) throws 
       Exception {Loginactionform LAF = (loginactionform) Form; 
       Stringusername = Laf.getusername (); 
        
       Stringpassword = Laf.getpassword (); 
       Usermanager Usermanager = Newusermanager (); 
          Pass user name and password try {usermanager.login (username, password); 
          Request.setattribute ("username", username); Return MAPPING.FINDFOrward ("Success"); 
          }catch (usernotfoundexception e) {e.printstacktrace (); 
       Request.setattribute ("msg", "User cannot find, user name =[" +username + "+]"); 
          }catch (passworderrorexception e) {e.printstacktrace (); 
       Request.setattribute ("msg", "Wrong password"); 
   Return Mapping.findforward ("error"); 
 } 
  
}

5,   establish Struts-config.xml
as the core description of the Struts framework, struts-config.xml can say "everything is in control". It not only describes the MVC model, defines the interface between all view layers and control layers (actionform), combines the control layer with the Model layer interface (Action), but also defines some additional components, such as the internationalization of information resources to file, tag library information, and so on. The
is still standing on the shoulders of giants, copying the struts-config.xml files from our downloaded struts  Bin folder to the Web-inf of our project, deleting the annotation section in Struts-config.xml. Configure the action and Actionform. Actionform into <form-beans></form-beans>, the action configuration is placed in <action-mappings></action-mappings>, The Struts-config.xml configuration code is shown below.

 <?xml version= "1.0" encoding= "Iso-8859-1"?> DOCTYPE struts-config Public "-//apache Software foundation//dtd struts configuration1.2//en" "Http://jakarta. Apache.org/struts/dtds/struts-config_1_2.dtd "> <struts-config> <form-beans> <form-bean na 
    Me= "LoginForm" type= "Com.bjpowernode.struts.LoginActionForm"/> </form-beans> <action-mappings> <action path= "/login" type= "com.bjpowernode.struts.LoginAction" name= "LoginForm" scope= EST "> <forward name=" Success "Path=/login_success.jsp"/> <forward "error" name= "/login_error.jsp"/> </action> </action-mappings> </struts-config> 

Where the Form-beans element can define 0 or more Form-bean elements, each form-bean is considered to be a Actionform object, the Name property represents the names of the Form-bean elements, and the type attribute specifies its class name and path.
The action-mappings element is used to contain 0 to multiple action, and its child element action is responsible for the details of the specific mapping. You can define 0 or more action elements in the action-mapping element. Each action element accepts the request defined by the path attribute and maps to the specific action object defined by the type attribute. During the mapping process, the actionform of the Name property definition is passed along, which has the following properties:
Parameter,scope Two attributes specify the mode and range of delivery, and the values commonly used for scope have two "sessions" and "request".
The Validate property specifies whether Actionform validation is required.
Forward the element to forward the request success to the "/login_success.jsp" page.
6. Business logic class Usermanager and custom exception classes
The code looks like this:

packagecom.bjpowernode.struts; 
  
Publicclassusermanager { 
    
   publicvoid login (Stringusername,stringpassword) 
   { 
       if (!) Admin ". Equals (username)) 
       { 
          thrownewusernotfoundexception (); 
       } 
        
        
       if (!) Admin ". Equals (password)) 
       { 
          thrownewpassworderrorexception (); 
       } 
   } 
  
} 

The custom exception class Usernotfoundexception and Passworderrorexception code are shown below.

packagecom.bjpowernode.struts; 
  
public class Usernotfoundexceptionextends RuntimeException {public 
  
   usernotfoundexception () { 
   } 
  
   Usernotfoundexception (stringmessage) { 
       super (message); 
   } 
  
   Public usernotfoundexception (Throwable cause) { 
       super (cause); 
   } 
  
   Public usernotfoundexception (stringmessage,throwable cause) { 
       Super (message, cause); 
   } 
  
} 
  
packagecom.bjpowernode.struts; 
  
public class Passworderrorexceptionextends RuntimeException {public 
  
   passworderrorexception () { 
   } 
  
   Public Passworderrorexception (stringmessage) { 
       super (message); 
   } 
  
   Public passworderrorexception (Throwable cause) { 
       super (cause); 
   } 
  
   Public passworderrorexception (stringmessage,throwable cause) { 
       Super (message, cause); 
   } 
  
} 

7, view JSP page calls.
Login Interface login.jsp, error display interface login_error.jsp, login successfully interface login_success.jsp. The code looks like this.

<% @pagelanguage = "java" contenttype= "text/html; charset=gb18030 " 
  pageencoding=" GB18030 "%> 
<! doctypehtml public "-//w3c//dtdhtml 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 
 
 

Login_success.jsp.

<% @page language= "java" contenttype= "text/html;charset=gb18030" pageencoding= "GB18030"%> <! 
DOCTYPE HTML PUBLIC "-//w3c//dtdhtml 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 
 
 

Login_error.jsp interface.

<% @page language= "java" contenttype= "text/html; charset=gb18030 " 
  pageencoding=" GB18030 "%> 
<! DOCTYPE HTML PUBLIC "-//w3c//dtdhtml 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 
 
 

In this way we achieved the use of the struts framework to complete user login. In this way from preliminary learning to simple application, as the number of applications increased, we will understand the struts more and more profound, and feel the struts framework to bring us convenience.


Form Processor Actionform (static dynamic)
This explains the struts configuration and implements the example of using the Struts framework for logging in. Some nouns are already floating in my mind.
Actionservlet:struts Controller, which is responsible for intercepting URLs or distributing them. Provides model (model layer) and view (view layer) use, so you can consider it as a mediator between models and views.
Actionform: Used to encapsulate the user's request parameters, and request parameters are passed through the form fields of the JSP page.
Action: A bridge between user requests and business logic, where each action acts as an agent of the business logic and can invoke the business logic.
Some questions need to be mentioned again.
Using the basic MVC and using the Struts framework, what is the advantage of using struts?
We know that when we do not apply frameworks, the typical controller in MVC is that Servlet,servlet can get the call and turn functions of parameters and logical models. And what does struts do to encapsulate it? When we request to a servlet, we get parameters in this servlet, invoke business logic, turn, we write dead in the servlet to the page, when we want to change a turn to the page, we need to change the code, change the code and then recompile.
And the data passed from the form is all in string form, we also need to according to the actual needs of the string into the type we need, if many places need to convert, and each use to convert each time, there is a mechanism to take the form of the string to automatically convert to the appropriate type? Do we need to do a manual conversion?
Based on the above inconvenience, the steering is not flexible, the form of the string each time to convert a series of reasons, struts to do these encapsulation. It is more flexible to extract repetitive operations and move information into the configuration file.
In the above question, the article elaborates struts to the form encapsulation, in the Web application development process, the developer needs the massive time to deal with the form question, sometimes is submits some new questions through the form, some changes the data through the form, The processing of all these forms is very complex in traditional web development. This article focuses on the form processor Actionform in struts.
Actionform
The question of the proposed
In traditional Web application development, complex forms processing has brought great difficulties to development workers, in the traditional development language, no build can automatically collect user input form content, developers have to manually extract the value of the form in the program. For example, there is a text input field in the form: <inputtype= "text" name= "password" > to get the value of this text input field in the program, only in this way: Request.getparameter (" Password "); This approach can be used when the form is relatively small, but it has to be heavily duplicated when the form is entered more often.
Solution to the problem
In struts is the use of actionform to solve this problem, for each user's form, need to provide a actionform, this actionform automatically put the customer submitted form to save in this actionform, The actionform is then passed to the action so that the user information can be taken out of the action by the Actionform, and then the corresponding business logic is processed according to the information.
In struts, for example, the HTML tag of struts is expressed in the following form:

 
 

In this case, when the form is submitted, the Struts framework automatically assigns this entry in the form to the password attribute in the Actionform, which saves the contents of the form in Actionform, and the entire process is done automatically by struts without the need for developer intervention. We should follow the following specifications when creating Actionform:
(1) Each actionform inherits the Org.apache.struts.action.ActionForm class and needs to provide a actionform for each form.
(2) Each property in the Actionform corresponds to the input item one by one in the form.
(3) Acitonform The Getter method and setter method to be provided for each property. The struts framework is the way to save the values of the form, and then take the form's values in the action by using these methods.
(4) If the form needs to be validated, you need to provide a validate method in Actionform, which provides specific validation logic for the form. This method not only realizes the data verification, but also realizes the function of data buffering, verifies the validity of the user submitting form in the Validate method, and automatically returns the user Input page when the form verification fails, when the user input value is saved in the Actionform. When you return to the page, the Struts framework takes out the data in the Acitonform and outputs it to the corresponding user entry, ensuring that the form information that the user starts to enter is entered.

The question of the proposed
The above is static actionform, when we create a acitonform for each form, will cause too many actionform. A strong aggregation of each actionform also makes the code difficult to maintain and reuse. How do you not have to create too many actionform? And when you submit a form with the same property name, you don't have to repeat the creation of acitonform (for example, login and registration)?
Solution to the problem
Dynamic Actionform can be used to solve these problems in struts. Dynamic Actionform does not need to create its own actionform, and you need to convert the Form object passed in the Execute method to Dynaactionform when you create your own action.
We need to change the Form-beans configuration in Struts-config.xml:

<form-beans> 
      <form-bean name= "DynaForm" type= "Org.apache.struts.action.DynaActionForm" > 
         < Form-property name= "username" type= "java.lang.String"/> <form-property 
         "age" name= " Java.lang.Integer "/> 
      </form-bean> 
  </form-beans> 

The Get method is used in the action to obtain the values in the form.

/** 
 * Test dynamic actionform. 
 * @author Summer 
 * */public 
Classdynaactionformtestaction extends Action { 
  
  @Override 
  Publicactionforward Execute (actionmapping mapping, actionform form, 
         httpservletrequestrequest, HttpServletResponse response) 
         throwsexception { 
      
      Dynaactionformdaf = (dynaactionform) Form; 
      
      Remove the key value from the map to Name,value as the class name. 
      Stringusername = (String) daf.get ("username"); 
      Integerage = (Integer) daf.get ("Age"); 
      
      System.out.println ("username" +username); 
      System.out.println ("username" +age); 
      
      Returnmapping.findforward ("Success"); 
  } 
  
 

Static Actionform way, using Get/set method, and dynamic Actionform way, using map Getkey way, where key is the value of label name.
Use dynamic Actionform Benefits: If you change forms and Actionform without recompiling, and static Actionform.java files that need to be changed, you must recompile. Disadvantage: Static return is the corresponding value, dynamic Actionform return is the object, we also want to cast this object.

Related Article

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.