Struts program design-Introduction to helloword practice

Source: Internet
Author: User
Tags tld
[Goal]

Implement a simple struts program. The program includes an input page and an output page.

We are used to learning program design from the hello program. Practice has proved that this is the most effective way to get started. Next we will design our first struts Program-hello program. The goal of the hello program is to input a "hello" word from the input box on the input JSP page, and display the "hello" word on the other output JSP page. According to the requirements of the Struts framework, the hello program will include the input JSP file, the output JSP file, the action file, the formaction file, and the configuration file. That is to say, this hello program is a complete struts program that can be run directly on servers such as tomact and resin.

[Background Knowledge]

Previously, people who used servlet to develop application systems deeply felt that it was very painful to embed a large number of HTML code in Java code, so sun launched JSP, solved the problem of embedding HTML code in Java code. But soon programmers know that using JSP to "embed a large number of Java code in HTML code" is the same pain point as "embed a large number of HTML code in Java code. JSP is like this, and ASP is like this. Therefore, Craig R. mcclanahan used the MVC idea to open Java and HTML separation of Java Web applications into different files, which were divided into three parts: struts. Later, microsoft has also learned this separation method, but Microsoft is somewhat lazy and only divided into two parts, namely ASP.. net.

Struts (Org. Apache. Struts) is an open-source Web application framework. Based on the MVC design pattern, it is created using Servlet and JSP APIs and can be used to build complex web applications. It allows us to break down the business logic, control logic, and presentation logic code of an application to make it more reusable and maintainable. The Struts framework is part of the Jakarta project and managed by the Apache Software Foundation. Struts can be downloaded from http://jakarta.apache.org/struts sites.

The Struts framework provides the following services.

Servlet used as the controller in the MVC structure.

JSP is a JSP tag library used for bean management, HTML and JavaScript generation, template processing, and process control.

The framework used for internationalized messages. Internationalization of your Web applications means that your web applications can be displayed in your favorite language during use. This means you need to create an application resource file that contains information for each language.

A jdbc implementation is used to define the data source and database connection pool.

A common error and Exception Handling Mechanism, including reading error information from an application resource file.

XML syntax analysis.

File upload tool.

Registration mechanism.

The presentation layer (view) of a Struts-based application is built using the struts tag Library (taglibs. The request from the customer is passed to the servlet called actionservlet, which serves as the controller. Struts application. All requests that need to be passed through the framework are passed through actionservlet. This actionservlet transmits data from the request to the actionform JavaBean.

Actionform is a JavaBean that represents the input data from a form view component. These forms are generated by JSP using the struts HTML Tag library. This beam is generated by actionservlet with the request parameter. It also requests actionform to verify the validity of the data submitted by the user.

Actionservlet is configured by defining a group of actionmapping. An actionmapping is an object that maps the URL in the request to the request processing component provided by the application developer. The configuration of actionservlet and actionmapping is completed in the XML configuration file.

A dedicated application is called an action class. In the MVC structure, they represent models. They may be used to verify the legality of user input. If an application error occurs during information processing, the action class can create an error object instance and save it in the HTTP request object. If the logic in the action class is successfully passed to the Controller as an actionforward object, the JSP that depicts the response is required. There are two types of actionforward: specifically forwarded to a specific action class or Global Forwarding (any action class can forward these actionforwards to the Controller ).

[STEP]

1. Open the visual struts development environment:

(1) copy the file to a directory on the local hard disk, for example

F:/javawebstudio/

(2) run the javawebstudio.exe file under the bindirectory (a shortcut is automatically created on the desktop at the same time. When you start the second time, you only need to click the shortcut on the desktop). The following startup interface is displayed:

In addition, when you run javawebstudio for the first time, you will be prompted whether to automatically configure environment variables. We recommend that you select automatic configuration.

2. Create an "Empty struts common template" application:

Select "file"-"New"-"New Project" from the menu to bring up the "new project" dialog box.

In the dialog box, select "Empty struts common template" and enter "simple", package (package name), and location (Project path) in the project name) use the default value. You can change the value as needed. Click "OK" to create a new project.

From the file manager, we can see that the file structure of the simple project is as follows:

Simple

+ ------ Config

+ ------ Lib

+ ------ SRC

+ ------ Web

------- Build. xml

