Third, action and exception handling

Source: Internet
Author: User
Tags constant exception handling
first, Action introduction

In Struts2, action is the most important because STRUTS2 is made up of multiple actions, such as the need to use action to distribute the business;

Struts2 compared to Struts1, the use of low-intrusive design , that is, a common Java class can also act as an action, not necessarily inherit or implement the action interface;

Defining an action typically requires following several specifications:

1. Can choose to inherit actionsupport;

2. Override the public String execute () throws Exception method, which is the method that accesses the default call of the action (you can, of course, call any method yourself, this configuration needs to be done in struts.xml);

The properties in the 3.Action class are used to encapsulate HTTP requests, page result data, and when the action is accessed, a property with the same name as the action is assigned through the params interceptor if it has a request parameter.

Action and Actionsupport: used to standardize the handling of action classes;

Second, configure the action

We configure the action in the Struts.xml;

Template:

<struts>
<constant name= "Struts.devmode" value= "true" ></constant>
<package name= "" extends= "Struts-default" namespace= "" >
	<action name= "" class= "" >                <param name= "Name" > xiazdong</param>
   		 <result>1.jsp</result>
	</action>
</package>
</struts>

Configure the action specification:<action> element must be in <package>;

The following is an introduction to the common elements when configuring action;

1.<package>

The package can use several attributes:

(1) Name: The name of the package, by the arbitrary designation can be;

(2) extends: Inherit which parent package, if inherited a parent package, will inherit the parent package action, usually we need to inherit the Struts-default, the package defines the built-in interceptor ;

(3) Namespace: Defines a namespace, or, if not specified, the default namespace , or, if "/", the root namespace;

(4) Abstract: Not commonly used, if true, you cannot define an action;

Example:

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

</package>

default namespace and root namespace:

The default namespace is a very special namespace, and if you want to access an action, you will eventually find it in the default namespace;

such as/aaa/bbb.action, first go to the name space for "/AAA" to find, if not found, go to the default namespace to find Bbb.action;

And the root namespace is just an ordinary namespace;

The URL for accessing an action is usually: http://localhost:8080/ApplicationName/Namespace/ActionName.action;

Lookup rules for namespaces:

such as Http://localhost:8080/StrutsProject/a/b/c/d/aa.action;

1. Find out if the/A/B/C/D namespace exists

If it does not exist, skip to step 2

If it exists, find out if it exists aa.action

If the action does not exist, look in the default namespace for the presence of aa.action;

if it exists;

2. Find out if the/a/b/c namespace exists

If it does not exist, skip to step 3

If it exists, find out if it exists aa.action

If the action does not exist, look in the default namespace for the presence of aa.action;

if it exists;

3. Find out if the/a/b namespace exists

If it does not exist, skip to step 4

If it exists, find out if it exists aa.action

If the action does not exist, look in the default namespace for the presence of aa.action;

if it exists;

4. Find out if A/a namespace exists

If it does not exist, skip to step 5

If it exists, find out if it exists aa.action

If the action does not exist, look in the default namespace for the presence of aa.action;

if it exists;

5. Find out if the/namespace exists

If it does not exist, skip to step 6

If it exists, find out if it exists aa.action

If the action does not exist, look in the default namespace for the presence of aa.action;

if it exists;

6. Find in the default namespace;

2.<action>

The <action> properties are:

(1) Name: Specifies the name of the action, and also the external URL;

(2) Class: Access this action's processing class, do not specify the default is Actionsupport, Actionsupport return value is success, note: The full name of the class must be written;

(3) Method: If not specified, the Execute method is called by default, and if specified, this method is called;

3.<result>

The JSP that defines the return result of the action (which can be any view page, of course);

The common properties of <result> are

(1) The string returned by the Name:action method, which defaults to success;

(2) Type: result type, default is dispatcher, this problem will be explained in detail below;

code example:

<package name= "MyPackage" extends= "Struts-default" namespace= "/" >
		<action name= "loginaction" class= " Org.login.action.LoginAction ">
			<result name=" Success "type=" redirect ">
				<param name=" Location " >/result.jsp</param>
			</result>
			<result name= "error" type= "redirect" >/result.jsp< /result>
		</action>
		
	</package>


the difference between a logical action and a physical action:

The logical action is the action element that is configured in Struts.xml, and the physical action is the actual action class;

If an action class exists with the FUN1 () and Fun2 () methods, you can define two logical actions, although the processing classes are the same;


local results and global results:

The global result is configured in the <global-results> element, and this result mapping relationship works for all action;

Local results are configured in the <action> element, meaning that this result mapping relationship only works on a specific action;

Local results are preferred when local results and global results meet the requirements simultaneously;

The global results are placed in the <package> element and are valid for all action on the package;

Syntax for global results:

<global-results>

<result>

</result>

</global-results>

4.<param>

If it is a child of <action>, it is used to inject values into the action;

Like what

When Helloaction has the name attribute, the Struts.xml contains the following code:

<action name= "Hello" class= "org.xiazdong.HelloAction" >
	<param name= "name" >xiazdong</param>
	<result>/1</result>
</action>


When this action is executed, the Name property is automatically assigned a value;


Third, DMI

