Java Struts framework login function and the use of form processor

  • 2020-04-01 04:31:17
  • OfStack

Implement Struts login
1. Jar copy
First, we'll set up the Java web project, and then we'll open up and we'll download the strtus framework, the struts-1.2.9-bin folder and the struts-1.2.9.src source folder. Copy the struts jar in the lib file in the bin folder to our own project struts_login > Lib folder.

2. Web.xml file configuration
Struts-1.2.9-bin--> The web.xml file under struts-1.2.9-bin under webapps under struts-blank in the struts instance under webapps under struts-blank, copy the configuration of the ActionServlet and paste it into the web.xml under the web-inf of our project struts_login, as shown below. It is mainly to configure the ActionServlet that comes with struts.


<servlet> 
  <servlet-name>action</servlet-name> 
  <servlet-class>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-param> 
   <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 Servlet Mapping --> 
 <servlet-mapping> 
  <servlet-name>action</servlet-name> 
  <url-pattern>*.do</url-pattern> 
 </servlet-mapping> 

3. Create your own ActionForm in your project
Create your own ActionForm in the project, inherit the ActionForm already written in the struts framework, and set the data in the ActionForm with the same name as set on our interface. Because when we submit the form, all of our requests go into the ActionForm. Create the loginactionform.java code for the loginactionform.java.


package com.bjpowernode.struts; 
import org.apache.struts.action.ActionForm; 
  
 
public classLoginActionForm extends ActionForm { 
  
  //The user name.
  private Stringusername; 
  //The password.
  private String password; 
   
  // Set up the The password.
  public voidsetPassword(Stringpassword) { 
    this.password = password; 
  } 
  // get The user name.
  public StringgetUsername() { 
    return username; 
  } 
  // Set up the The user name.
  public voidsetUsername(Stringusername) { 
    this.username = username; 
  } 
  // get The password.
  public StringgetPassword() { 
   
    return password; 
  } 
   
} 

4. Create your own actions
Build your own Action, at the same time, inherited the struts framework in the org.. Apache struts. The Action. The Action, overloading the execute method of the parent. This completes the retrieval of the data from the form. Through CalActionFormcalForm = (CalActionForm) (CalActionForm) form; (the struts framework has encapsulated it for us, so we can use it) to get the values in the form. After the judgment, the corresponding operation, jump to the corresponding page. The function of Action is to take care of the page jump after the form data and the business logic is invoked. Create the login Action class, LoginAction. Java class, and invoke the login method of the business logic class UserManager. The code is shown below.


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; 
  
 
public classLoginAction extendsAction { 
  
   @Override 
   public ActionForward execute(ActionMappingmapping,ActionForm form, 
          HttpServletRequest request, HttpServletResponseresponse) 
          throws Exception { 
  
  
       LoginActionForm laf = (LoginActionForm)form; 
       Stringusername = laf.getUsername(); 
       Stringpassword = laf.getPassword(); 
        
       UserManager userManager = newUserManager(); 
       //Pass the username and password
       try 
       { 
          userManager.login(username, password); 
          request.setAttribute("username", username); 
          return mapping.findForward("success"); 
       }catch(UserNotFoundException e) 
       { 
          e.printStackTrace(); 
          request.setAttribute("msg"," The user cannot find , The user name =[" +username +"+]"); 
       }catch(PasswordErrorException e) 
       { 
          e.printStackTrace(); 
          request.setAttribute("msg"," Password mistake "); 
       } 
        
       return mapping.findForward("error"); 
   } 
  
} 

