Struts2的使用注解配置Action(零配置)

时间:2022-05-12 08:12:14

1.首先引入struts2注解的jar包:struts2-convention-plugin.jar

Struts2的使用注解配置Action(零配置)

------------------------------第一种方式-------------------------------------

2.struts的配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts>
<package name="lxyPackage" extends="json-default" namespace="/"> <!-- S QLQ 增加的培训类别管理 -->
<global-results>
<result name="success" type="json">
<param name="root">response</param>
</result>
</global-results>
</struts>

3.TestAnnotationAction.java(测试JSON,跳转,重定向三种方式)

package cn.xm.exam.action.trainContent;

import java.util.HashMap;
import java.util.Map; import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; @Controller
@Scope("prototype") // 多例
@Namespace("/")
@Results({ @Result(name = "tiaozhuan", location = "/view/testPerson/outEmployeeAllot.jsp"),
@Result(name = "redirect", type = "redirect", location = "/view/testPerson/outEmployeeAllot.jsp") })
@ParentPackage("lxyPackage") // 属于哪个package
public class TestAnnotationAction extends ActionSupport {
private Map response; @Action("/test1")
public String test1() {
response = new HashMap();
response.put("hello", "hello");
return SUCCESS;
} @Action("/test2")
public String test2() {
return "tiaozhuan";
} @Action("/test3")
public String test3() {
return "redirect";
} public Map getResponse() {
return response;
} public void setResponse(Map response) {
this.response = response;
} }

4.测试:

(1)测试返回JSON

Struts2的使用注解配置Action(零配置)

(2)测试转发

Struts2的使用注解配置Action(零配置)

 (3)测试重定向

访问:  http://localhost/Exam/test3.action

Struts2的使用注解配置Action(零配置)

------------------------------第二种方式(注解返回JSON、跳转、重定向)-------------------------------------

pom.xml依赖:

        <dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.24</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.24</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.3.24</version>
</dependency>

struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts>
<constant name="struts.i18n.encoding" value="utf-8"></constant>
<constant name="devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<!-- 配置拦截的后缀 -->
<constant name="struts.action.extension" value="action,do" /> <package name="default" extends="json-default"></package> </struts>

测试代码:

package cn.qlq.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result; import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable; @Namespace("/")
@ParentPackage("default")
public class FirstAction extends ActionSupport implements Preparable { private static final long serialVersionUID = 1L;
private String test;
@Override
public void prepare() throws Exception {
System.out.println("这是所有方法前的处理");
} @Action(value = "test",
results = { @Result(name = "success1", location = "/index2.jsp", type = "redirect") ,
@Result(name = "error", location = "/index2.jsp") ,
@Result(name = "success" ,type = "json" , params = {"root","test"})
})
@Override
public String execute() throws Exception {
test = "test";
return super.execute();
} public String getTest() {
return test;
} public void setTest(String test) {
this.test = test;
} }

注意:

  @Result的type值默认为dispatcher(转发)。

  如果普通页面跳转和重定向,不需要指定ParentPackage属性。

  如果需要返回JSON,需要指定ParentPackage属性,否则找不到JSON结果类型,params = {"root","test"}是将test属性作为JSON返回前台,如果不指定参数会将所有带get、set的属性以JSON形式返回前台。

  如果希望某些属性不被转为JSON返回前台,可以:

@JSON(serialize=false)//不被序列化  

 

补充:

  网上说注解配置必须继承ActionSupport,经过测试不继承ActionSupport也是可以的。上面的是单独的没和spring整合的注解配置,发现是多例模式,每次请求都会创建Action对象。

------------------------------第三种:和spring整合的注解----------------

pom配置:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.xm</groupId>
<artifactId>jwxt</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>jwxt Maven Webapp</name>
<url>http://maven.apache.org</url> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency> <!-- 调试过程中自己加的包依赖包 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-rc1</version>
</dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-rc1</version>
</dependency> <!--EL和JSTL -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> <dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.24</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.24</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.3.24</version>
</dependency>
<!-- slf4j 依赖包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-rc1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-rc1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.24</version>
</dependency>
</dependencies> <build>
<!-- 配置了很多插件 -->
<plugins> <!-- 编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>

spring配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 扫描Action基本包 -->
<context:component-scan base-package="cn.qlq.action"></context:component-scan> </beans>

