415不支持的媒体类型+弹簧 [英] 415 unsupported media type + spring

查看:98
本文介绍了415不支持的媒体类型+弹簧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:
我正在尝试将POST作为请求发送至参数:{id: 20, roleName: "ADMIN"},并收到此错误(415不支持的媒体类型).

The problem:
I'm trying to send a request as a POST with to parameters: {id: 20, roleName: "ADMIN"} and getting this error (415 unsupported media type).

框架:
春天4.1.1

Framework:
Spring 4.1.1

在服务器端的@Controller中,我具有以下内容:

In my @Controller in server side, I have the following:

@RequestMapping("/role/add.action")
    @ResponseBody
    public Map<String,Object> addrole(@RequestBody Role role, 
            HttpServletRequest request,
            Authentication authentication,
            HttpServletResponse response) {
    //Code goes here..
}

此-> @RequestBody Role role适用于任何其他类型的对象,但是对于Role我遇到了这个问题.

This --> @RequestBody Role role works fine for any other type of object but, for Role I get this issue.

我的Role类是:

@Entity
public class Role implements Serializable{


    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    private int id;

    @Column
    private String roleName;

    @Fetch(FetchMode.SELECT)
    @OneToMany(mappedBy = "role", targetEntity = Users.class, fetch = FetchType.EAGER)
    @JsonManagedReference(value="role")
    private List<Users> users = new LinkedList<Users>();

    @Fetch(FetchMode.SELECT)
    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(name="role_features",
            joinColumns=@JoinColumn(name="roleId"),
            inverseJoinColumns=@JoinColumn(name="featureId"))
    @OrderBy(clause="featureId")
    private Set<SystemFeature> features = new HashSet<SystemFeature>();

    @Fetch(FetchMode.SELECT)
    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(name="role_menu",
            joinColumns=@JoinColumn(name="roleId"),
            inverseJoinColumns=@JoinColumn(name="menuId"))
    @OrderBy(clause="menuId")
    private Set<Menu> menus = new HashSet<Menu>();

    @Fetch(FetchMode.SELECT)
    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(name="role_services_stations",
            joinColumns=@JoinColumn(name="roleId"),
            inverseJoinColumns=@JoinColumn(name="stationId"))
    @OrderBy(clause="stationId")
    private Set<ServiceStation> stations = new HashSet<ServiceStation>();

    //Constructors, getters and setters...

}

此类具有java.util.Set属性,我认为这可能会导致问题.

This class has java.util.Set attributes, and I think that this may causing the problem.

我仅发送两个属性:id和roleName.演员阵容应该可以,对吧?

I'm sending just two properties: id and roleName. The cast should work, right?

PS:我已经设置了Jackson message-converter bean,但是没有用.

PS: I've set a Jackson message-converter bean already, but didn't work.

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                        <property name="serializationInclusion">
                            <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                        </property>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

有人可以帮助我吗? xD

Someone could help me? xD

推荐答案

我的问题基本上是关于@JsonManagedReference注释的.

My problem was basically on @JsonManagedReference annotation.

我做了什么:

1)我将有效载荷更改为Map:

1) I changed my payload to a Map:

public Map<String,Object> addRole(@RequestBody Map payload, 
            HttpServletRequest request,
            Authentication authentication,
            HttpServletResponse response) {
...
}

2)然后,我尝试使用Jackson的ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)进行投射:

2) Then I tried to cast it with Jackson's ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper):

ObjectMapper mapper = new ObjectMapper();

Role role = mapper.convertValue(payload, Role.class);

然后调试器向我抛出了一个异常:

Then the debugger threw me an exception:

java.lang.IllegalArgumentException: Can not handle managed/back reference 'parent': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class br.com.ttrans.samapp.model.Menu]]

此异常有助于发现问题,就我而言,是注释@JsonManagedReference.来自 docs :

This exception helped find the problem, that (in my case) was the annotation @JsonManagedReference. From docs:

注释,用于指示带注释的属性是字段之间双向链接的一部分;并且它的角色是父"(或前进")链接.属性的值类型(类)必须具有单个兼容的属性,并带有JsonBackReference注释.处理链接时,可以正常处理用此注释注释的属性(正常序列化,没有反序列化的特殊处理);是需要特殊处理的匹配后向引用

Annotation used to indicate that annotated property is part of two-way linkage between fields; and that its role is "parent" (or "forward") link. Value type (class) of property must have a single compatible property annotated with JsonBackReference. Linkage is handled such that the property annotated with this annotation is handled normally (serialized normally, no special handling for deserialization); it is the matching back reference that requires special handling

这用于双向链接,而我的有效载荷正单向.所以..

This is used for two-way linkage and my payload was coming one-way. So..

3)...我删除了@JsonManagedReference的注释,并在所有嵌套类中仅保留了@JsonBackReference

3) ...I removed @JsonManagedReference's annotations and kept only @JsonBackReference in all nested classes;

然后,调试器向我抛出了另一个异常,但这一次是:java.lang.IllegalArgumentException: Unrecognized field ...,因此将@JsonIgnoreProperties(ignoreUnknown = true)放在所有类上都解决了我的问题.

Then the debbuger threw me another exception, but this time was: java.lang.IllegalArgumentException: Unrecognized field ... so putting @JsonIgnoreProperties(ignoreUnknown = true) on all classes solved my problem.

所以毕竟我可以收到已经解析为Role的有效负载:

So after all that I could receive the payload already parsed as Role:

@RequestMapping("/role/add.action")
@ResponseBody
public Map<String,Object> addRole(@RequestBody Role role, 
            HttpServletRequest request,
            Authentication authentication,
            HttpServletResponse response) {

            ...
}

希望有帮助!

这篇关于415不支持的媒体类型+弹簧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