回应一个宁静的电话

时间:2017-04-05 05:54:35

标签: java rest servlets grails

我正在从grails代码中调用servlet doGet()方法。成功调用doGet()方法,我能够看到print语句。一旦调用了doGet(),我就需要将响应发送回调用该方法的restful调用。如何在servlet中设置响应,以便将其发送回grails

    def getStatus(String tableName) {
            try {
                def result
                def resultList = []
                println "attempting to send START signal to http://localhost:9081/ServletSample/ServletSample"
                result = rest.get("http://localhost:9081/ServletSample/ServletSample?tableName="+tableName)
                println "length "+result.length()
                println result.body
                resultList.add(result)
                log.debug "$result.body"
                resultList.each {
                    println "$it.body"
                    if (it.status == 200) {
                        if (it.body == "Starting")

 {
                        println ("starting up")

在servlet中我试图将响应设置为

response.setContentLength(5);
        response.setStatus(200);

但是没有收到。我收到以下异常

Exception occured in rest service() groovy.lang.MissingMethodException: No signature of method: grails.plugins.rest.client.RestResponse.length() is applicable for argument types: () values: []
Possible solutions: getAt(java.lang.String), each(groovy.lang.Closure), with(groovy.lang.Closure), wait(), getXml(), every() from class java.net.URL

1 个答案:

答案 0 :(得分:0)

您需要将java对象转换为json字符串并将其写入HttpServletResponse。这是代码:

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8"); 
// Get the printwriter object from response to write the required json object to the output stream      
PrintWriter out = response.getWriter();
String json = new Gson().toJson(someObject);

out.write(json);

要将java对象转换为json字符串,我使用了Google Gson

但是如果容易的话,你可以手动创建json字符串