------- Hello. prj

The root directory of the simple project contains four sub-directories and two files. This is the standard structure of the jspstudio project. It is best not to change their default names; otherwise, problems may occur.

3. Use the struts file Wizard to create a new application:

Right-click the jspstudio File Manager and choose "struts file wizard" from the shortcut menu to enter the struts file wizard dialog box, you can also choose File> New> struts file Wizard to enter the struts file wizard dialog box.

In the struts file wizard dialog box, enter the "hellword" file name in the file name input column under the JSP file tag. Use the default settings for other files. Click "OK" to complete the struts file wizard.

Refresh the jspstudio File Manager and find that two files are automatically generated under the web directory, respectively, hellword. JSP and hellword. JSP: the former is the input JSP file, the latter is the output JSP file; the src/emptyprj directory automatically generates two files, respectively, hellword action. java and hellword form. java. The former is the action file, and the latter is the formaction file.

4. Compile and start the server:

Click the compile button on the toolbar or select "generate"-"compile" from the menu to start Project compilation. The compilation process and result are displayed in the output column as follows:

C:/Documents and Settings/Administrator/desktop> F:

F:/> Cd F:/javawebstudio/javawebstudioworkdir/simple

F:/javawebstudio/javawebstudioworkdir/simple> ant-buildfile build. xml

Buildfile: Build. xml

Prepare:

[Mkdir] created dir: F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple

[Copy] copying 2 files to F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple

[Mkdir] created dir: F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple/WEB-INF

[Copy] copying 6 files to F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple/WEB-INF

[Mkdir] created dir: F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple/WEB-INF/classes

[Copy] copying 5 files to F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple/WEB-INF/classes

[Mkdir] created dir: F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple/WEB-INF/lib

[Copy] copying 18 files to F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple/WEB-INF/lib

[Mkdir] created dir: F:/javawebstudio/javawebstudioworkdir/wars

Compile:

[Javac] compiling 3 source files

F:/javawebstudio/jakarta-tomcat-5.0.24/webapps/simple/WEB-INF/classes

Dist:

[Jar] building jar: F:/javawebstudio/javawebstudioworkdir/wars/simple. War

Build successful

Total time: 5 seconds

The above output indicates that the project set by compiling build. XML with ant has been successfully compiled. Copy the compilation result to the webapps directory of the Tomcat server and generate the simple. War package.

5. Start the server:

Click the start server button on the toolbar or choose "run"> "start server" from the menu to start the Jakarta-Tomcat server.

6. Run:

Expand the web directory of the simple project in the File Manager. The helloword. Jap and hellowordout. jsp files are displayed. Double-click the helloword. JAP file to open the helloword. JAP file ,. The editing window consists of two parts: the source program editing and the visual editing, which are similar to the Dreamweaver MX editing window.

Click the "run" button on the toolbar or select "run"-"Run (Web browsing)" to display the helloword. jsp running result. Enter "Hello word" in the input box on the running result page and click "Submit". Then, the "Hello word" word is output to the hellowordout. jsp file.

The source code is as follows:

<HTML>

<Meta http-equiv = Content-Type content = "text/html; charset = gb2312">

</Head>

<Body bgcolor = white>

<Base href = "http: // localhost: 8080/simple/helloword. JSP "> <form name =" hellowordform "method =" Post "Action ="/simple/hellowordaction. do; JSESSIONID = cffac422c4a779419348832d588ca5be ">

<Input type = "text" name = "mybeanvariable1" value = ""> <input type = "Submit" value = "Submit"> <input type = "reset" value =" rewrite ">

</Form>

</Body>

</Html>

The source code is as follows:

<HTML>

<Base href = "http: /localhost: 8080/simple/hellowordout. jsp">

</Head>

<Body bgcolor = "white">

Hello word

</Body>

</Html>

[Project file structure]

The Config directory contains all the configuration files and Struts label description files, such as web. XML, struts-config.xml, struts-bean.tld, struts-html.tld, struts-logic.tld and struts-template.tld.

LIB contains struts library files and other library files with, such as Struts. jar, struts-legacy.jar, commons-lang.jar and xerces. Jar files.