Dynamic method invocation, that is, dynamically decide which method to invoke the action, that is, not the pre-configuration decision, such as a page with a login button and a registration button, there is only one action class, there is the login () method and the Regist () method, If you click the Register button, then call the Regist method, if you click the login button, then call the login () method, you can use the dynamic method call;

Note: dynamic method Calls are turned on by default in struts2.3, so no configuration is required, otherwise

<constant name= "Struts.enable.dynamicMethodInvocation" value= "true" ></constant>

Default configuration file: Struts2-core-2.3.1.1.jar\org\apache\struts2\default.properties;

Dynamic method invocation Syntax: Actionname!methodname

Like Loginaction. Login invokes the login method in the Loginaction class;

Example code:

Loginaction.java

Package org.login.action;

Import Com.opensymphony.xwork2.ActionSupport;

public class Loginaction extends actionsupport{
	private String user;
	private String password;
	Private String result;
	Public String Login () throws exception{
		if (user.equals ("Xiazdong") &&password.equals ("12345")) {
			Setresult ("Landing Success");
			return SUCCESS;
		}
		else{
			Setresult ("Landing failed");
			return ERROR;
		}
	}
	Public String regist () throws exception{
		Setresult ("registered successfully");
		return SUCCESS;
	}
	Public String GetUser () {
		return user;
	}
	public void SetUser (String user) {
		this.user = user;
	}
	Public String GetPassword () {
		return password;
	}
	public void SetPassword (String password) {
		this.password = password;
	}
	public void Setresult (String result) {
		This.result = result;
	}
	Public String GetResult () {
		return result;
	}
	
}


login.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
    pageencoding=" Utf-8 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >


Struts.xml

<?xml version= "1.0" encoding= "GBK"?> <!
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 "></constant>
	
	<package name=" MyPackage "extends=" Struts-default "namespace="/">
		<action Name= "Loginaction" class= "org.login.action.LoginAction" >
			<result name= "Success" type= "redirect" >
				<param name= "Location" >/result.jsp</param>
			</result>
			<result name= "error" type = "Redirect" >/result.jsp</result>
		</action>
		
	</package>
</struts>


Four, the use of wildcard characters

We may encounter this situation: many logical actions need to be configured, but there are many similarities in the name, such as:

<action name= "loginaction" class= "org.login.action.LoginAction" >
	<result name= "Success" Type= " Dispatcher ">/result.jsp</result>
	<result name=" error "type=" Dispatcher ">/result.jsp</ result>
</action>
<action name= "registaction" class= "org.login.action.registAction" >
	<result name= "Success" type= "Dispatcher" >/result.jsp</result>
	<result name= "error" type= " Dispatcher ">/result.jsp</result>
</action>

If you use wildcard characters, you can represent:

<action name= "*action" class= "org.login.action. {1} Action ">
	<result name=" Success "type=" Dispatcher ">/result.jsp</result>
	<result name=" Error "type=" Dispatcher ">/result.jsp</result>
</action>

Use "*" in the Name property, and {1}, {2} for the value of the first *, and the second * for the class, method, and result elements;

<action name= "*" > can match any action request, because he is located in the default namespace;

Note: If you match more than one action at the same time, the order is determined unless it is identical;

The {N} expression can be used for the class attribute, method property, and result property;

In result, you can also use ${attributename} to refer to the value of the property of the action class through an OGNL expression;

Like <result>/${name}.jsp.

v. Default action and Default processing class

Are configured under the <package> element;

The default action is to execute this action when all action does not match;

The default processing class refers to the processing class if you do not specify the class attribute, or Actionsupport if it is not specified;

The syntax is as follows:

<default-action-ref name= "ActionName" >

<default-class-ref class= "Action"/>

Vi. type attribute of <result>

Definition of logical and physical views:

The logical view is the return value after the action is processed, which is a string, and the physical view is a JSP page;

1.dispatcher

Default value, associated with the JSP;

2.redirect

Redirect to JSP page, the difference from dispatcher is:

Dispatcher is a server jump; Redirect is a client jump;

3.redirectAction

Redirect to another action class;

<result> Sub-elements <param> you can fill in the following two attributes to specify the action:

<result type= "Redirectaction" >

<param name= "ActionName" >actionname</param>

<param name= "namespace" >namespace</param>

</result>

4. Stream

Generally used for file download, not in detail here ; 5.plainText

The source code used to display the view resource;

To configure plaintext templates:

<result type= "PlainText" >

<param name= "Location" >/index.jsp</param>

<param name= "CharSet" >UTF-8</param>

</result>

Vii. Accessing the servlet

Servletactioncontext can easily get the common objects of the servlet, and in the Execute () method:

		HttpServletRequest request = Servletactioncontext.getrequest ();
		HttpServletResponse response = Servletactioncontext.getresponse ();
		PageContext page = Servletactioncontext.getpagecontext ();
		ServletContext application = Servletactioncontext.getservletcontext ();
		HttpSession session = Request.getsession ();


Get

Add:

Prer Use of Esultlistener

Preresultlistener triggered after executing the action code, before entering the physical view;

The template code is as follows:

actioninvocation invocation = Actioncontext.getcontext (). Getactioninvocation ();
Invocation.addpreresultlistener (New Preresultlistener () {public
	void Beforeresult (actioninvocation invocation, String resultcode) {
		...}
});

Eight, exception handling

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.