<!--Struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.16</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.16</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.16</version>
</dependency>
<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>*.action</url-pattern>
</filter-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!-- 编码 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- struts2的action必须放在一个指定的包空间下定义 -->
<package name="default" extends="struts-default" namespace="/">
<!-- 定义处理请求URL为login.action的Action -->
<action name="login" class = "com.study.struts.LoginAction">
<!-- 定义处理结果字符串和资源之间的映射关系 -->
<result name = "success">success.jsp</result>
<result name = "error">error.jsp</result>
</action>
</package>
</struts>
Caused by: java.lang.NullPointerException
at com.opensymphony.xwork2.spring.SpringObjectFactory.getClassInstance(SpringObjectFactory.java:230)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyResultType(XmlConfigurationProvider.java:604)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addResultTypes(XmlConfigurationProvider.java:574)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:530)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:292)
at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:258)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:445)
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:489)
... 15 more
去掉pom中struts2-spring-plugin依赖配置,因为没有用到spring
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.16</version>
</dependency>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Action处理完用户请求后,将数据存放在某一位置,如request中,并返回视图,然后Struts将跳转至该视图资源,在该视图中,我们需要做的是将数据从存放位置中取出,然后将其转换为JSON字符串,输出在视图中。这跟传统WEB应用中在JSP页面输出JSON数据的做法如出一辙:
public String testByJSP() {
User user = new User();
user.setId("123");
user.setName("Struts2");
user.setPassword("123");
user.setSay("Hello world !");
JSONObject jsonObject=new JSONObject();
jsonObject.accumulate("user", user);
//这里在request对象中放了一个data,所以struts的result配置中不能有type="redirect"
ServletActionContext.getRequest().setAttribute("data", jsonObject.toString());
return SUCCESS;
};
配置文件
<package name="default" extends="struts-default" namespace="/">
<!-- 定义处理请求URL为login.action的Action -->
<action name="testByJsp" class = "com.study.struts.LoginAction" method="testByJsp">
<!-- 定义处理结果字符串和资源之间的映射关系 -->
<result name = "success">login/success.jsp</result>
<result name = "error">login/error.jsp</result>
</action>
</package>
error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
${data }
action代码
public void testByGeneral() throws IOException{
HttpServletResponse response=ServletActionContext.getResponse();
//以下代码从JSON.java中拷过来的
response.setContentType("text/html");
PrintWriter out;
out = response.getWriter();
//将要被返回到客户端的对象
User user=new User();
user.setId("123");
user.setName("JSONActionGeneral");
user.setPassword("JSON");
user.setSay("Hello , i am a action to print a json!");
JSONObject json=new JSONObject();
json.accumulate("success", true);
json.accumulate("user", user);
out.println(json.toString());
// 因为JSON数据在传递过程中是以普通字符串形式传递的,所以我们也可以手动拼接符合JSON语法规范的字符串输出到客户端
// 以下这两句的作用与38-46行代码的作用是一样的,将向客户端返回一个User对象,和一个success字段
// String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONActionGeneral\",\"say\":\"Hello , i am a action to print a json!\",\"password\":\"JSON\"},\"success\":true}";
// out.println(jsonString);
out.flush();
out.close();
}
struts.xml中的配置:
<package name="default" extends="struts-default" namespace="/">
<action name="testByGeneral" class = "com.study.struts.LoginAction" method="testByGeneral"></action>
</package>
注意:这个action没有result,且doAction方法没有返回值!
action代码
public String testByAction() {
// dataMap中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据
dataMap.clear();
User user = new User();
user.setId("123");
user.setName("JSONActionStruts2");
user.setPassword("123");
user.setSay("Hello world !");
dataMap.put("user", user);
// 放入一个是否操作成功的标识
dataMap.put("success", true);
// 返回结果
return SUCCESS;
}
struts.xml中action的配置:
<package name="json" extends="json-default" namespace="/">
<action name="testByAction" class="com.study.struts.LoginAction" method="testByAction">
<result type="json">
<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 -->
<!-- 默认将会序列所有有返回值的getter方法的值,而无论该方法是否有对应属性 -->
<param name="root">data</param>
<!-- 指定是否序列化空的属性 -->
<!-- <param name="excludeNullProperties">true</param> -->
<!-- 这里指定将序列化dataMap中的那些属性 -->
<!-- <param name="includeProperties">userList.*</param> -->
<!-- 这里指定将要从dataMap中排除那些属性,这些排除的属性将不被序列化,一半不与上边的参数配置同时出现 -->
<!-- <param name="excludeProperties">SUCCESS</param> -->
</result>
</action>
</package>
第三种方法配置后,启动报错:
Caused by: Unable to load configuration. - [unknown location]
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:70)
at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:445)
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:489)
... 15 more
Caused by: Parent package is not defined: json-default - [unknown location]
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.buildPackageContext(XmlConfigurationProvider.java:670)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:519)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:292)
at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:258)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
... 17 more
原因 未加入struts2-json-plugin-2.3.16.3.jar 包,pom添加依赖
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.3.16</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.16</version>
</dependency>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts运行时由Spring创建对象 -->
<constant name="struts.objectFactory" value="spring"/>
package com.study.struts;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import com.opensymphony.xwork2.ModelDriven;
import com.study.entity.User;
import com.study.utils.struts.BaseAction;
@Namespace("/annotationTest")
public class AnnotationTest extends BaseAction implements ModelDriven<User>{
private User user = new User();
@Action("/test")
public String testAnnotation(){
String val = "";
if("gyh".equals(user.getUserName())){
val = "测试 annotation方式的action 成功";
}else{
val = "失败";
}
this.writeJson2Page(val);
return "hh";
}
@Override
public User getModel() {
return user;
}
}
<package name="package3" extends="struts-default" namespace="/">
<action name="test" class="userAction" method="getUserName"></action>
</package>
<package name="package3" extends="struts-default" namespace="/">
<action name="*!*" class="{1}" method="{2}"></action>
</package>
userAction代码如下
package com.study.struts;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ModelDriven;
import com.study.entity.User;
import com.study.utils.struts.BaseAction;
@Controller("userAction")
@Scope("prototype")
public class UserAction extends BaseAction implements ModelDriven<User>{
private User user = new User();
@Override
public User getModel() {
return user;
}
public void getUserName(){
String val = "";
if(user == null){
val = "输入要查询的用户";
}
if("gyh".equals(user.getUserName())){
val = "高玉环";
}else{
val = "用户不存在";
}
writeJson2Page(val);
}
}