5,   Establish the struts - config. XML
As the core description of the Struts framework, struts-config.xml can be said to be "under control." It not only describes the MVC model, defines all the interfaces between the view layer and the control layer (ActionForm), combines with the interface between the control layer and the model layer (Action), but also defines some additional components, such as internationalization information resources to file, tag library information, and so on.
Still standing on the shoulders of giants, downloading us struts  The struts-config.xml file in the bin folder is copied into the web-inf of our project, removing the comments section in struts-config.xml. Configure the Action and ActionForm. Actionforms on < The form - beans> < / form - beans> , the Action configuration is placed in < The 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 name="loginForm" type="com.bjpowernode.struts.LoginActionForm"/> 
  </form-beans> 
   
  <action-mappings> 
    <action path="/login" 
       type="com.bjpowernode.struts.LoginAction" 
       name="loginForm" 
       scope="request" 
       > 
       <forward name="success" path="/login_success.jsp"/> 
       <forward name="error" path="/login_error.jsp"/> 
    </action> 
  </action-mappings>  
</struts-config> 

Where 0 or more form-bean elements can be defined in the form-beans element, each form-bean is considered an ActionForm object, the name attribute indicates the name of the form-bean element, and the type attribute specifies its class name and path.
The action-mappings element is used to contain zero to multiple actions, and the child actions are responsible for the details of the specific mappings. 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 defined by the name property is passed along with the following properties:
The two properties of Parameter and scope specify the transfer mode and scope, and the common values of scope include two "session" and "request".
The Validate property specifies whether actionform validation is required.
The Forward element forwards the request success to the "/login_success.jsp" page.
6. Business logic class UserManager and custom exception class
The code is as follows:


packagecom.bjpowernode.struts; 
  
publicclassUserManager { 
    
   publicvoid login(Stringusername,Stringpassword) 
   { 
       if(!"admin".equals(username)) 
       { 
          thrownewUserNotFoundException(); 
       } 
        
        
       if(!"admin".equals(password)) 
       { 
          thrownewPasswordErrorException(); 
       } 
   } 
  
} 

The custom exception classes UserNotFoundException and PasswordErrorException code are shown below.


packagecom.bjpowernode.struts; 
  
public class UserNotFoundExceptionextends RuntimeException { 
  
   public UserNotFoundException() { 
   } 
  
   public 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 call.
Login interface login.jsp, error display interface login_error.jsp, login success interface login_success.jsp. The code is shown below.


<%@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"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=GB18030"> 
<title>Inserttitle here</title> 
</head> 
<body> 
<form action="login.do" method="post"> 
   The user :<inputtypeinputtype="text" name="username"><Br> 
   password :<inputtypeinputtype="password" name="password"></br> 
  <input type="submit" value=" The login "> 
</form> 
</body> 
</html> 

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"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=GB18030"> 
<title>Insert title here</title> 
</head> 
<body> 
 ${username}, Login successful ! 
</body> 
</html> 

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"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=GB18030"> 
<title>Insert title here</title> 
</head> 
<body> 
 <%-- 
 <%=request.getAttribute("msg") %> 
 --%> 
  