The src directory contains original java files and resource files, such as applicationresources. properties and applicationresources_ch.properties. The former is an English resource file and the latter is a Chinese resource file. The new directory contains the sub-directory "emptyprj", which is the same as the package name entered during project creation. The emptyprj directory contains the "filters" and "JDBC" sub-directories. The former is the filter directory and the Chinese solution. For detailed analysis, see the filter program design and Chinese solution chapters, the latter is the database connection pool file. For detailed analysis, see the following struts Database Application Design chapter.

The web directory contains JSP, HTML, and other web files and image files used by web files. This directory is empty when you create a new directory.

Build. XML files are required for compilation. Because jspstudio uses the ant compiler, this file is indispensable in the jspstudio project. It is an ant standard configuration file, the directory structure of all projects also meets the requirements of the ant compiler. It can be seen that the jspstudio project has excellent compatibility with ant, which is also one of the advantages of jspstudio.

The Hello. prj file is a project file with an XML structure. The content is as follows:

<Projectname> simple </projectname>

<Projecttype> struts </projecttype>

<Title> This is an empty struts common template. </title>

<Package> emptyprj </package>

<Typepath>/Jave WEB Project/empty struts common template </typepath>

<Projectpath> F:/javawebstudio/javawebstudioworkdir/simple </projectpath>

<Projectname> the tag contains the project name. <projecttype> the tag contains the project type. Do not change the TAG content. <title> the tag contains a brief description of the project, enter the default package name in the <package> label, the relative path of the Project template in the <typepath> label, and the absolute path saved by the project in the <projectpath> label.

[Key Technologies]

Struts uses the MVC structure. The logic diagram shown in figure 2.1 describes the high-level structure of the Framework.

We will now discuss each element in the graph.

The presentation layer (view) of a Struts-based application is built using the struts tag Library (taglibs. The request from the customer is passed to the servlet called actionservlet, which serves as the controller. Struts application. All requests that need to be passed through the framework are passed through actionservlet. This actionservlet transmits data from the request to the actionform JavaBean.

Actionmapping

Actionform (model data)

Action)

Send

Actionservlet (Controller)

JSP (view)

Taglib (view)

Use

Instantiation

Call

Use

Use

Actionform is a JavaBean that represents the input data from a form view component. These forms are generated by JSP using the struts HTML Tag library. This beam is generated by actionservlet with the request parameter. It also requests actionform to verify the validity of the data submitted by the user.

Actionservlet is configured by defining a group of actionmapping. An actionmapping is an object that maps the URL in the request to the request processing component provided by the application developer. The configuration of actionservlet and actionmapping is completed in the XML configuration file.

A dedicated application is called an action class. In the MVC structure, they represent models. They may be used to verify the legality of user input. If an application error occurs during information processing, the action class can create an error object instance and save it in the HTTP request object. If the logic in the action class is successfully passed to the Controller as an actionforward object, the JSP that depicts the response is required. There are two types of actionforward: specifically forwarded to a specific action class or Global Forwarding (any action class can forward these actionforwards to the Controller ).

In this example, the relationship between the main files is as follows:

Input page:

Helloword. jsp

Actionform (model data)

Hellowordform. Java

Actionservlet (Controller)

Implement through struts-config.xml Configuration

Actionmapping

Input page:

Hellowordout. jsp

Action)

Hellowordaction. Java

[Key source code analysis]

4.3.1 enter the JSP page file

The input JSP page file name is hello. jsp, which mainly implements a form with a text box. The file code is as follows:

<% @ Page contenttype = "text/html; charset = gb2312" 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" %>

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

<HTML: HTML>

<Head>

<Title> </title>

<HTML: base/>

</Head>

<Body bgcolor = "white">

<HTML: Form Action = "/helloaction. Do" method = "Post">

<HTML: Text property = "mybeanvariable1"/>

<HTML: Submit value = "Submit"/>

<HTML: reset value = "Rewrite"/>

</Html: Form>

</Body>

</Html: HTML>

First, define this page to support Chinese display. The Chinese encoding adopts the gb2312 format and the programming language is Java:

<% @ Page contenttype = "text/html; charset = gb2312" Language = "Java" %>

You can define four types of struts tag beans, HTML, logic, and template. You can remove the tags that are not used in the file. If you need to use custom tags in the file, you also need to add the corresponding definition here:

<% @ 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" %>

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

<HTML: HTML>. The <HTML: base/> tag corresponds to the <base> tag of HTML, which is used to set the absolute path of the file in the browser. Then, you only need to write down the relative location of the file in the file, these locations are automatically attached to the absolute path when you test the path in the browser to become the complete path. In this document, all URLs in relative address form are relative to the utrl defined here. The <base> tag cannot be more than one in a document. It must be placed in the

<HTML: Form Action = "/helloaction. Do" method = "Post">

<HTML: Text property = "mybeanvariable1"/>

<HTML: Submit value = "Submit"/>

<HTML: reset value = "Rewrite"/>

</Html: Form>

<HTML: Form> the tag defines a form. The target URL for submission is "/helloaction. do ", the method is" Post ", the POST method is to include the data filled in the form body, and send it together to the processing program on the server, the ten thousand method has no character restrictions. It contains the iso000046 character set. It is a mail-type ten thousand. The submitted information is not displayed in the browser's address bar, there is no limit to this type of data transmitted in a thousand ways. Of course, you can also select the get method. The get method is to append the form content to the URL address. Therefore, the length of the submitted information is limited to a maximum of 8192 characters, if the information is too long, it will be intercepted, resulting in unexpected results, and non-ASCII characters cannot be transmitted. The form contains a text input box <HTML: Text>. Its value corresponds to the variable "mybeanvariable1" in the bean. If mybeanvariable1 is used to pay the initial value, the default value of mybeanvariable1 is displayed in the text box when the page is started. In addition, the form contains the two most common submission buttons <HTML: Submit value = "Submit"/> and rewrite button <HTML: reset value = "Override"/>.

4.3.2 output JSP page file

The output JSP page file name is helloout. jsp, which mainly implements the value of the text box submitted by the input file. The file code is as follows:

<% @ Page contenttype = "text/html; charset = gb2312" 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" %>

<HTML: HTML>

<Head>

<Title> </title>

<HTML: base/>

</Head>

<Body bgcolor = "white">

<HTML: HTML>

<Head>

<Title> </title>

<HTML: base/>

</Head>

<Body bgcolor = "white">

<Bean: write name = "helloform" property = "mybeanvariable1"/>

</Body>

</Html: HTML>

</Body>

</Html: HTML>

The only difference between the output file and the previous input file is that the <HTML: Form> tag is changed to the <Bean: Write> tag:

<Bean: write name = "helloform" property = "mybeanvariable1"/>

<Bean: Write> the tag outputs the bean property value. The name stores the bean name, which is "helloform". From the configuration file below, we can see that the corresponding class is the helloform class; property stores the property name. Here is "mybeanvariable1", which is the same as the attribute name in the text box of the input file.

4.3.3 actionform bean File

The actionform bean file of the hello program contains only one variable bean. The file name is helloform. java. The file code is as follows:

Package emptyprj;

Import javax. servlet. http. httpservletrequest;

Import org. Apache. Struts. Action. actionerror;

Import org. Apache. Struts. Action. actionerrors;

Import org. Apache. Struts. Action. actionform;

Import org. Apache. Struts. Action. actionmapping;

Public final class hellowordform extends actionform

{

Private string mybeanvariable1;

Public String getmybeanvariable1 ()

{

Return (this. mybeanvariable1 );

}

Public void setmybeanvariable1 (string mybeanvariable1)

{

This. mybeanvariable1 = mybeanvariable1;

}

}

First, define the package name:

Package emptyprj;

The default package name emptyprj of jspstudio is selected. Note that the package name must correspond to the directory name. Next, we introduce five common classes of httpservletrequest, actionerror, actionerrors, actionform, and actionmapping in the actionform bean design. This is automatically added by jspstudio. In fact, the helloform class is only used for the actionform class, other parts can be deleted, but they are retained here for future extension.

Import javax. servlet. http. httpservletrequest;

Import org. Apache. Struts. Action. actionerror;

Import org. Apache. Struts. Action. actionerrors;

Import org. Apache. Struts. Action. actionform;

Import org. Apache. Struts. Action. actionmapping;

The next step is to define helloform, a parameter mybeanvariable1 and its corresponding get () and set () functions, which are exactly the same as the methods defined by common beans.

4.3.4 action file

The action file of the hello program processes the form submitted by the input file. The file name is helloaction. java. The file code is as follows:

Package emptyprj;

Import java. Lang. Reflect. invocationtargetexception;

Import java. util. locale;

Import javax. servlet. servletexception;

Import javax. servlet. http. httpsession;

Import javax. servlet. http. httpservletrequest;

Import javax. servlet. http. httpservletresponse;

Import org. Apache. commons. beanutils. propertyutils;

Import org. Apache. commons. Logging. log;

Import org. Apache. commons. Logging. logfactory;

Import org. Apache. Struts. action. Action;

Import org. Apache. Struts. Action. actionerror;

Import org. Apache. Struts. Action. actionerrors;

Import org. Apache. Struts. Action. actionform;

Import org. Apache. Struts. Action. actionforward;

Import org. Apache. Struts. Action. actionmapping;

Import org. Apache. Struts. Action. actionservlet;

Import org. Apache. Struts. util. moduleexception;

Import org. Apache. Struts. util. messageresources;

Public final class hellowordaction extends action

{

// Variable definition:

Private log = logfactory. getlog ("org. Apache. Struts. webapp. Example ");

// Function Definition:

Public actionforward execute (actionmapping mapping,

Actionform form,

Httpservletrequest request,

Httpservletresponse response)

Throws exception

{

// Extract attributes and parameters we will need

Locale locale = getlocale (request );

Messageresources messages = getresources (request );

Httpsession session = request. getsession ();

Hellowordform myform = (hellowordform) form;

String variable1 = myform. getmybeanvariable1 ();

Try

{

If (variable1.trim (). Equals (""))

{

Return new actionforward (mapping. getinput ());

}

// Other code

Return (mapping. findforward ("success "));

}

Catch (exception E)

{

// Log. Error ("error", e );

// Log. Trace ("error ");

Throw new runtimeexception (E. getmessage ());

}

}

}

First, define the processing function execute (). It can be understood that when the hello input file form is submitted to the actionservlet of the server, the actionservlet calls the execute () function of action to implement business logic processing, after the processing is complete, the result is forwarded to the output file. The execute () function defines a helloform instance "myform", reads data from the submitted input actionform object instance form, and assigns the value of mybeanvariable1 to the new string variable variable1:

Helloform myform = (helloform) form;

String variable1 = myform. getmybeanvariable1 ();

The next step is error handling. The try statement is used to combine a code block that causes an exception. It tells Java to note that an exception may occur. Catch: once an exception is thrown, capture this exception. The Catch statement allows the programmer to define a capture. Finally: at the end of the try/Catch Block, the program may need to ensure that a code block is always executed no matter whether an exception is thrown or not, for example, whatever happens, we may need to ensure that a specific file is closed; implicit Tlon: A class used to store information about an "exception" or "error" found in the Code; throws: An exception occurs when something needs to be noticed. This exception was caught by a special code we created to handle the exception ". By throwing an exception, we tell the code that an error occurs and special logic needs to be called to handle the problem. The complete process is completed as follows:

Try

{

// Normal code

}

Catch (exception E)

{

// Error handling code

Throw new runtimeexception (E. getmessage ());

}

Finally

{

// The final processing code that must be performed

}

In the try block, the variable variable1 is null. If it is null, it is forwarded to the input page. Otherwise, it is forwarded to the output page defined as success:

If (variable1.trim (). Equals (""))

{

Return new actionforward (mapping. getinput ());

}

// Other code

Return (mapping. findforward ("success "));

The mapping. getinput () function is used to get the URL value of the input page, which corresponds to the input property value of the <action> item in the configuration file struts-config.xml.

4.3.5 struts program Configuration

<? XML version = "1.0" encoding = "ISO-8859-1"?>

<! Doctype Struts-config public

"-// Apache Software Foundation // DTD struts configuration 1.0 // en"

Http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd>

<Struts-config>

<Form-beans>

<Form-bean name = "hellowordform"

Type = "emptyprj. hellowordform"/>

</Form-beans>

<Action-mappings>

<Action Path = "/hellowordaction"

Type = "emptyprj. hellowordaction"
Name = "hellowordform"

Scope = "session"

Input = "/helloword. jsp">

<Forward name = "success" Path = "/hellowordout. jsp"/>

</Action>

</Action-mappings>

</Struts-config>
 

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.