Learn Struts2 By example-Starting from Struts-blank (1) _struts2

Source: Internet
Author: User
Tags getmessage tomcat server apache tomcat

Recently found a number of websites in Copy&paste my article, please respect my labor results, reproduced in the time marked the source, thank you.

Objective

has been using STRUTS1, now the new project to turn to STRUTS2, first study to learn, do some technical reserves.

I have always thought that the computer software industry is a very practical industry, the book read how much does not work, must roll up their sleeves, hands-on, to learn the essence of a technology, can talk about proficiency.

Otherwise floating in the surface, only understand the concept, Kua Kua yarn, one into the real project on the dumbfounded.

But oneself completely from zero to learn a technology is still too slow, must find a cut-in point, like war, concentrated advantage strength, from a point of breakthrough, to the depth of development, circuitous flank, each annihilation.

This entry point is the excellent source code, see how Daniel is doing, and then imitate learning, can greatly reduce the time you study.

There are many books on the market now, Struts2 Authority, Encyclopedia, Guide, a mixed bag, my point is to not rush to read them, first find a booklet to understand the basic knowledge, and then find excellent STRUTS2 Project Code learning, in learning to think, not only to know what, How to ask yourself a few why, imagine if you want to design, what you will do, and then the design of struts and contrast, so as to truly improve.

As for those "authority/encyclopedia/guide", I will be more used to find technical details, as a reference book.


Based on this idea, we first searched the web for a INFOQ book << a simple struts2>>, and it was a very quick way to build a basic impression.

As for the excellent Struts2 project code, did not find the right, decided to take STRUTS2 application to study, after all, is the official production, not to where.

Which students know better use of STRUTS2 project source code, please do not hesitate to enlighten.


Setting up the environment

That's a lot of crap, so get started.

To prepare the environment first:
1. Download source from STRUTS2 official website: http://struts.apache.org/release/2.1.x/, write this article when version is struts-2.3.15.1, pay attention to download that full distribution, will contain source code and examples
2. Development tools, of course, download a "Eclipse IDE for Java EE developers from http://www.eclipse.org/downloads/," which can be used with Web server and Applicati On server integration
3. Use Tomcat to do the Web server: http://tomcat.apache.org/, I downloaded the version is 7.0.42


Unzip the downloaded struts2, there is a Struts-2.3.15.1/apps directory, which is all we want to project examples

The war packages here can be run directly into Tomcat, but for the sake of research, we need to untie them, don't tell me you don't know how to unpack the war file.:-)

From the name to see Struts2-blank.war simplest, decompression open probably like this


Start Eclipse startup, add an Apache Tomcat 7 server enviroment to the Preferences-> server-> Runtime Runtime, the process will not be said, I believe that all students can Easy to handle.


To create a dynamic Web project, the name is called Struts2-blank Bar, and then the important steps are:

(1) Copy all the files in the above picture to the webcontent of the new project, and if Eclipse prompts to overwrite the file, select Yes

(2) Then copy all files under Web-inf/src/java to the SRC directory of the Struts-blank project------This is the real source code.

(3) Delete the Web-inf/src directory, empty the web-inf/classes directory----These directories are useless

The best system looks like this:


Build a TOMCAT7 server to deploy the project, and then add Struts2-blank to the server, start the server, and you can see that Tomcat server is starting, then the log of struts2 started

Running http://localhost:8080/struts2-blank/in a browser will see the simplest interface:

It seems like a lot of effort, in fact it is quite simple, the reason to build an eclipse environment, mainly to see the source code convenience.

For other examples of Struts2, you can do the same with your classmates.

Struts2 Blank Project

Finally can start to look at the source code, the first cause I notice is struts.xml, is directly placed in the Eclipse Project SRC directory, which means that the runtime eclipse will automatically copy it to the Web-inf/classes directory, and compiled Java class files together, and in Struts1, the configuration file, called Struts-config.xml, is placed directly under the Web-inf directory, which is a big difference.

Open this file and take a look:

<constant name= "Struts.devmode" value= "true"/> <---must be the specified development mode

<package name= "Default" namespace= "/" extends= "Struts-default" >

<default-action-ref name= "index"/> <---Specify the default action reference, defined below
<global-results>
<result name= "error" >/error.jsp</result> <---Global result, if the action results in error, you can use it
</global-results>

<global-exception-mappings>
<exception-mapping exception= "java.lang.Exception" result= "error"/> <---This function is good, all code anomalies are mapped to error this result
</global-exception-mappings>

<action name= "Index" >
<result type= "redirectaction" > <---Invoke another action: "/example/helloworld", namespace actually refers to the URL
<param name= "ActionName" >HelloWorld</param>
<param name= "namespace" >/example</param>
</result>
</action>
</package>

<include file= "Example.xml"/> <---good, can include other files, modular better, easier to support team development


Come back to see Example.xml

    <package name= "Example" namespace= "/example" extends= "Default" > <---Note namespace is/example, That is, all the action calls under this package have to be written like this: 
                                                                    <---http://xxxx/structs-blank/example/xxxx

        <action name= "HelloWorld "Class=" example. HelloWorld ">   <---It is obvious that the action implementation class here is HelloWorld, and it can be guessed that execution success will call
                                                                <---helloworld.jsp
             < Result>/example/helloworld.jsp</result>
        </action> ...
    </package>


Get a peek at Helloworld.java.
public class HelloWorld extends Examplesupport {
    //No doubt, this method will be invoked, set a message key (Helloworld.message) and then return to sucess, 
    In the package.properties can see Helloworld.message, but struts2 exactly how to call it. Don't worry,
    /write down the problem, read the whole process first
   . Public String Execute () throws Exception {  
        setmessage (message);          
        return SUCCESS;                         
    }

    /**
     * Provide default Valuie for message property.
     * * Public
    static final String message = "Helloworld.message";

    /**
     * Field for message property.
     * *
    private String message;

    /** * Return message property
     .
     *
     * @return Message Property
     *
    /Public String getMessage () {return message
        ;
    }

    /**
     * Set message property.
     *
     * @param message Text to display on HelloWorld page.
     *
    /public void Setmessage (String message) {
        this.message = message;
    }
}

In helloworld.jsp, there is such a

So, the basic process is over, and we see that the Struts2 action definition is in Struts.xml (and other XML files that are contained), and the Execute method of the action is invoked, The value of the property set in the action can be referenced in the JSP.

There seems to be something missing, and by the struts2, what is the configuration that works. The answer, of course, is in Web.xml.

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class> Org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</ Url-pattern>
    </filter-mapping>


Unlike Struts1, Struts2 uses a filter to handle all requests.

If you have struts2 development experience before, you may notice that the use of this is not filterdispatcher, but strutsprepareandexecutefilter.

This is because for the old version of Struts2, the use of Filterdispatcher, for the 2.1.3 above the version, it began to use Strutsprepareandexecutefilter

Let's call it a day and take a closer look at the other branches tomorrow.







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.