 ${msg } 
</body> 
</html> 

So we implemented the struts framework to complete user login. In this way, from preliminary learning to simple application, as the number of applications increases, we will have a deeper understanding of struts and feel the convenience brought by the struts framework.


Form processor ActionForm (static and dynamic)
The struts configuration is explained above and an example of logging in using the struts framework is implemented. Some nouns are already floating around in my mind.
ActionServlet: struts controller that intercepts urls or distributions. Provides the use of the Model(Model layer) and the View(View layer), so you can think of it as a mediation between the Model and the View.
ActionForm: encapsulates the user's request parameters, which are passed through the form field of the JSP page.
Action: a bridge between user requests and business logic. Each Action ACTS as a proxy for business logic and can invoke business logic.
Some questions need to be asked again.
What is the difference between using basic MVC and using the struts framework?
We know that when we don't apply the framework, the typical controller in MVC is a servlet, which can get the invocation and steering functions of the parameters and logical model. Struts encapsulates it. Why? When we request to a servlet, we get parameters in the servlet, call the business logic, redirect, we write dead redirect page in the servlet, when we want to change a redirect page, we need to change the code, change the code after the recompile.
And all the data passed in from the form is a string, we also need to convert a string to we need according to the requirements of actual type, if a lot of places need to be transformed, and used every time every time, is there a mechanism to get the string in the form automatically converted to the corresponding type? Don't we need to do manual conversion?
Struts encapsulates this for a number of reasons, including the above inconveniences, inflexible steering, and the fact that the strings in the form are converted every time. The repeated operations are extracted and the steering information is put into the configuration file, which is more flexible.
In the above problems, this paper expounds the struts encapsulation of form, in the process of web application development, developers need a lot of time to deal with the form problem, sometimes it is through the form submit some new problems, have a plenty of through a form to modify the data, all of these forms in the process in the traditional web development is very complex. This article focuses on the form processor ActionForm in struts.
actionforms
Problem presentation
In traditional web application development, the complex form processing brings great difficulties to the development staff. In traditional development languages, there is no component that can automatically collect the form contents entered by the user, and the developers have to manually extract the form values 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, you can only use the following method: request-getparameter (" password "); This can be used when the form is small, but when the form has a large number of input items, you have to repeat much of the same process.
Problem solving
Actionforms in Struts is used to solve this problem, for each user of the form, there is a need to provide a actionforms, this actionforms automatically save customer submit form in this actionforms, then put the actionforms passed to the Action, in which the Action through the actionforms user information removed, then according to these information to complete the corresponding business logic processing.
For example, in Struts, the Struts HTML tag is expressed in the following form:


<html:text property= " password " />

In this case, after the form is submitted, the struts framework will automatically assign this input item in the form to the password attribute in the ActionForm, thus saving the contents of the form in the ActionForm. The whole process is completed automatically by struts without any intervention from the developer. We should follow the following specifications when creating the ActionForm:
(1) each actionforms should inherit org.. Apache struts. Action. Actionforms classes, but also need to provide a actionforms for each form.
(2) each attribute in ActionForm should correspond to the input item in the form.
(3) the getter and setter methods to be provided for each property of AcitonForm. The Struts framework USES these methods to save the values of the form and then retrieve them in the Action.
(4) if the form requires validation, you need to provide the validate method in the ActionForm, which provides the specific validation logic for the form. This method not only realizes the data validation and implements the data buffer role, verify the validity of the user submits the form in the validate method, when the form validation failure automatically return to the user to enter the page, then the value of user input is stored in actionforms, return to the page in the struts framework will take out AcitonForm data inputs and outputs to the corresponding user, to ensure the information users start input form.

Problem presentation
This is static actionforms, and when we create an AcitonForm for each form, we end up with too many actionforms. The excessive aggregation of each ActionForm also makes the code difficult to maintain and reuse. How about not creating too many actionforms? And when you submit the form with the same property name, you don't need to create the AcitonForm again (such as login and registration)?
Problem solving
Dynamic ActionForm can be used in Struts to solve the above problem. Dynamic actionforms don't need to create their own actionforms. Instead, they need to directly convert the form object passed in the execute method to DynaActionForm when creating their own actions.
We need to change the configuration of form-beans 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 name="age" type="java.lang.Integer"/> 
      </form-bean> 
  </form-beans> 

The get method is used in the Action to get the value in the form.


 
public classDynaActionFormTestAction extends Action { 
  
  @Override 
  publicActionForward execute(ActionMapping mapping, ActionForm form, 
         HttpServletRequestrequest, HttpServletResponse response) 
         throwsException { 
      
      DynaActionFormdaf = (DynaActionForm)form; 
      
      //Take the key value in the map as name and the 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"); 
  } 
  
} 

The static ActionForm method USES the get/set method, while the dynamic ActionForm method USES the map getkey method, where the key is the value of the tag name.
Advantage of using dynamic ActionForm: if you do not need to recompile to change the form and ActionForm, and if you need to change the static actionform.java file statically, you must recompile. Disadvantages: static returns the corresponding value, dynamic ActionForm returns the object, and we need to cast this object.


Related articles: