Strts2 Result View and Action Type

Result View

1. Result View Concept
The return value of action method is String type. It returns the name of the corresponding result view. In action class, return keyword is used to express it. In corresponding struts.xml file, tag is used to express it.
2. Result View Properties

<result name="success" type="dispatcher">/jsp/success.jsp</result>
Label name explain
name This is the name, which needs to be consistent with the name return ed in the action class
type This is the way the result view jumps, and the default is dispatcher, which means the content enclosed in the request forwarding value is the path of the jump.

3. Result View TYPE

type Name
type="dispatcher" Request forwarding, address bar unchanged, default value
type="redirect" Redirection, address bar change, prevent refresh
type="chain" The request is forwarded to an action action class with the address bar unchanged
type="redirectAction" Redirect to an action action class, address bar changes
type="stream" File upload and download

tips: When the TYPE type is redirected, just write another action name for the enclosed content.

Cross-package redirection
To redirect across packages to another action, you need to specify namespaces and parameters with the help of tags. Note, however, that if two are not distinguished using namespace, they are not considered cross-package operations, redirectAction access. You can still use chain directly or

<result>
    <param name="namespace">/user</param>
    <param name="actionName">user</param>
</result>

4. Global Result View

If the label is written in a certain area, it is called the local result view, which is only valid for the label, and if the label is written out, it is called the global result view, which is valid for all. The result is the view path to be returned, and the name is the name of the result. To correspond to the return string in the action, the type is a jump.
4.1 Global Result View in Package

<package>
    <global-results>
        <result name="error">error.jsp</result>
    </global-results>
    <action>...</action>
</package>

4.2 Out-of-package global result view

<!--take global-result Put it in a common parent package-->
<package name="basePackage" extends="struts-default" abstract="true">
    <global-results>
        <result name="error">error.jsp</result>
    </global-results>
</package>
<package name="p1" extends="basePackage"></package>
<package name="p2" extends="basePackage"></package>

5. Return to JSON

Struts 2 has good support for JSON types, but needs to import an additional jar package.

<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-json-plugin -->
<dependency>
	<groupId>org.apache.struts</groupId>
	<artifactId>struts2-json-plugin</artifactId>
	<version>2.5.14.1</version>
</dependency> 

[HTML Page Side]

<div>ajax Version login</div>
<form id="form1">
	<input name="login.loginname" type="text" />
	<input name="login.loginpass" type="password" />
	<button type="button" id="btn1">Sign in</button>
</form>


[JS End: Through ajax Pass the form in to action in]
$(function(){
    $("#btn1").on("click",function(){
        $.ajax({
            url : "/My_S25H431/loginAction!loginByAjax.action",
            type: "post",
            data: $("#form1").serialize(),
            success:function(response){
                // This return value is the JSON set of all objects in your action that have set/get methods
                // You can get the value you want directly from it.
                //console.log(response);
                if(response.status){
                    alert("Log in successfully!");
                    location.href="/My_S25H431/html/main.html";
                }else{
                    alert("Logon failed!");
                    location.href="/My_S25H431/index.html";
                }
            }
        });
    });
});

[action End: Normal return´╝îNo need to acquire response object]
private Boolean status;// set/get
public String loginByAjax() {
	if(service.login(login)) {
		status=true;// Successful login
	}else {
		status=false;// Logon failure
	}	
	return "ajaxResponse";
}

[struts.xml end: changing the type type of package inheritance and result]

The json-default package also inherits struts-default

<package name="package2" strict-method-invocation="false" extends="json-default">
	<action name="loginAction" class="com.xhh.action.LoginAction">
		<result name="ajaxResponse" type="json"></result>
	</action>
</package>

Action type

1. Ordinary bean s as action classes

Method Modification: public
Method return value: String
Method parameters: No need
Method Name: Default execute: When you do not set method in the xml file, you will automatically find the execute method.

2. Implementing Action Interface

To have a normal bean implement an Action interface is to provide more scenario constants than the first one.

SUCCESS returns the success page (you must set the name of result = "success")
NONE does not return any pages, nor does it report errors
ERROR returns the error page
INPUT returns to jump back to the form page when an error occurs in submitting the form
LOGIN returns to the login interface

3. Inheriting the ActionSupport class

Common bean s inherit the ActionSupport class, which is commonly used in development.

4. Action life cycle

The life cycle of an Action is a request.

Create: Each request creates an Action object (non-singleton, thread-safe).
Destruction: When the Action action class executes the method, it disappears.

5. Wildcard Action Class Access

Using wildcards to access an Action can achieve an Action configuration to enable multiple Action access. However, multiple wildcard access configurations cannot exist in the same package.
5.1 Action Class

Create four methods in TestAction.java with the same name.

public String createUser(){
    System.out.println("Create a user");
    return "tocreate";
}
public String retrieveUser(){
    System.out.println("Query a user");
    return "toretrieve";
}
public String updateUser(){
    System.out.println("Modify a user");
    return "toupdate";
}
public String deleteUser(){
    System.out.println("Delete a user");
    return "todelete";
}

5.2 struts.xml

<package name="pa0" extends="struts-default" strict-method-invocation="false">
    <action name="*User" class="com.xhh.action.TestAction" method="{1}User">
        <result name="{1}">/jsp/{1}User.jsp</result>
    </action>
</package>

{
tips: strtus version 2.5 must add strict-method-invocation= "false"

5.3 Access
http://127.0.0.1:8080/project name/createUser
http://127.0.0.1:8080/project name/retrieveUser
http://127.0.0.1:8080/project name/updateUser
http://127.0.0.1:8080/project name/deleteUser

6. Dynamic Access Action

6.1 Privileges to Open Dynamic Access

Modify the struts.xml file as follows:

<constant name="struts.enable.DynamicMethodInvocation" value="true" />

Version 2.5, with some changes, you need to change the strict-method-invocation value to false.

<package name="" extends="struts-default" strict-method-invocation="false">

6.2 Dynamic Access
http://127.0.0.1:8080/180512_j232/user!xxx.action

7. Get the Servlet API

In Action, we can also get some application program interfaces of the servlet to achieve the joint development effect of action+servlet.

7.1 built-in acquisition method

Use ServeltAction Context to obtain request and session and application actions

HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = ServletActionContext.getRequest().getSession();
ServletContext application = ServletActionContext.getServletContext();

7.2 Interface Acquisition Method

After implementing the ServletRequestAware interface, the setServletRequest method is implemented, and the request attribute corresponding to the setServletRequest method is set. After assigning the value in the setServletRequest method, the request can be obtained by reflection, the rest like response and application action, and so on.

tips: the red circled parts all need to be written by hand.
tips: HttpSession can be obtained by request.getSession(). (Better than Session Aware)
tips: this method is relatively cumbersome and is generally not recommended.

Tags: Struts JSON JSP xml

Posted on Sun, 04 Aug 2019 00:15:57 -0700 by first_lady_the_queen