How to configure and develop struts in eclipse

Source: Internet
Author: User
Tags tld

How to configure and develop struts in eclipse

 

Original address: http://blog.csdn.net/baggio785/archive/2006/03/10/620535.aspx (reprinted please indicate the source)

Date: 2006-3-9

Keywords: Eclipse, myeclipse, struts, Java

Preface

This article describes in detail how to configure and develop struts in eclipse Based on the instance. I have seen a lot of this on the Internet before.ArticleAnd many netizens asked such questions. Therefore, I want to write a detailed article based on my actual experience and examples. One is to help you, and the other is to test your knowledge.

This article is just some of my comments. If you have any errors, please comment on them.

Development Environment

Jdk00004_03, click to download
Tomcat5.0.28, click to download
Eclipse3.1.2. Click to download the Chinese package. The Chinese package 3.1.1 is also applicable to 3.1.2.
Myecil00004.1, click to download myecil00004.1 and crack the patch
Tomcatplugin plug-in, click to download tomcatplugin plug-in
For more Eclipse plug-ins, click to enter

Requirement

The struts application instance to be combined in this article is logon. The requirements for Logon are as follows:

1. Receive the username and password, go to the success page, and prompt "<username> welcome to log on !".
2. If the user name is empty, the system submits the form and prompts "Enter the user name !".
3. If the password is blank, the system submits the form and prompts "enter the password !".
4. If you enter an invalid user name, the system prompts "enter the correct user name !".
5. Use the model component to save logon information.

Introduction to the application instance logon framework

A logon application consists of the following modules:
1 model (m): The model is a JavaBean Component-savelogon, which contains two attributes: username (username) and userpassword (password). You can use GET/set to read and set attributes, and the method used to save the logon information is savetodb (). The savetodb task is to save the login information to a persistent storage system (such as a database ).
2 view (v): The view includes two JSP files and one actionform bean-logonform. The JSP files are logon. jsp and success. jsp. Logon. jsp is responsible for accepting user names and passwords and displaying error information. Success. jsp is responsible for displaying logon success information.
3. Controller (c): the controller is an action-type logonaction. Verify the business logic of the data, call the model component to save the login information, and select the view component to return it to the user.

Struts Working Mechanism

In the View component (logon. JSP), enter the user name and password, and submit the HTML form. The Struts framework first reads the web. configure servlet in XML, and then automatically encapsulate form data into actionform bean. In this example, It is logonform. Logonform verifies the validity of the submitted data (such as the shortest length and whether it contains invalid characters ). If the actionform bean verification fails, logonform returns the actionerrors object. The Struts framework stores the actionerrors object within the request range and forwards the request to the view component, the <HTML: errors/> label is used in the view component to display the error information contained in the actionerrors object within the request range. If the error information is verified by the actionform bean, the actionerrors object returned by logonform is null. The Struts framework submits the form data to the logonaction component of the controller. The controller verifies the business logic of the form data. If the logonaction verification fails, create an actionmessages object that contains the error message, save the actionmessages object to the request range by using the saveerrors method, forward the request to the view component, and pass <HTML: errors/> label to display the re The error message contained in the actionerrors object within the quest range; If logonaction passes verification, the Struts framework accesses the model component, then the Struts framework returns the actionfoward object, and according to the configuration of the Struts-config.xml file, decides to pass the forwarding information contained in the actionfoward object to that view component.

Deploy Struts Framework

Everyone has a certain understanding of the working mechanism of Struts. Now we will introduce how to deploy the Struts framework in eclipse.

The environment mentioned in this article has been mentioned earlier. This article does not introduce the installation of eclipse and its plug-ins myeclipse and tomcatplugin. Please refer to other articles. For more information about eclipse, see http://blog.csdn.net/baggio785/category/148174.aspx.

1. Create a project

1) Select Java> Tomcat project, next, 1


(Figure 1)

2) enter the project name. If the default value of the project directory is not used, modify it and click Finish. II


(Figure 2)

2. Create a Struts Framework

1) Right-click Project> New> Other> myeclipse> Web-Struts> struts 1.2> struts 1.2 form, Action & JSP. 3. If an error occurs in this step, this article does not describe it. Please refer to my other article-how to solve the problem of creating struts in myeclipse.


