简体   繁体   English

Java服务400错误的请求错误

[英]java service 400 bad request error

Dear spring Java professionals 尊敬的Spring Java专业人士

please help me out in this : I have a custom service in spring and I dont have any errors on my wildfly server when i run it . 请帮我解决这个问题:我在春天有一个定制服务,运行我的wildfly服务器上没有任何错误。 but when I do the below update request i am getting 400 bad request though im sending the format as specified in my controller 但是当我执行以下更新请求时,尽管我发送了控制器中指定的格式,但我收到了400错误的请求

inside my controller : 在我的控制器内:

@RequestMapping(value = "/user/updatefilters/{Id}", method = RequestMethod.POST)
    public Response updateFilter(@PathVariable("Id") Long Id, @RequestBody @Valid Filter Filter) {

        FilterService.updateFilter(Id, Filter);

        HashMap<String, Object> response = new HashMap<>();
        response.put("messages", null);
        response.put("success", Boolean.valueOf(true));
        return Response.instance().friendlyName("filter-updated").object(response).statusCode(HttpStatus.OK);
}

inside my service file : 在我的服务文件中:

public void updateFilter(Long Id,Filter Filter) {
    List<Filter> currentFilter = FilterRepo.getFilters(Id, Filter.getFilterId().longValue(),null);
    currentFilter.get(0).setLabel(Filter.getLabel());
    FilterRepo.save(currentFilter.get(0));

    for (FilterField FilterField : Filter.getFilterFields()) {
        FilterField currentFilterField = FilterFieldRepo.getFilterField(FilterField.getfieldId());
        if (currentFilterField != null) {
            currentFilterField.setfield(FilterField.getfield());
            currentFilterField.setTypeId(FilterField.getTypeId());
            FilterFieldRepo.save(currentFilterField);
        }           
    }   
}

inside my repository : 在我的存储库中:

public List<Filter> getFilterList(Long Id, String type) {
    List<Filter> FilterField = FilterFieldRepo.getFilterFields(Id,type);
    return FilterField;
}   

public void updateFilter(Long Id,Filter Filter) {
    List<Filter> currentFilter = FilterRepo.getFilters(Id, Filter.getFilterId().longValue(),null);
    currentFilter.get(0).setLabel(Filter.getLabel());
    FilterRepo.save(currentFilter.get(0));

    for (FilterField FilterField : Filter.getFilterFields()) {
        FilterField currentFilterField = FilterFieldRepo.getFilterField(FilterField.getfieldId());
        if (currentFilterField != null) {
            currentFilterField.setfield(FilterField.getfield());
            currentFilterField.setTypeId(FilterField.getTypeId());
            FilterFieldRepo.save(currentFilterField);
        }           
    }   
}

Please note that inside my entity I added a transient list like this : 请注意,在我的实体内,我添加了一个临时列表,如下所示:

@Transient
private List<FilterField> filterFields;

updated : this is my Filter class i generated the crud in netbeans but added the transuent list manually: 更新:这是我的Filter类,我在netbeans中生成了crud,但是手动添加了transuent列表:

@Entity
@Table(schema="hitmeister",name = "filters")
@NamedQueries({
    @NamedQuery(name = "Filter.findAll", query = "SELECT s FROM Filter s"),
    @NamedQuery(name = "Filter.findByFilterId", query = "SELECT s FROM Filter s WHERE s.filterId = :filterId"),
    @NamedQuery(name = "Filter.findById", query = "SELECT s FROM Filter s WHERE s.Id = :Id"),
    @NamedQuery(name = "Filter.findByLabel", query = "SELECT s FROM Filter s WHERE s.label = :label"),
    @NamedQuery(name = "Filter.findByInsertionDate", query = "SELECT s FROM Filter s WHERE s.insertionDate = :insertionDate"),
    @NamedQuery(name = "Filter.findByIsActive", query = "SELECT s FROM Filter s WHERE s.isActive = :isActive"),
    @NamedQuery(name = "Filter.findByType", query = "SELECT s FROM Filter s WHERE s.type = :type")})
