gpt4 book ai didi

java - 如何使用 Struts2 REST 插件创建自定义方法

转载 作者:行者123 更新时间:2023-12-01 06:15:07 24 4
gpt4 key购买 nike

我的问题涉及在操作中创建自定义方法。我使用 Struts2 和 REST 插件来实现 RESTful WebService。我的 Action 类如下:

public class SampleController implements ModelDriven<Object> {

private Sample sample = new Sample();
private Collection<Sample> list;
private int id;

public HttpHeaders create() {
sdao.save(sample);
return new DefaultHttpHeaders("create");
}


public HttpHeaders destroy() {
return new DefaultHttpHeaders("destroy");
}

public HttpHeaders show() {
return new DefaultHttpHeaders("show").disableCaching();
}

public HttpHeaders update() {
sdao.save(sample);
return new DefaultHttpHeaders("update");
}

public HttpHeaders index() {
list = sdao.findAll();
return new DefaultHttpHeaders("index").disableCaching();
}

public Object getModel() {
return (list != null ? list : sample);
}


public int getId() {
return id;
}

public void setId(Integer id) {
if (id != null) {
this.sample = (Sample) sdao.findById(id);
}
this.id = id;
}

}

我可以通过 GET HTTP 方法正确访问资源。为了使用自定义方法,通过传递参数来调用搜索资源,即

public searchBySenderName(String senderName) {
list.addAll(sdao.findBySenderName(senderName))
}

正确的程序是什么?如何通过 GET 下面的 URL 调用它?

最佳答案

您可以根据您的情况从 GET 的任何预定义方法(indexshow)调用自定义方法,请参阅 RESTful URL mapping logic .

RESTful URL Mapping Logic

This Restful action mapper enforces Ruby-On-Rails REST-style mappings.If the method is not specified (via '!' or 'method:' prefix), themethod is "guessed" at using REST-style conventions that examine theURL and the HTTP method. Special care has been given to ensure thismapper works correctly with the codebehind plugin so that XMLconfiguration is unnecessary.

<小时/>

当然,您可以更改操作映射器使用的方法名称,但这会影响整个应用程序。如果您已经占用了一个资源 URL,那么您应该使用另一个资源 URL 来执行其工作。如果您使用严格的 rest 映射器,则会出现这种情况。在 mixed mode您可以将常用操作映射到某些操作方法。

REST and non-RESTful URL's Together Configuration

If you want to keep using some non-RESTful URL's alongside your RESTstuff, then you'll have to provide for a configuration that utilizesto mappers.

Plugins contain their own configuration. If you look in the Restplugin jar, you'll see the struts-plugin.xml and in that you'll seesome configuration settings made by the plugin. Often, the plugin justsets things the way it wants them. You may frequently need to overridethose settings in your own struts.xml.

<小时/>

最后,您可能无法通过 !method: 前缀指定方法,因为它受到默认配置的限制。

关于java - 如何使用 Struts2 REST 插件创建自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26702426/

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