Home>

Implement struts login

1.Jar package copyThe first is to build a java web project. After that, we download the strtus framework, struts-1.2.9-bin folder and struts-1.2.9.src source file folder.Copy the jar package of struts in the lib file in the bin folder and copy it to our own project struts_login->lib folder.

Web.xml file configurationFind struts-1.2.9-bin in struts-1.2.9-bin->struts instance under webapps struts-1.2.9-bin \ webapps \ struts-blank \ web- in struts-blank The web.xml file under inf, copy the configuration to the actionservlet configuration, and paste it into web.xml under web-inf of our project struts_login. The code is shown below.It mainly configures 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 the projectCreate your own actionform in the project, inherit the actionform already written in the struts framework, set the data used in the actionform,And it should be consistent with the name set on our interface.Because when we submit the form,All requests are placed in the actionform. To establish a login actionform, the loginactionform.java code is shown below.

package com.bjpowernode.struts;
import org.apache.struts.action.actionform;
/**
 * Login to actionform, responsible for collecting data from the form.
 * The properties of the form must be the same as the properties of get and set in actionform.
 * @author summer
 *
 * /
public classloginactionform extends actionform {
  //username.
  private stringusername;
  //password.
  private string password;
  //set password.
  public voidsetpassword (stringpassword) {
    this.password=password;
  }
  //Get the username.
  public stringgetusername () {
    return username;
  }
  //Set the user name.
  public voidsetusername (stringusername) {
    this.username=username;
  }
  //Get the password.
  public stringgetpassword () {
    return password;
  }
}

4. Create your own actionCreate your own action, and inherit org.apache.struts.action.action from the struts framework, and override the execute method of the parent class. Finish here to fetch the data from the form.Through calactionformcalform=(calactionform) (calactionform) form;(the struts framework has already packaged it for us,We can use it) to get the values ​​in the form.After judgment,Take the appropriate action,Jump to the corresponding page.The function of action is responsible for page jump after getting form data and calling business logic.Create a login action class, loginaction.java, and call the login method of the business logic 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;
/**
 * Login action
 * Responsible for obtaining form data,Call business logic,Returns steering information.
 *
 * @author summer
 *
 * /
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 username 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,Username=["+ username +" +] ");
       } catch (passworderrorexception e)
       {
          e.printstacktrace ();
          request.setattribute ("msg", "Wrong password");
       }
       return mapping.findforward ("error");
   }
}

5.Build struts-config.xmlAs the core description of the struts framework,struts-config.xml can say "everything is under control". It not only describes the MVC model, defines all the interface (actionform) between the view layer and the control layer, and combines the interface (action) with the control layer and model layerAnd you can define some additional components,If internationalized information resources are filed,Tag library information, etc.

Still standing on the shoulders of giants,Copy the struts-config.xml file from the struts bin folder we downloaded to the web-inf of our project and delete the comment section in struts-config.xmlConfigure action and actionform.Actionform is placed in<form-beans></form-beans>

<?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>

Among them, 0 or more form-bean elements can be defined in the form-beans element, each form-bean is considered as an actionform object, and the name attribute represents the name of the form-bean elementThe type attribute specifies its class name and path.

The action-mappings element is used to contain zero or more actions, and its child elements are responsible for detailed mapping details.You can define 0 or more action elements in the action-mapping element. Each action element accepts a request defined by the path attribute,And mapped to the specific action object defined by the type attribute. During the mapping process,Pass the actionform defined by the name attribute together,It has the following attributes:

parameter and scope specify the transmission method and scope.Commonly used values ​​for scope are two "session" and "request".

The validate attribute 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 classThe 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 () {
   }
   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">
  User:<inputtypeinputtype="text" name="username"><br>
  Password:<inputtypeinputtype="password" name="password"></br>
  <input type="submit" value="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>

In this way we have implemented struts framework to complete user login.So from initial learning to simple application,As the number of applications increases,We will understand struts more and more,And feel the convenience brought to us by the struts framework.

Form handler actionform (static and dynamic)The struts configuration was explained above, and an example of logging in using the struts framework is implemented.Some terms are already floating in my head.

actionservlet:controller for struts,Responsible for intercepting URLs or distributing. Provides the use of model (model layer) and view (view layer), so it can be considered as an intermediary between the model and the view.

actionform:used to encapsulate the user's request parameters,The request parameters are passed through the form fields of the jsp page.

action:a bridge between user requests and business logic,Each action acts as a proxy for business logic,You can call business logic.

Some issues need to be raised again.

The difference between using basic mvc and using struts framework,What are the benefits of using struts?

When we knew we did n’t apply the framework,The typical controller in MVC is a servlet. The servlet can obtain parameters and call and redirect functions of the logical model.And struts encapsulates it,Why encapsulation?When we request a servlet, we get parameters in this servlet, call business logic, and redirect. We write to the servlet to redirect the page.When we want to change to a redirect page, we need to change the code,Recompile after changing the code.

And the data passed from the form is all in string form,We also need to convert the string to the type we need according to the actual needs,If conversion is needed in many places,And every time you use it,Is there a mechanism,How about taking the string in the form and automatically converting it to the corresponding type?Don't we need to perform manual conversion again?

Based on the above inconvenience,The steering is not flexible,A series of reasons, such as the conversion of strings in a form,struts encapsulates this.Extract duplicate actions,The steering information is put into the configuration file,This is more flexible.

In the above question,Explained the encapsulation of the form by struts,During web application development,Developers need a lot of time to deal with form issues,Sometimes new questions are submitted through the form,Some are modifying data through forms,The processing of all these forms everywhere is very complicated in traditional web development.This article focuses on the form processor actionform in struts.

actionform

statement of problem

In traditional web application development,The complicated form processing has caused great difficulties for the development staff,In traditional development languages,There is no component that automatically collects the form content entered by the user.The developer has to manually extract the values ​​of the form in the program.For example, there is a text input field in the form:To get the value of this text input field in the program,You can only use this method:request.getparameter ("password");This processing method can be used when the form is relatively small,But when there are many form input items, you have to repeat a lot of similar processing.

Problem solving

In struts, we use actionform to solve this problem.For each user ’s form,Need to provide an actionform, this actionform automatically saves the form submitted by the customer in this actionform, and then passes this actionform to the action, so the user information can be retrieved through this actionformThen complete the corresponding business logic processing based on this information.

For example, struts is expressed in the following form using html tags of struts:

<html:text property="password" />

After the form is submitted in this case,The struts framework will automatically assign this input item in the form to the password attribute in actionform, thereby saving the content in the form in actionform. The entire process is automatically completed by struts.No developer intervention is required.We have to follow the following specifications when creating an actionform:

(1) Each actionform must inherit the org.apache.struts.action.actionform class, and an actionform needs to be provided for each form.

(2) Each attribute in the actionform should correspond to the entry in the form one by one.

(3) getter method and setter method for each attribute of acitonform. The struts framework uses these methods to save the values ​​of the form.Then use these methods to get the value of the form in the action.

(4) If the form requires validation,You need to provide a validate method in actionform, which provides specific validation logic for the form.This method not only implements data verification, but also implements the role of data buffering.Verify the validity of the user submitted form in the validate method,When the form validation fails, the user input page is automatically returned.At this time, the values ​​entered by the user are stored in the actionform. When the struts framework returns the page, the data in the acitonform will be taken out and output to the corresponding user input.The form information that the user starts to enter is guaranteed.

statement of problem

The above is a static actionform. When we create an acitonform for each form, it will cause 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 the attribute names of the submit forms are the same,No more creating acitonform (such as login and registration)?

Problem solving

Struts can use dynamic actionform to solve the above problems.The dynamic actionform does not need to create its own actionform. When creating its own action, it is necessary to directly convert the form object passed in the execute method into a dynaactionform.

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 name="age" type="java.lang.integer" />
      </form-bean>
  </form-beans>

Use the get method in the action to get the value 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;
      //Retrieve the key value from the map 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, and the dynamic actionform method uses the map's getkey method, where key is the value of the label name.

Advantages of using dynamic actionform:If you do not need to recompile when changing the form and actionform,The static need to change the static actionform.java file must be recompiled.Disadvantages:the corresponding value is returned statically,Dynamic actionform returns objects,We also have to cast this object.

  • Previous Simple analysis of C language program compilation problems for the ARM platform
  • Next Summary of the use of the describe command in MySQL