2017-02-23 174 views
2

我創建了一個小型服務,它從UI textarea接收一個字符串,並將該字符串傳遞給一個spring boot rest服務,該字符串包含一段java代碼,並將通過彈簧邏輯進行分析並推送結果回到UI再次,在這裏我有串問題Spring Boot Rest API編碼錯誤

在UI項目,代碼:

var sendCode = function(){ 
     var code = $(".textarea").val(); 
     console.log(code); 
     var url = "http://localhost:8080/simpleoj"; 
     var success = function(data){ 
     $("#finalResult").html(data); 
     } 

     $.ajax({ 
     type: "POST", 
     url: url, 
     data: code, 
     success: success 
     }); 
    } 

其中URL是目標後應該去

在後端,我的代碼如下:

import org.springframework.web.bind.annotation.*; 

import javax.tools.JavaCompiler; 
import javax.tools.ToolProvider; 
import java.io.File; 
import java.io.IOException; 
import java.lang.reflect.Method; 
import java.net.URL; 
import java.net.URLClassLoader; 
import java.nio.charset.StandardCharsets; 
import java.nio.file.Files; 

@RestController 
public class WebController{ 

    @CrossOrigin(origins = "*") 
    @RequestMapping(value = "/simpleoj",method = RequestMethod.POST,consumes = {}) 
    public String greetings(@RequestBody String bodyContent) throws Exception{ 

     String source = bodyContent; 
     System.out.println(source); 
     //I have remove the logic, because it is not important 
     } 
    } 
} 

當我部署所有這些,我發現邏輯無法執行,因爲的BodyContent如下所示:

public+class+Solution%7Bpublic+int+add%28%29%7Breturn+1+1%3B%7D%7D= 

這不是我想要的!

我想這是如下:

public class Solution{public int add{return 1+1;}} 
,當我在郵遞員測試

,這是工作的罰款。 有人可以幫我嗎?

+0

順便說一下,雖然當然沒有必要使用表單POST的形式編碼而不是請求主體。 – chrylis

回答

1

這是因爲該參數被調用爲URL。您可以使用以解碼

String result = java.net.URLDecoder.decode(bodyContent, "UTF-8"); 
+0

但問題是當我按照你的建議編碼時,我有另一個問題,問題是返回語句是1 + 1,所以編碼時,'+'將被解散。說實話,我只是想從textarea中獲得一個純字符串,當我將它們集成在一起時,我得到的字符串缺少'+'並在末尾添加'='。 – crlyw

+0

這是因爲字符串編碼不好,它應該是public + class +解決方案%7B公共+ int + add%7B返回+ 1%2B1%3B%7D%7D – reos

+0

我找到了解決方法,首先在帖子在jQuery中,我應該添加以下內容:contentType:「plain/text; charset = utf-8」,dataType:「text」,並且在RestController中添加標頭= {Accept = text},我不會這很重要,但我的問題解決了,感謝所有幫助我的人。 – crlyw