gpt4 book ai didi

java - JSON 对象未在 Struts2 Action 中设置变量

转载 作者:行者123 更新时间:2023-11-30 11:16:25 25 4
gpt4 key购买 nike

我真的很难处理如下复杂的 json 对象:

var data= {service:{
client:{idClient: idClient},
pet:{idPet: idPet},
employee:{idEmployee: idEmployee},
conclusion: ''+conclusion}};

我通过这个发送它:

$.ajax({
url: 'registerService.action',
type:'post',
data: JSON.stringify(data),
contentType: 'application/json',
dataType: 'json',
succes: function(data){
//do something
}
});

并且会触发异常:java.lang.NullPointerException,表示action中的变量service还没有被实例化。

public class SomeAction extends ActionSupport{
private Service service; //getter y setter

public String registerService(){
Integer cod= (getServiceService().registerService(service));
return SUCCESS;
}

Service 类看起来像这样

public class Service {
//everything with its respective setter a getter
private Client client;
private Pet pet;
private Employee employee;
private String conclusion;

public Service(){
client = new Client();
pet = new Pet();
employee= new Employee();
}

}

此外,不同对象的每个 id 都是 Integer。

希望得到帮助,谢谢提前致谢


解决方案

对象服务实例化后,它的属性为null,那是因为我没有在struts.xml中包含如下所示的相应拦截器的 Action 映射

struts.xml

<interceptors>
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
</interceptors>

Action 映射

<action name="registerService" class="servicioActionSpring"  method="registerService">
<interceptor-ref name="json"/>
<result type="json"></result>
</action>

最佳答案

没错,属性应该被初始化。

private Service service = new Service(); //getter y setter

或者你可以做到this使用内部DI机制的方式。如果您使用其他 DI 框架,您应该使用相应的插件。

因为您要向操作发送 JSON,请确保您在操作配置中使用了 json 拦截器。

关于java - JSON 对象未在 Struts2 Action 中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24879094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com