(Figure 3)

2) Configure struts actionform

Because the struts application instance in this article is a user logon, use logon in use case. Select a superclass. Other Default values are used. Thu


(Figure 4)

Enter optional details and enter form items. In this example, username and password are used ). Click Add. For details, see Figure 5 and figure 6.


(Figure 5)


(Figure 6)

After the input is complete, the form properties of optional details will be displayed. VII.


(Figure 7)

We use the default setting for the settings on the Methods tab.

Click the JSP tab, select the "Create JSP form" option, and set "/form/logon. jsp" by default ". 8


(Figure 8)

3) Configure struts action

The preceding steps complete the form configuration. configure action below.

Click Next in Figure 8 and use the default setting. 9


(Figure 9)

The parameter and methods options also use the default value.

Click the forwards tab and click Add. The configuration successful page is displayed. In this article, success. jsp in the root directory is selected as the success page, and the name is logon_ SC. 10


(Figure 10)

After the input is completed, the forwards of optional details is displayed. 11th


(Figure 11)

Click Finish.

Struts has been configured. Look at eclipse, there are some more stuff in the project, such as Struts-related jar, as well as struts-config.xml and TLD files. Of struts-config.xmlCodeAs follows:

Code listing 1 (struts-config.xml)

<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype Struts-config public "-// Apache Software Foundation // DTD struts configuration 1.2 //" http://struts.apache.org/dtds/struts-config_1_2.dtd ">

<Struts-config>

<Data-sources/>

<Form-beans>

<! -- Here is the configuration information of actionform. The name of actionform bean is logonform, and the corresponding class is com. mystruts. Struts. Form. logonform -->

<Form-bean name = "logonform" type = "com. mystruts. Struts. Form. logonform"/>

</Form-beans>

<Global-exceptions/>

<Global-forwards/>

<Action-mappings>

<! -- Here is the configuration information of the action component, which describes the action ing from the specific request path to the response action -->

<! -- Attribute: Set the key of the actionform associated with the action in the request or session range. It is the name in the request or session sharing. -->

<! -- Input: Specify the URL containing the form. The URL sent when form verification fails. -->

<! -- Name specifies the name of the form associated with the action. The name must have been defined in form-bean and can be written or not -->

<! -- Path specifies the path of the request to access the action, which must start with "/" -->

<! -- Scope specifies the scope of form, for example, request -->

<! -- Type specifies the class corresponding to the action component -->

<Action

Attribute = "logonform"

Input = "/form/logon. jsp"

Name = "logonform"

Path = "/logon"

Scope = "request"

Type = "com. mystruts. Struts. Action. logonaction">

<! -- This is forward, that is, the local forwarding configuration information. After logging on successfully, the system redirects to/success. jsp and the name is logon_ SC -->

<Forward

Name = "logon_ SC"

Path = "/success. jsp"

/>

</Action>

</Action-mappings>

<! -- The message resource file configuration is used to configure the resource bundle. It is used to store local text message files. Parameter specifies the file name, excluding the suffix. -->

<Message-resources parameter = "com. mystruts. Struts. applicationresources"/>

</Struts-config>

 

Create a message resource file

The view component uses tags to output text content from resource bundle. Resource bundle corresponds to the Message resource file.

Code List 2 (applicationresources. properties)

# Annotations
Logon. Page. Title = my first struts

Logon. username. Error = enter the user name!

Logon. userpassword. Error = enter the password!

Logon. badusername. Error = the user name cannot be admin!

Logon. baduserpassword. Error = the password cannot be 123456!

Logon. Success = welcome to log on!

In order to achieve internationalization, the Chinese characters in the message resource file adopt UTF-8 encoding. Shows how to convert Chinese characters to UTF-8.

Create a JSP file

Logon. jsp (Path:/form/) receives the username and password entered by the user, and displays the error message of Form Verification failure. Success. jsp displays the successful logon information.

All JSP files use custom tags without Java code. The entered text content is completely provided by tags.

Code List 3 (logon. jsp)

<% @ page contenttype = "text/html; charset = UTF-8 "Language =" Java "%>
<% @ taglib uri ="/WEB-INF/struts-bean.tld "prefix =" Bean "%>

