Struts2的使用注解配置Action(零配置)
1.首先引入struts2注解的jar包:struts2-convention-plugin.jar
------------------------------第一种方式-------------------------------------
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
(2)测试转发
(3)测试重定向
访问: http://localhost/Exam/test3.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;
} }
结果:
控制台:(证明Action是多例的,每个请求都会创建新的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(零配置)的更多相关文章
- struts2 codebehind + actionPackages 实现Action零配置
1.jar包:struts2-codebehind-plugin-2.2.1.1.jar 2.struts.xml:<!-- codebehind中查找action的返回结果资源时的默认文件夹 ...
- struts2 Convention插件零配置,使用注解开发
从struts21开始,struts2不再推荐使用codebehind作为零配置插件,而是改用Convention插件来支持零配置.与以前相比较,Convention插件更彻底. 使用Conventi ...
- Struts2 Convention Plugin ( struts2 零配置 )
Struts2 Convention Plugin ( struts2 零配置 ) convention-plugin 可以用来实现 struts2 的零配置.零配置的意思并不是说没有配置,而是通过约 ...
- 从struts2.1开始Convention零配置
从struts2.1开始,struts2不再推荐使用Codebehind作为零配置插件,而是改为使用Convention插件来支持零配置,和Codebehind相比,Convention插件更彻底,该 ...
- Struts 2零配置
从struts2.1开始,struts2不再推荐使用Codebehind作为零配置插件,而是改为使用Convention插件来支持零配置,和Codebehind相比,Convention插件更彻底,该 ...
- Struts2基于注解的Action配置
使用注解来配置Action的最大好处就是可以实现零配置,但是事务都是有利有弊的,使用方便,维护起来就没那么方便了. 要使用注解方式,我们必须添加一个额外包:struts2-convention-plu ...
- Struts2 注解零配置方法(convention插件使用)
最近接触到一个新的项目,是做一个使用S2SH的电子商务商城的二次开发.之前使用过S2SH,在此之前的项目中,Struts2 使用的是XML配置而这个项目是使用注解.在这个项目中,注解还不需要使用Act ...
- struts2基于注解配置action
如果使用struts2,就需要配置文件或者注解,关于struts2的配置文件struts.xml非常熟悉,对于注解可能spring使用的比较多.配置文件的繁琐衬托出了注解的简洁方便,一条或者几条注解解 ...
- 注解实现struts2零配置
零配置指的是不经过配置文件struts.xml配置Action 首先:导入jar struts2-convention-plugin-2.3.24.1.jar package com.action ...
- struts2学习笔记之十四:使用注解配置Action(不是和spring集成使用)
Struts2支持使用注解配置Action,减少配置文件的配置 Struts2如果要支持注解配置Action,需要插件的支持,导入插件struts2-convention-plugin-2.1.8.1 ...
随机推荐
- Linux NFS服务器的安装与配置详解
一.NFS服务简介 NFS是Network File System(网络文件系统).主要功能是通过网络让不同的服务器之间可以共享文件或者目录.NFS客户端一般是应用服务器(比如web,负载均衡等),可 ...
- CentOS Linux release 7.6.1810全新安装 Zimbra 8.8.12邮箱
1.1 基础环境配置 1.1.1 主机名配置 [root@mail ~]# hostnamectl --static set-hostname mail.example.com [root@mai ...
- web前后台数据交互的几种方式
1.利用cookie对象 Cookie是服务器保存在客户端中的一小段数据信息.使用Cookie有一个前提,就是客户端浏览器允许使用Cookie并对此做出相应的设置.一般不赞成使用Cookie. (1) ...
- JZOJ 5347. 遥远的金字塔
Description Input Output Sample Input 5 3 1 6 1 5 3 5 4 4 4 4 Sample Output 15 Data Constraint 做法: 其 ...
- 权限组件(15):rbac的使用文档和在业务中的应用
这里用主机管理系统当做示例. 一.将rbac组件拷贝到项目中. 注意: rbac自己的静态文件.layout.html(被继承的模板).bootstrap.fontsize.公共的css.jquery ...
- Gym 100829S_surf 动态规划的优化
题目大意是,非你若干个任务,任务分别对应开始时间.预期收益.持续时间三项指标,让你从中选择一个受益最大的方案(没有开始时间相同的任务). 于是,标准状态转移方程应当为,设DP[K]为选择了前K个任务的 ...
- 笔记-网络-抓包-wireshark
笔记-网络-抓包-wireshark 1. 开始 环境:win8笔记本,无线网 1.1. 无线网卡设置 因为需抓捕无线网卡上的数据包,需要进行一项设置,如捕获有线网卡,无需设置. 打开 ...
- Android拨打电话不弹出系统拨号界面总结
我在网上搜了一下,解决这个问题,有两种方式: 1.反射调用系统底层方法,并获取系统权限 反射调用的代码如下: Class phoneFactoryClass = Class.forName(" ...
- ERROR L105: PUBLIC REFERS TO IGNORED SEGMENT 的解决办法
今天接着写一个单片机程序,出现这个问题,我仔细查看每一句语句,发现逻辑上没有错误,但就是出现这个问题,不能生成目标文件: *** ERROR L107: ADDRESS SPACE OVERFLOW ...
- java十分钟速懂知识点——System类
上次面试中遇到的一个问题,问到System.out.println()中的out是不是内部类,当时就给问蒙了,直观感觉out应该是System类的一个属性,跟内部类有什么关系?而且之前整理IO部分的时 ...