struts配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts>
<constant name="struts.i18n.encoding" value="utf-8"></constant>
<constant name="devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="" value="true" />
<!-- 配置拦截的后缀 -->
<constant name="struts.action.extension" value="action,do" />
<!-- 与spring整合 -->
<constant name="struts.objectFactory" value="spring"></constant>
<package name="default" extends="json-default"></package> </struts>

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Struts</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!-- spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <!-- struts -->
<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> </web-app>

测试:

package cn.qlq.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; @Namespace("/")
@ParentPackage("default")
@Controller("firstAction")
@Scope("singleton")
public class FirstAction extends ActionSupport{ private String test; public FirstAction() {
System.out.println("-----------无参构造方法---------");
} @Action(value = "test", results = { @Result(name = "success1", location = "/index2.jsp", type = "redirect"),
@Result(name = "error", location = "/index2.jsp"),
@Result(name = "success", type = "json", params = { "root", "test" }) })
public String execute() throws Exception {
test = "test";
return "success";
} public String getTest() {
return test;
} public void setTest(String test) {
this.test = test;
} }

发现上面无论我们写不写@Controller都可以生成Action对象,写不写scope都是多例模式,即使写成单例也是多例。

补充:有时候我们希望简化配置,不想每个方法都写一对Action注解,如下:(先结果写在类注解上,然后每个方法只写对应的Action的value即可)

package cn.qlq.action;

import java.util.HashMap;
import java.util.Map; import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; @Namespace("/")
@ParentPackage("default")
@Controller("firstAction")
@Results({ @Result(name = "redirect", location = "/index2.jsp", type = "redirect"),
@Result(name = "forward", location = "/index.jsp"),
@Result(name = "json", type = "json", params = { "root", "responseMap" }) })
public class FirstAction extends ActionSupport { private Map<String, Object> responseMap = new HashMap<String, Object>(); public FirstAction() {
System.out.println("-----------无参构造方法---------");
} @Action(value = "getJson1")
public String getJson1() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
responseMap.put("str1", "str1");
return "json";
} @Action(value = "getJson2")
public String getJson2() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
responseMap.put("str2", "str2");
return "json";
} @Action(value = "redirect")
public String redirect() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
responseMap.put("redirect", "redirect");
return "redirect";
} @Action(value = "forward")
public String forward() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
responseMap.put("forward", "forward");
return "forward";
} public Map<String, Object> getResponseMap() {
return responseMap;
} public void setResponseMap(Map<String, Object> responseMap) {
this.responseMap = responseMap;
} }

结果:

Struts2的使用注解配置Action(零配置)

Struts2的使用注解配置Action(零配置)

Struts2的使用注解配置Action(零配置)

Struts2的使用注解配置Action(零配置)

控制台:(证明Action是多例的,每个请求都会创建新的Action)

Struts2的使用注解配置Action(零配置)

有时候我们也希望方法上的注解覆盖类上的注解,例如:

package cn.qlq.action;

import java.util.HashMap;
import java.util.Map; import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; @Namespace("/")
@ParentPackage("default")
@Controller("firstAction")
@Results({ @Result(name = "redirect", location = "/index2.jsp", type = "redirect"),
@Result(name = "forward", location = "/index.jsp"),
@Result(name = "json", type = "json", params = { "root", "responseMap" }) })
public class FirstAction extends ActionSupport { private Map<String, Object> responseMap = new HashMap<String, Object>(); public FirstAction() {
System.out.println("-----------无参构造方法---------");
} @Action(value = "getJson1")
public String getJson1() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
responseMap.put("str1", "str1");
return "json";
} @Action(value = "getJson2")
public String getJson2() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
responseMap.put("str2", "str2");
return "json";
} // 希望返回是json的时候还是页面跳转
@Action(value = "getJson3", results = { @Result(name = "json", location = "/index.jsp") })
public String getJson3() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
responseMap.put("str3", "str3");
return "json";
} @Action(value = "redirect")
public String redirect() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
responseMap.put("redirect", "redirect");
return "redirect";
} @Action(value = "forward")
public String forward() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
responseMap.put("forward", "forward");
return "forward";
} public Map<String, Object> getResponseMap() {
return responseMap;
} public void setResponseMap(Map<String, Object> responseMap) {
this.responseMap = responseMap;
} }

测试:

Struts2的使用注解配置Action(零配置)

总结:方法上的结果返回的定义优先级别高于类级别的返回结果定义,所以我们可以在配置中采用此方式简化一些配置。