<% @ taglib uri = "/WEB-INF/struts-html.tld" prefix = "html" %>

<% @ taglib uri = "/WEB-INF/struts-logic.tld" prefix = "logic" %>

<Bean: Message key = "logon. page. title "/>

Username:

password:

Code list 4 (success. jsp)

<% @ Page Language = "Java" pageencoding = "UTF-8" %>
<% @ Taglib uri = "/WEB-INF/struts-bean.tld" prefix = "Bean" %>

<% @ Taglib uri = "/WEB-INF/struts-html.tld" prefix = "html" %>

<% @ Taglib uri = "/WEB-INF/struts-logic.tld" prefix = "logic" %>

<HTML: HTML lang = "true">

<Head>

<HTML: base/>

<Title> success. jsp </title>

</Head>

<Body>

<Logic: present name = "savelogon" Scope = "request">

<Bean: write name = "savelogon" property = "username"/>

<Bean: Message key = "Logon. Success"/>

</Logic: Present>

</Body>

</Html: HTML>

Create actionform bean component logonfrom

After you submit an HTML form, the Struts framework automatically encapsulates the form data in actionform Bean (in this example, logonform. The attributes of actionform Bean must correspond to the fields in the HTML form one by one. Actionform bean verifies the form data and provides a method to reset the field value of the HTML form to the default value (equivalent to the reset of the Form in HTML ).

Code List 5 (logonfrom. Java)

Package com. mystruts. Struts. form;

Import javax. servlet. http. httpservletrequest;

Import org. Apache. Struts. Action. actionerrors;
Import org. Apache. Struts. Action. actionform;
Import org. Apache. Struts. Action. actionmapping;
Import org. Apache. Struts. Action. actionmessage;

/**
* Myeclipse struts
* Creation date: 02-27-2006
*
* XDoclet definition:
* @ Struts. form name = "logonform"
*/
Public class logonform extends actionform {

// ----------------------------------------------------------- Instance variables

/** Userpassword property */
Private string userpassword;

/** Username property */
Private string username;

// ----------------------------------------------------------- Methods

/**
* Method validate
* @ Param Mapping
* @ Param request
* @ Return actionerrors
*/
// The validate Method Used for Form Verification
Public actionerrors validate (
Actionmapping mapping,
Httpservletrequest request ){

// Declare an actionerrors object
Actionerrors errors = new actionerrors ();

// If the user name verification fails, save the actionmessage object to the actionerrors object errors. Logon. username. Error corresponds to the value of Logon. username. Error in the message resource file.
If (username = NULL | username. Length () <3 ){
Errors. Add ("username", new actionmessage ("Logon. username. error "));
}

// If password verification fails, save the actionmessage object to the actionerrors object errors. Logon. userpassword. Error corresponds to the value of Logon. userpassword. Error in the message resource file.
If (userpassword = NULL | userpassword. Length () <3 ){
Errors. Add ("userpassword", new actionmessage ("Logon. userpassword. error "));
}
// Todo auto-generated method stub

// Returns the actionerrors object errors. The Struts framework stores errors in the request range and forwards the request to the view component logon. in JSP, <HTML: errors/> is used to display error messages.
Return errors;
}

/**
* Method Reset
* @ Param Mapping
* @ Param request
*/
Public void reset (actionmapping mapping, httpservletrequest request ){

// Todo auto-generated method stub
This. Username = NULL;
This. userpassword = NULL;
}

/**
* Returns the userpassword.
* @ Return string
*/
Public String getuserpassword (){
Return userpassword;
}

/**
* Set the userpassword.
* @ Param userpassword the userpassword to set
*/
Public void setuserpassword (string userpassword ){
This. userpassword = userpassword;
}

/**
* Returns the username.
* @ Return string
*/
Public String GetUserName (){
Return username;
}

/**
* Set the username.
* @ Param username the username to set
*/
Public void setusername (string username ){
This. Username = username;
}

}

Create the logonaction component of the controller action

Logonaction verifies the business logic of form data.

Code Listing 6 (logonaction. Java)

Package com. mystruts. Struts. Action;

Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;

Import org. Apache. Struts. action. Action;
Import org. Apache. Struts. Action. actionform;
Import org. Apache. Struts. Action. actionforward;
Import org. Apache. Struts. Action. actionmapping;
Import org. Apache. Struts. Action. actionmessage;
Import org. Apache. Struts. Action. actionmessages;

Import com. mystruts. Struts. savelogon;
Import com. mystruts. Struts. Form. logonform;

/**
* Myeclipse struts
* Creation date: 02-27-2006
*
* XDoclet definition:
* @ Struts. Action Path = "/logon" name = "logonform" input = "/form/logon. jsp" Scope = "request" Validate = "true"
* @ Struts. Action-forward name = "logon_ SC" Path = "/success. jsp"
*/
Public class logonaction extends action {

// ----------------------------------------------------------- Instance variables

// ----------------------------------------------------------- Methods

/**
* Method Execute
* @ Param Mapping
* @ Param form
* @ Param request
* @ Param response
* @ Return actionforward
*/
// After passing the actionform bean verification, the Struts framework automatically calls the execute Method
Public actionforward execute (
Actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response ){
// Todo auto-generated method stub

// Obtain the username in the form data
String username = (string) (logonform) Form). GetUserName ();

// Obtain the userpassword in the form data
String userpassword = (string) (logonform) Form). getuserpassword ();

// Define an invalid user name
String badusername = "admin ";

// Define an invalid password
String baduserpassword = "123456 ";

// Declare an actionmessages object
Actionmessages errors = new actionmessages ();

If (badusername. Equals (username )){

// If the user name verification fails, save the actionmessage object to the actionmessages object errors. Logon. badusername. Error corresponds to the value of Logon. badusername. Error in the message resource file.
Errors. Add ("username", new actionmessage ("Logon. badusername. error", badusername ));

// Save the actionmessages object errors to the request range.
Saveerrors (request, errors );

// Return the actionforward object. The Struts framework forwards the request to the view component logon. jsp and displays the error message through <HTML: errors/>.
Return (New actionforward (mapping. getinput ()));
}

If (userpassword. Equals (baduserpassword )){
Errors. Add ("userpassword", new actionmessage ("Logon. baduserpassword. error", baduserpassword ));
Saveerrors (request, errors );
Return (New actionforward (mapping. getinput ()));
}

// Define the model component savelogon
Savelogon SL = new savelogon ();
SL. setusername (username );
SL. setuserpassword (userpassword );
SL. savetodb ();

// The Controller component saves the savalogon object to the request range. The name of the <login: Present> tag and the name of the <bear: Write> tag in the view component success. jsp
Request. setattribute ("savelogon", SL );

// Clear the actionform bean within the request range because the subsequent request is no longer needed
Request. removeattribute (mapping. getattribute ());

// The Controller component transfers the information to the view component logon. jsp, which corresponds to the name of the forward element in the struts-config.xml
Return (mapping. findforward ("logon_ SC "));
}

}