public class Filter implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "filter_id")
    private Integer filterId;
    @Basic(optional = false)
    @NotNull
    @Column(name = "id")
    private int Id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 500)
    @Column(name = "label")
    private String label;
    @Basic(optional = true)
    @Column(name = "insertion_date")
    @Temporal(TemporalType.TIMESTAMP)
    private Date insertionDate;
    @Column(name = "is_active")
    private Boolean isActive;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "type")
    private String type;

    @Transient
    private List<FilterField> filterFields;

    public Filter() {
    }

    public Filter(Integer filterId) {
        this.filterId = filterId;
    }

    public Filter(Integer filterId, int Id, String label, Date insertionDate, String type) {
        this.filterId = filterId;
        this.Id = Id;
        this.label = label;
        this.insertionDate = insertionDate;
        this.type = type;
    }

    public Integer getFilterId() {
        return filterId;
    }

    public void setFilterId(Integer filterId) {
        this.filterId = filterId;
    }

    public int getId() {
        return Id;
    }

    public void setuserId(int Id) {
        this.userId = userId;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public Date getInsertionDate() {
        return insertionDate;
    }

    public void setInsertionDate(Date insertionDate) {
        this.insertionDate = insertionDate;
    }

    public Boolean getIsActive() {
        return isActive;
    }

    public void setIsActive(Boolean isActive) {
        this.isActive = isActive;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (filterId != null ? filterId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Filter)) {
            return false;
        }
        Filter other = (Filter) object;
        if ((this.filterId == null && other.filterId != null) || (this.filterId != null && !this.filterId.equals(other.filterId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return " Filter #"+ filterId ;
    }

    public List<FilterField> getFilterFields() {
        return filterFields;
    }

    public void setFilterFields(List<FilterField> filterFields) {
        this.filterFields = filterFields;
    }


}

If you need my entity code i can post it as well Thanks In advance ! 如果您需要我的实体代码,我也可以发布它。谢谢!

My first recommendation: (OP tried and it didn't work, she was sending POST request) 我的第一个建议: (OP尝试了,但没有用,她正在发送POST请求)

Change your mapping as below and I think you should be fine. 如下更改映射,我认为应该没问题。 Request from browser address bar is a GET request. 来自浏览器地址栏的请求是GET请求。

As you can see below, HTTP 400 comes when server is unable to understand the request client is sending, and in your case you are sending GET but server has nothing for GET but for POST, so 400. 如下所示,当服务器无法理解客户端正在发送的请求时,HTTP 400出现了,在您的情况下,您正在发送GET,但是服务器除了POST之外没有其他用于GET的消息,所以返回400。

W3C HTTP 400 W3C HTTP 400

10.4.1 400 Bad Request 10.4.1 400错误的请求

The request could not be understood by the server due to malformed syntax. 由于语法格式错误,服务器无法理解该请求。 The client SHOULD NOT repeat the request without modifications. 客户不应在没有修改的情况下重复请求。

Code fix: 代码修复:

@RequestMapping(value = "/user/updatefilters/{Id}", method = RequestMethod.GET)


My second recommendation: 我的第二个建议:

I am not Spring expert but here are my 2 cents you can try based on the JSON object you have provided and your Filter mapping - (1.) Change userId to Id , (2.) Have insertionDate as NULL, instead of an empty string. 我不是Spring专家,但是这是我的2美分,您可以根据提供的JSON对象和过滤器映射进行尝试-(1.)将userId更改为Id ,(2。) insertionDate userId设置为NULL,而不是空字符串。

Make sure your JSON string variables are mapped case-sensitively with your Filter class mapping, and their values are compatible with reference types. 确保您的JSON字符串变量与Filter类映射区分大小写,并且它们的值与引用类型兼容。

Either your request format is not what Spring expects, or one of the Filter validations is failing. 您的请求格式不是Spring期望的格式,或者Filter验证之一失败了。 Add a org.springframework.validation.Errors argument and dump the values to find out what validations failed. 添加org.springframework.validation.Errors参数并转储值以找出验证失败的原因。

public Response updateFilter(@PathVariable("Id") Long Id, @RequestBody @Valid Filter Filter, Errors filterErrors) {

You can sniff the actual traffic using curl or a network monitoring tool to make sure the HTTP transaction is really what you think it is. 您可以使用curl或网络监视工具来嗅探实际流量,以确保HTTP事务确实如您所想。

EDIT: Having looked at the JSON in one of your comments, I think this is going to turn out to be upper/lower case in your JSON field names. 编辑:在您的注释之一中查看了JSON之后,我认为这在您的JSON字段名称中将变成大写/小写。 Either change "Id" to "id" and "FilterId" to "filterId", or annotate the Filter fields with @XmlElement(name = "Id") and @XmlElement(name = "FilterId") . 可以将“ Id”更改为“ id”,将“ FilterId”更改为“ filterId”,或者使用@XmlElement(name = "Id")@XmlElement(name = "FilterId")注释Filter字段。 Java Bean property names are case sensitive. Java Bean属性名称区分大小写。

EDIT 2: Filter.setuserId(int Id) is broken as well. 编辑2: Filter.setuserId(int Id)也被损坏。 You need a setId() method for deserializing the bean, and you need to change the method so it stores the passed argument instead of just setting userId to itself. 您需要一个setId()方法来反序列化Bean,并且需要更改该方法,以便它存储传递的参数,而不仅仅是将userId设置为其自身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM