簡體   English   中英

@RequestBody沒有使用Rest服務

[英]@RequestBody not working on Rest service

我正在使用Spring開發一個使用AngularJS和WildFly的Web應用程序。

我的問題是我瘋了,因為注釋@requestBody似乎工作錯誤。

這是我的服務:

@ResponseBody
@RequestMapping(value = "/keyuser", method = RequestMethod.POST,
  consumes = "application/json")
public KeyProfileUserSummary updateEmployee(@RequestBody KeyProfileUserSummary keyUser) {
return null;
}

這是我的對象KeyProfileUserSummary的成員:

private Integer id;
private String login;
private String password;
private String firstname;
private String lastname;
private UserRole userRole;

我不知道發生了什么但是我已經用其他類型的對象測試了這個服務並且它工作得很好,但是當定義KeyProfileUserSummary它不能工作時,我得到ERROR 400 BAD REQUEST。 我已經測試過將@RequestBody設置為“Object”,所以至少我可以看到即將發生的事情,從我的前端,我得到以下信息:

{id=3, login=aa, password=a, firstname=Martin, lastname=Müller, userRole=ROLE_USER} 

UserRole是一個枚舉。 重要的是要清楚KeyProfileUserSummary只是KeyProfileUser的摘要版本,但是由於我得到了響應的所有鏈接元素,我決定發送這個更輕的類。 使用KeyProfileUser進行測試工作得很好,我在Angular端獲得JSON對象並可以將其發回。

在Angular方面,我沒有對該對象做任何事情。 只需在列表中接收它,當按下編輯按鈕時,只需返回列表中的元素即可。 這是我發送它的方式:

res = $http.post("url.../keyuser", user);

問題是我讓所有東西都與KeyProfileUser完美配合,但由於數據庫可以變得非常龐大並且引用相當多,我決定切換到這個較輕的類,但現在我只得到這個ERROR 400 BAD REQUEST ...而我正要掛起自己:P

謝謝你的幫助!

好的,最后我找到了解決方案。

在我的KeyProfileUserSummary中,我只有一個構造函數正在使用KeyProfileUser並將屬性設置為摘要版本:

public KeyProfileUserSummary(KeyProfileUser keyProfileUser) {
  this.id = keyProfileUser.getId();
  this.login = keyProfileUser.getLogin();
  this.password = keyProfileUser.getPassword();
  this.firstname = keyProfileUser.getPerson().getFirstname();
  this.lastname = keyProfileUser.getPerson().getLastname();
  this.userRole = keyProfileUser.getUserRole();
}

顯然, 在調度程序servlet的第993行設置一個斷點 (感謝@Clemens Eberwein的提示)我意識到當從JSON對象解析時,Jackson解析器需要一個空的構造函數 所以添加它解決了它並且完美地工作。

注意:對於KeyProfileUser,它完全正常,因為我們為hibernate提供了注釋@Entity,因此自動創建了空構造函數。

嘗試一下..可能對你有用..

$http({
    method: 'POST',
    url: 'http://localhost:8080/keyuser',
    data: user,
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }}).then(function(result) {
           console.log(result);
       }, function(error) {
           console.log(error);
       });

如果我猜測,傑克遜無法反序列化/序列化您的對象。 這是我制作的一個工具:

import java.io.IOException;
import java.nio.charset.Charset;

import org.springframework.http.MediaType;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class SerializeDeserializeUtil {

    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
            MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    public static byte[] convertObjectToJsonBytes(Object object)
            throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);

        return mapper.writeValueAsBytes(object);

    }

    public static <T> T deserializeObject(String jsonRepresentation,
            Class<T> clazz) throws JsonParseException, JsonMappingException,
            IOException {

        ObjectMapper mapper = new ObjectMapper();

        Object obj = mapper.readValue(jsonRepresentation.getBytes(), clazz);

        return clazz.cast(obj);
    }


    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static byte[] convertObjectToJsonBytesWithCustomSerializer(
            Object object, JsonSerializer serializer, Class clazz)
            throws IOException {

        ObjectMapper mapper = new ObjectMapper();

        SimpleModule sm = new SimpleModule();
        sm.addSerializer(clazz, serializer);

        mapper.registerModule(sm);
        mapper.setSerializationInclusion(Include.NON_NULL);

        return mapper.writeValueAsBytes(object);

    }

}

嘗試創建一個測試只是為了序列化和反序列化目標。 創建一個KeyProfileUserSummary對象並嘗試反序列化/序列化,看看傑克遜是否抱怨。

更簡單的方法是啟用DEBUG日志記錄並檢查日志文件,默認情況下您不會看到此類錯誤

希望能幫助到你。

如果為“org.springframework.web”添加DEBUG日志記錄org.springframework.web.servlet.DispatcherServlet應該為您提供導致“400 Bad Request”錯誤的詳細信息。

有關Wildfly日志記錄配置的詳細信息,請訪問此處

根據你的KeyProfileUserSummary類,我猜問題是UserRole對象,在上面的例子中只是userRole=ROLE_USER 由於它是一個對象,它應該用花括號括起來,並且必須設置屬性名稱。 例如

userRole = { name = "ROLE_USER"}

如果它是枚舉, 這個答案可能會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM