STRUTS2 environment Construction and first procedure

Source: Internet
Author: User

Environment construction

Project Directory

Import the dependent jar package, as shown in the Lib directory.

Different versions may not be the same, it doesn't matter when Tomcat starts, if the error java.lang.ClassNotFoundException, we can add the appropriate jar package according to the wrong prompt.

Configuring the Struts2 filter in Web. XML

The filter org.apache.struts2.dispatcher.FilterDispatcher of STRUTS2 is configured in the project's Web. xml file, which, by default, intercepts a request that ends in a. Action in the request string and delegates the request to the specified a ction for processing.

Add the following code to 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>

Note: You can set the path of the Struts.xml configuration file by adding the <init-param> child element to the filter element. If the <param-name>config</param-name> parameters are set, the files that are loaded by the original struts2, such as Struts-default.xml, are also manually specified, otherwise they will not be loaded automatically.

Struts-default.xml path to write a struts applet under the struts2-core-2.x.x jar package

1. Create a class to store the welcome message (model)

2. Create a Server Page rendering message (view)

3. Create a page submit user request parameters (form)

4. Create an action class to control interactions between users, models and Views (Controller)

5. Create a mapping (struts.xml) to describe the relationship of the action class and the view. 1. Storing Message Messagestore.java

Package Hello;public class Messagestore {     private String message;        Public Messagestore () {                         setmessage ("Hello Struts User");             Public String GetMessage () {                 return message;        }             public void Setmessage (String message) {                 this.message = message;        }        Public String toString () {            return message;        }}
2. Render Message hello.jsp

Here is a simple use of some struts tags, get Action property values, simplify the display of information. Before that, we need to introduce the Struts tag library

The Struts2 attribute is marked as <S:PROPERTY>, with the following usage in the main.

1. Display the property value in action: <s:property value= "property name"/>
2. Display the string, using single quotation marks: <s:property value= "' String '"/>
3. Displays the default value, when the specified property is not found in the action, displays the value of the default property: <s:property value= "property name" default= "Default"/>
4. Parse HTML string, escape default value is True, direct output string, escape set to False, parse HTML string: <s:property value= "' <font color=\" red\ ">red </font> ' "escape=" false "/>

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%@ taglib prefix= "s" uri= "/struts-tags" %><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
3. Submit the Request index.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%@ taglib prefix= "s" uri= "/struts-tags" %><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
4. Handling User Requests Helloaction.java

Helloaction inherits Actionsupport, acting as the controller's role for:

1. Accept user's request parameters

2. Handling user requests (or invoking logical processing)

3. Returns the result of string type, telling struts what view to render.

Accept Request Parameters

Set the parameter properties in action, add getter and setter methods, let action autofill, and do the appropriate type conversions.

Processing Requests

We can process the user's request in the Execute method, directly processing the request parameters or invoking the service's method. The method has a string-type return value that tells struts what view should be returned to the user.

Package Hello;import Com.opensymphony.xwork2.actioncontext;import Com.opensymphony.xwork2.actionsupport;public        Class Helloaction extends Actionsupport {private static final long serialversionuid = 1L;        private static int hellocount = 0;        Private Messagestore Messagestore;        Private String user;            Public String Execute () throws Exception {Messagestore = new Messagestore ();            hellocount++;            Actioncontext.getcontext (). GetSession (). Put ("user", user);        return SUCCESS;        } public Messagestore Getmessagestore () {return messagestore;        } public void Setmessagestore (Messagestore messagestore) {this.messagestore = Messagestore;        } public String GetUser () {return user;        The public void SetUser (String user) {this.user = user;        } public int Gethellocount () {return hellocount; } PublIC void Sethellocount (int hellocount) {this.hellocount = Hellocount; }}
5.struts.xml Configuration

We will define the mapping relationship between the result string and the resource in Struts.xml, that is, the view that defines the string returned by the Execute method of the action.

Create the Struts.xml file under the project Classpath, which is the Struts2 configuration file, where you can configure actions, beans, interceptor, and so on in the Struts.xml file.

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public    "-//apache software foundation//dtd struts Configuration 2.0//en"    "/http Struts.apache.org/dtds/struts-2.0.dtd "><struts>    <constant name=" Struts.devmode "value=" true "/ >    <package name= "basicstruts2" extends= "Struts-default" >        <action name= "Hello" class= "hello." Helloaction "method=" execute ">            <result name=" Success ">/Hello.jsp</result>        </action>    </package></struts>

Note: The classpath of the Web application refers to the Web-inf/classes directory, which, in Eclipse, is automatically copied to the Web-inf/classes directory after the files that are created in the SRC directory are eventually published.

The code Listing 3 involves a lot of tags, and here's a simple explanation:

label name

Include

contain other XML file, in the example, this means that the Struts.xml You can access the defined Struts-default.xml the components in the file.

This element can make Struts2 define multiple configuration files, "Divide and conquer".

It is important to note that any one struts2 the configuration file should both be Struts.xml have the same format, including DOCTYPE , and can be placed anywhere under the classpath.

Package

to be Action or intercept block.

name : Name, required, name custom, but not the same. Convenient for other package references.

extends : Package can inherit the other Package , which is implemented by this property, and the value is another Package of the name .

in the example, extends = "Struts-default" is from Struts-default.xml inherited from the.

Action

definition action , name class action

Result

according to Action The return value defines the page navigation.

Action the predefined return values are:

String SUCCESS = "SUCCESS";

String NONE = "None";

String ERROR = "error";

String INPUT = "input";

String LOGIN = "Login";

For example, when Action return SUCCESS when you want to go to ok.jsp page, you can write this:

<result name= " Success " >ok.jsp</result>

wherethe default name is success.

SOURCE download

I have already packaged the project code (LIB does not import the jar package)

Struts2 HelloWorld

STRUTS2 environment Construction and first procedure

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.