rest - 向 Grails restfulcontroller 添加功能

标签 rest grails

我有一个非常简单的 restful Controller ,它看起来像这样:

class PersonController extends RestfulController<Person> {

    static responseFormats = ['json', 'xml']

    PersonController() {
        super(Person)
    }
}

但是,现在我想为此添加一个搜索选项。使这成为可能的 Grails 方法是什么?

我想添加以下内容:
def search(Map params) {
    println params
}

但这会使 Grails (2.3) 崩溃(| Error Fatal error during compilation org.apache.tools.ant.BuildException: Compilation Failed (Use --stacktrace to see the full tr​​ace))。

那么添加这个的正确方法是什么?我正在寻找可以使用 http://localhost:8080/foo/person/search?q=erik 调用的解决方案

这是我的 UrlMappings:
static mappings = {
    "/$controller/$action?/$id?(.${format})?"{
        constraints {
            // apply constraints here
        }
    }


    "/rest/persons"(resources:'Person')

我已将以上内容更改为:
def search() {
    println params
}

这不再给出编译错误,但我仍然收到此错误:
TypeMismatchException occurred when processing request: [GET] /declaratie-web/rest/medicaties/search - parameters:
q: erik
Provided id of the wrong type for class nl.Person. Expected: class java.lang.Long, got class java.lang.String. Stacktrace follows:
org.hibernate.TypeMismatchException: Provided id of the wrong type for class nl.Person. Expected: class java.lang.Long, got class java.lang.String

我还发现我如何调用 Controller 并不重要:
http://localhost:8080/foo/person/search?q=erik
http://localhost:8080/foo/person/search222?q=erik
http://localhost:8080/foo/person/search39839329?q=erik

一切都因上述错误而失败,所以似乎我的方法被忽略了(可能是由我的 URLmapping 引起的?)

最佳答案

这样做你真的不是 RESTful。 q应该只是索引操作的参数。您可以覆盖该方法以包含您的功能。

def index(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    def c = Person.createCriteria()
    def results = c.list(params) {
       //Your criteria here with params.q
    }
    respond results, model:[personCount: results.totalCount]
}

关于rest - 向 Grails restfulcontroller 添加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19360559/

相关文章:

api - 对实体/资源进行 RESTful API 授权?

mongodb - 从Grails从MongoDB 2.4.12迁移到3.2.7的异常

macos - 为什么即使它在我的 PATH 上,Groovy 也找不到该程序?

Grails OpenLDAP 登录失败 : Sorry, 我们无法找到具有该用户名和密码的用户

java - 400 错误请求 - 将 JSON 数据发布到 RESTful Controller 时

rest - WCF、Web API、WCF REST 和 Web 服务之间的区别?

java - 来自 jQuery 的远程 AJAX 调用验证检查电子邮件有效性不起作用

javascript - VueJS 将所​​有 Prop 传递给子组件

validation - Grails命令对象验证给出异常而不是错误

spring - 无法安装spring-security-core.2.0-RC2