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:
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.
.
The second feature of the JSP file is that the pages are not directly written for display, such as username, password, etc., but use
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.
The ActionForm used by this simple app is UserInfoform, the code list is as follows:
Package Entity;
Import org.apache.struts.Action.actionform;
Import org.apache.struts.action.actionmapping;
Import javax.servlet.http.httpservletRequest;
Public Class UserInfoform Extends Actionform {
PRIVATE STRING UserName;
PRIVATE STRING Password;
Public string getUsername () {
Return (this.username);
}
Public void setusername (String username) {
THIS.USERNAME = UserName;
}
Public string getpassword () {
Return (this.password);
}
Public void setpassword (string password) {
this.password = password;
}
}
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.
Add the following code to
/webapps/mystruts/web-inf/struts-config.xml file
form-beans>
It is especially to be reminded: About ActionForm's big lowercase, be sure to write in the above way to avoid unnecessary trouble.
At this point, we have completed the first step.
Step 2, we built a file called ApplicationResource.properties and put it in
/ 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:
The content we joined in the ApplicationResource.properties file is:
#Application resource for the logon.jsp
Logon.jsp.title = the logon page
Logon.jsp.page.Heading = Welcome World!
Logon.jsp.prompt.username = Username:
Logon.jsp.prompt.password = password:
Logon.jsp.prompt.submit = SUBMIT
Logon.jsp.prompt.reset = reset
#Application resource for the main.jsp
Main.jsp.title = the main page
Main.jsp.welcome = Welcome:
At this point, we have completed the second step.
In the third step, we began to generate and configure the Controller component.
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:
// All the user information is saved and turned to the successful page
HttpSession session = request.getations ();
Session.setttribute ("UserInfoForm", FORM);
Return mapping.findforward ("Success");
}
}
Catch (throwable e) {
// Process possible errors
E.PrintStackTrace ();
Actionerror Error = New ActionError (E.getMessage ());
Errors.Add (ActionerRors.global_Error, Error);
}
}
// Turn to the input page as an error, and display the corresponding error message
SaveerRors (Request, Errors);
Return New ActionForward (mapping.getinput ());
}
There are two error messages in this Action class to be added to the ApplicationResource.properties file, the list is as follows:
#Application resource for the logonaction.java
Error.Missing.username =
missing username font> li>
Error.Missing.password =
missing password font> li >>
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
...
After the label, the configuration list of our login program is as follows:
TYPE = "action.logonaction" Validate = "false">
action>
action-mappings>
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:
Package bussness;
Import entity.userinfoform;
Public class usrinfobo {
Public userinfobo () {
}
Public String ValidatePwd (String UserName, String Password) {
String validateresult = ""
IF (username.equals ("lhb") && password.equals ("awave")) {
Validateresult = "match";
}
Else {
Throw new runtimeException ("error.nomatch");
}
Return validateresult;
}
}
Place it in a bussness package.
We also set it to the key value of the error message in the ApplicationResource.properties file, the list is as follows:
#Application resource for the userinfobo.java
Error.Nomatch =
no matched user font> li>
To this end, we have completed all components of this simple login program. Let's enjoy our labor results.
In the sixth step, compile the running application.
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
/ Common / lib directory, and set ClassPath in the environment variables.
/common/lib/struts.jar; you can compile the .java files under the Entity, Bussness, and Action directories, respectively. After the compilation is completed: open
The server.xml file under the / conf directory, add a virtual directory for our application before adding the following statement:
If the front step does not have a leak, a login screen shown in the figure will appear in front of you.
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.
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.
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.
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
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.
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.
Author: Luo Kuaibo Dangyang IRS Information Center can contact him by lhbf@sina.com