gpt4 book ai didi

java - 使用 Struts2 和 hibernate 创建 Web 服务(SOAP 或 REST)

转载 作者:行者123 更新时间:2023-11-30 10:48:54 24 4
gpt4 key购买 nike

我在使用 struts 2 和 hibernate 调用 Web 服务时遇到问题...

HTTP Status 500 - Unable to instantiate Action, actions.events.rest.EventController, defined for 'event' in namespace '/'Error creating bean with name 'actions.events.rest.EventController': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [actions.events.rest.EventController]: Constructor threw exception; nested exception is java.lang.NullPointerException

这是我的来源:

事件 Controller :

public class EventController extends BaseAction implements ModelDriven<Object> {
private static final long serialVersionUID = 1L;
private String id;
private Object model;

private static Map<String, Event> map;
{
List<Event> events = services.getEvents();
for(Event event : events){
map.put(event.getId() + "", event);
}
}

public HttpHeaders index() {
model = map;
return new DefaultHttpHeaders("index").disableCaching();
}

public String add(){
services.createEvent("Event1");
return "SUCCESS";
}

public String getId() {
return id;
}
public void setId(String id) {
Integer iid = Integer.parseInt(id);
model = services.getEventById(iid);
this.id = id;
}

public Object getModel() {
return model;
}

基础 Action :

public class BaseAction extends ActionSupport {
// So that spring can inject the business singleton
protected Services services;

public void setServices(Services value) {
services=value;
}

// For redirect results
protected String redirectUrl;

public String getRedirectUrl() {
return redirectUrl;
}

public String redirect(String to) {
redirectUrl = to;
return "redirect";
}

当我调试时,我在 List<Event> events = services.getEvents(); 中遇到错误在 EventController .它可以是什么?

最佳答案

  • 异常是由于
    您从静态初始化 block 中引用注入(inject)的bean 服务 :

    { 
    List<Event> events = services.getEvents();
    for(Event event : events){
    map.put(event.getId() + "", event);
    }
    }

    完全删除它,在 prepare() 方法或 @PostConstruct 方法或任何地方执行此类操作,但单独保留静态 block 。

也就是说,您正在遵循一些不良做法:

  • 您正在返回 "SUCCESS",而它应该是 "success"SUCCESS( “成功”)

  • 你正在将逻辑放在 setter 中,最好不要

  • 我还建议放弃 ModelDriven,完全放弃 Spring 和 use CDI ,但这是我的拙见。顺便说一句,确保到take a look at what I'm talking about .

关于java - 使用 Struts2 和 hibernate 创建 Web 服务(SOAP 或 REST),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35622962/

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