Adding functionality to Grails restfulcontroller

回眸只為那壹抹淺笑 提交于 2020-01-06 08:07:11

问题


I'm having a very simple restful controller, which looks like this:

class PersonController extends RestfulController<Person> {

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

    PersonController() {
        super(Person)
    }
}

However, now I want to add a search option to this. What is the Grails way of making this possible?

I thought of adding the following:

def search(Map params) {
    println params
}

But that makes Grails (2.3) crash (| Error Fatal error during compilation org.apache.tools.ant.BuildException: Compilation Failed (Use --stacktrace to see the full trace)).

So what is the right way of adding this? I'm looking for some solution which I can call using http://localhost:8080/foo/person/search?q=erik

This is my UrlMappings:

static mappings = {
    "/$controller/$action?/$id?(.${format})?"{
        constraints {
            // apply constraints here
        }
    }


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

I've changed the above to:

def search() {
    println params
}

And that doesn't give the compilation error anymore, but I still get this error:

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

I also found out that it doesn't matter how I call the 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

All fails with the above error, so it seems my method is ignored (maybe caused by my URLmapping?)


回答1:


You really aren't being RESTful by doing that. q should just be a parameter for the index action. You can override that method to include your functionality.

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]
}



回答2:


@james-kleeh solution is right, but you can do it more clean by override the listAllResources method which is called by index

@Override
protected List<Payment> listAllResources(Map params) {
    Person.createCriteria().list(params) {
        // Your criteria here with params.q
    }
}


来源:https://stackoverflow.com/questions/19360559/adding-functionality-to-grails-restfulcontroller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!