0

This is my entity class:

@Entity
@Table(name = "menuitem")
public class MenuItem {

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY )
@Column(name = "id")
private Integer id;

@Column(name = "title")
private String title;

@Column(name = "eng_title")
private String engTitle;

@Column(name = "price")
private double price;

@Column(name = "description")
private String description;

@Column(name = "consist_of")
private String consistOf;

@Column(name = "volume_value")
private double volumeValue;

@Column(name = "volume_title")
private String volumeTitle;

@ManyToOne
@JoinColumn(name = "category_id",insertable = false, updatable = false)
private Category category;

@Column(name = "category_id")
private int categoryId;

public MenuItem() {

}

public MenuItem(JSONObject jsonObject) {
    if (!jsonObject.isNull("id")) {
        this.id = jsonObject.getInt("id");
    }

    if (!jsonObject.isNull("title")) {
        this.title = jsonObject.getString("title");
    }

    if (!jsonObject.isNull("engTitle")) {
        this.engTitle = jsonObject.getString("engTitle");
    }

    if (!jsonObject.isNull("price")) {
        this.price = jsonObject.getDouble("price");
    }

    if (!jsonObject.isNull("description")) {
        this.description = jsonObject.getString("description");
    }

    if (!jsonObject.isNull("consistOf")) {
        this.consistOf = jsonObject.getString("consistOf");
    }

    if (!jsonObject.isNull("volumeValue")) {
        this.volumeValue = jsonObject.getDouble("volumeValue");
    }

    if (!jsonObject.isNull("volumeTitle")) {
        this.volumeTitle = jsonObject.getString("volumeTitle");
    }
}

public MenuItem(Integer id, String title, String engTitle, double price,
        String description, String consistOf, double volumeValue,
        String volumeTitle) {
    super();
    this.id = id;
    this.title = title;
    this.engTitle = engTitle;
    this.price = price;
    this.description = description;
    this.consistOf = consistOf;
    this.volumeValue = volumeValue;
    this.volumeTitle = volumeTitle;
}



@Override
public String toString() {
    return "MenuItem [id=" + id + ", title=" + title + ", engTitle="
            + engTitle + ", price=" + price + ", description="
            + description + ", consistOf=" + consistOf + ", volumeValue="
            + volumeValue + ", volumeTitle=" + volumeTitle + ", categoryId=" + categoryId + "]";
}

public String getEngTitle() {
    return engTitle;
}

public void setEngTitle(String engTitle) {
    this.engTitle = engTitle;
}

public void setId(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getConsistOf() {
    return consistOf;
}

public void setConsistOf(String consistOf) {
    this.consistOf = consistOf;
}

public double getVolumeValue() {
    return volumeValue;
}

public void setVolumeValue(double volumeValue) {
    this.volumeValue = volumeValue;
}

public String getVolumeTitle() {
    return volumeTitle;
}

public void setVolumeTitle(String volumeTitle) {
    this.volumeTitle = volumeTitle;
}

@JsonBackReference
@JsonIgnore
public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}   

public void setCategoryId(int categoryId) {
    this.categoryId = categoryId;
}

}

This is my root context:

<beans:bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:array>
                <beans:bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                    <beans:property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
                </beans:bean>
            </beans:array>
        </beans:property>
    </beans:bean>

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <!-- Configure to plugin JSON as request and response in method handler -->
    <beans:bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean>

    <mvc:interceptors>
        <beans:bean class="ru.tenet.cafe.interceptor.LoginInterceptor" />
    </mvc:interceptors>

    <context:component-scan base-package="ru.tenet.cafe" />

    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <beans:bean id="dataSourceMain" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <beans:property name="driverClass" value="org.postgresql.Driver" />
        <beans:property name="jdbcUrl"
            value="jdbc:postgresql://192.168.101.158:5432/cafe" />
        <beans:property name="user" value="postgres" />
        <beans:property name="password" value="123" />
        <beans:property name="minPoolSize" value="5" />
        <beans:property name="maxPoolSize" value="8" />
        <beans:property name="preferredTestQuery" value="SELECT 1" />
        <beans:property name="acquireIncrement" value="1" />
        <beans:property name="idleConnectionTestPeriod" value="100" />
        <beans:property name="maxStatements" value="0" />
        <beans:property name="checkoutTimeout" value="60000" />
    </beans:bean>

    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSourceMain" />
        <beans:property name="configLocation">
            <beans:value>/WEB-INF/db/hibernate.cfg.xml</beans:value>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.connection.characterEncoding">UTF-8</beans:prop>
                <beans:prop key="hibernate.connection.charSet">UTF-8</beans:prop>
                <beans:prop key="hibernate.connection.useUnicode">true</beans:prop>
                <beans:prop key="hibernate.show_sql">false</beans:prop>
            </beans:props>
        </beans:property>

    </beans:bean>



    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory" />
    </beans:bean>

This is my controller:

@RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> create(
            @RequestBody MenuItem menuItem) {   
        menuService.create(menuItem);
        return new ResponseEntity<String>(HttpStatus.OK);

    }

But if I send POST request with the following body

{
   "title":"Пепперони",
   "engTitle":"Pepperoni",
   "price":300,
   "description":"Сами лючщи пица слющи. Тольки щто привезли дарагой.",
   "consistOf":"E666, стальная стружка, вода (без ГМО)",
   "volumeValue":500,
   "volumeTitle":"г",
   "categoryId":38
}

I will get:

415 The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

What the hell?

1
  • As Louis suggested with quite a good definition, you need to pass Content-Type: application/json header with your rest service call Commented Jun 17, 2016 at 15:58

2 Answers 2

2

let's start with a little definition :

415 Unsupported Media Type

The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

Which can be solved by :

@RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json; charset=UTF-8", consumes = "application/json; charset=UTF-8")

Explanation : Basically you need to specify what kind of data your endpoint is going to consume / produce. Don't forget when sending the request to specify the header

Content-Type: application/json
Sign up to request clarification or add additional context in comments.

Comments

0

Your current controller must be replaced with the following code:

@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<String> create() {
    MenuItem menuItem = null;
    menuService.create(menuItem); // Fill in the menuItem
    // Now respond
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(menuItem, responseHeaders, HttpStatus.OK);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.