Create model component savelogon

This model provides the get/set method and the savetodb method. The savetodb method is not implemented in this example.

Code listing 7 (savelogon. Java)

Package com. mystruts. Struts;

/**
* @ Author Administrator
*
*/
Public class savelogon {

Private string username = NULL;
Private string userpassword = NULL;

Public void setusername (string username ){
This. Username = username;
}

Public String GetUserName (){
Return this. Username;
}

Public void setuserpassword (string userpassword ){
This. userpassword = userpassword;
}

Public String getuserpassword (){
Return this. userpassword;
}

Public void savetodb (){

}

}

Run

If the user name and password are empty, the running result is 12, Fig 13, and fig 14.


(Figure 12)

If the user name is admin, run Result 13.


(Figure 13)

If the verification is passed, the running result is 14


(Figure 14)

Summary

1. To reduce coupling, a Java file should be created to store constants. For example, the string badusername = "admin" in logonaction. Java, or the first parameter of request. setattribute ("savelogon", SL.

2 To achieve struts internationalization, support multi-language, the encoding method must be UTF-8.

3 When configuring action, see Figure 9. If redirect is selected, the Action Element in the struts-config.xml has one more attribute, redirect = "true ". The result is that the savelogon object within the request range cannot be obtained in success. jsp.

 

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.