Spring MVC POST和PUT不支持的媒体类型

时间:2017-09-20 17:38:23

标签: java spring spring-mvc

我正在开发一个项目(使用SPRING MVC),我创建了一个带有GET,PUT和POST的控制器,它工作正常但是现在如果我尝试POST并且PUT出现错误:     服务器拒绝了此请求,因为请求实体所采用的方法所请求的资源不支持该格式。

我的控制员:

  /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package zw.co.telecel.camsapi.controllers;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import zw.co.telecel.camsapi.entities.District;
import zw.co.telecel.camsapi.utils.ApiResponse;
import zw.co.telecel.camsapi.utils.Helper;
import zw.co.telecel.camsapi.utils.ResponseCode;

/**
 *
 * @author prime
 */
@Controller
@RequestMapping("/districts")
public class DistrictController {

    private static final Logger logger = Logger.getLogger(UserController.class);

    /**
     * Gets all districts registered in the system
     *
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public ApiResponse getDistricts() {
        ApiResponse response = new ApiResponse();
        BasicConfigurator.configure();
        EntityManagerFactory emf = null;
        EntityManager em = null;
        try {
            emf = Persistence.createEntityManagerFactory(Helper.PERSISTENCE_UNIT_NAME);
            em = emf.createEntityManager();
            Query query = em.createNamedQuery("District.findAll");
            List<District> districts = query.getResultList();
            if (districts.isEmpty()) {
                logger.info(districts);
                response.setCode(ResponseCode.NOT_FOUND);
                response.setDescription("NOT_FOUND");
                response.setIsSuccess(false);
                response.setData(districts);
                logger.info(response);
                return response;

            } else {
                logger.info(districts);
                response.setCode(ResponseCode.FOUND);
                response.setDescription("FOUND");
                response.setIsSuccess(true);
                response.setData(districts);
                logger.info(response);
                return response;
            }

        } catch (PersistenceException ex) {
            logger.error(ex);
            response.setCode(ResponseCode.FAILED_DEPENDENCY);
            response.setDescription("Failed dependency.");
            response.setIsSuccess(false);
            return response;
        } catch (Exception ex) {
            logger.error(ex);
            response.setCode(ResponseCode.INTERNAL_SERVER_ERROR);
            response.setDescription("Failed to process request.");
            response.setIsSuccess(false);
            return response;

        } finally {
            if (em != null) {
                if (em.isOpen()) {
                    em.close();
                }
            }

        }

    }

    /**
     * *
     * Get district by id
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public ApiResponse getDistrict(@PathVariable Integer id) {
        ApiResponse response = new ApiResponse();

        BasicConfigurator.configure();
        EntityManagerFactory emf = null;
        EntityManager em = null;
        try {
            emf = Persistence.createEntityManagerFactory(Helper.PERSISTENCE_UNIT_NAME);
            em = emf.createEntityManager();
            Query query = em.createNamedQuery("District.findById");
            query.setParameter("id", id);
            List<District> districts = query.getResultList();
            if (districts.isEmpty()) {
                logger.info(districts);
                response.setCode(ResponseCode.NOT_FOUND);
                response.setDescription("NOT_FOUND");
                response.setIsSuccess(false);
                response.setData(districts);
                logger.info(response);
                return response;

            } else {
                logger.info(districts);
                response.setCode(ResponseCode.FOUND);
                response.setDescription("FOUND");
                response.setIsSuccess(true);
                response.setData(districts);
                logger.info(response);
                return response;
            }
        } catch (PersistenceException ex) {
            logger.error(ex);
            response.setCode(ResponseCode.FAILED_DEPENDENCY);
            response.setDescription("Failed dependency.");
            response.setIsSuccess(false);
            return response;
        } catch (Exception ex) {
            logger.error(ex);
            response.setCode(ResponseCode.INTERNAL_SERVER_ERROR);
            response.setDescription("Failed to process request.");
            response.setIsSuccess(false);
            return response;

        } finally {
            if (em != null) {
                if (em.isOpen()) {
                    em.close();
                }
            }

        }
    }

    /**
     * *
     * Create new district
     *
     * @param district
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.POST, produces = "application/json", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ApiResponse createDistrict(@RequestBody District district) {
        ApiResponse response = new ApiResponse();
        BasicConfigurator.configure();
        EntityManagerFactory emf = null;
        EntityManager em = null;
        try {

            emf = Persistence.createEntityManagerFactory(Helper.PERSISTENCE_UNIT_NAME);
            em = emf.createEntityManager();
            Query query = em.createNamedQuery("District.findByName");
            query.setParameter("name", district.getName());
            List<District> districts = query.getResultList();

            if (districts.isEmpty()) {
                em.getTransaction().begin();
                em.persist(district);
                em.getTransaction().commit();
                logger.info(district);
                response.setCode(ResponseCode.CREATED);
                response.setDescription("CREATED");
                response.setIsSuccess(true);
                response.setData(district);
                logger.info(response);
                return response;

            } else {
                logger.info(district);
                response.setCode(ResponseCode.CONFLICT);
                response.setDescription("Conflict");
                response.setIsSuccess(false);
                logger.info(response);
                return response;

            }

        } catch (PersistenceException ex) {
            logger.error(ex);
            System.out.println(ex.getMessage());
            if (em != null) {
                em.getTransaction().rollback();
            }
            response.setCode(ResponseCode.FAILED_DEPENDENCY);
            response.setDescription("Failed dependency.");
            response.setIsSuccess(false);
            return response;
        } catch (Exception ex) {
            logger.error(ex);
            System.out.println(ex.getMessage());
            response.setCode(ResponseCode.INTERNAL_SERVER_ERROR);
            response.setDescription("Failed to process request.");
            response.setIsSuccess(false);
            return response;
        } finally {
            if (em != null) {
                if (em.isOpen()) {
                    em.close();
                }
            }

        }
    }

    /**
     * *
     * Update district
     *
     * @param district
     * @param  id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = "application/json")
    @ResponseBody
    public ApiResponse updateDistrict(@PathVariable int id, @RequestBody District district) {
        ApiResponse response = new ApiResponse();
        BasicConfigurator.configure();
        EntityManagerFactory emf = null;
        EntityManager em = null;
        try {

            emf = Persistence.createEntityManagerFactory(Helper.PERSISTENCE_UNIT_NAME);
            em = emf.createEntityManager();
            District dist = em.find(District.class, id);
            em.getTransaction().begin();
            dist.setName(district.getName());
            dist.setIsActive(district.getIsActive());
            dist.setProvinceId(district.getProvinceId());
            em.getTransaction().commit();
            response.setCode(ResponseCode.CREATED);
            response.setDescription("CREATED");
            response.setIsSuccess(true);
            response.setData(district);
            logger.info(response);
            return response;

        } catch (PersistenceException ex) {
            logger.error(ex);
            System.out.println(ex.getMessage());
            if (em != null) {
                em.getTransaction().rollback();
            }
            response.setCode(ResponseCode.FAILED_DEPENDENCY);
            response.setDescription("Failed dependency.");
            response.setIsSuccess(false);
            return response;
        } catch (Exception ex) {
            logger.error(ex);
            System.out.println(ex.getMessage());
            response.setCode(ResponseCode.INTERNAL_SERVER_ERROR);
            response.setDescription("Failed to process request.");
            response.setIsSuccess(false);
            return response;
        } finally {
            if (em != null) {
                if (em.isOpen()) {
                    em.close();
                }
            }

        }
    }
}

我的实体类:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package zw.co.telecel.camsapi.entities;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 *
 * @author tinashehondo
 */
@Entity
@Table(name = "District")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "District.findAll", query = "SELECT d FROM District d"),
    @NamedQuery(name = "District.findById", query = "SELECT d FROM District d WHERE d.id = :id"),
    @NamedQuery(name = "District.findByName", query = "SELECT d FROM District d WHERE d.name = :name"),
    @NamedQuery(name = "District.findByIsActive", query = "SELECT d FROM District d WHERE d.isActive = :isActive")})
public class District implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "Id")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "Name")
    private String name;
    @Basic(optional = false)
    @Column(name = "IsActive")
    private boolean isActive;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "districtId")
    private Collection<Ward> wardCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "districtId")
    private Collection<Farm> farmCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "districtId")
    private Collection<Farmer> farmerCollection;
    @JoinColumn(name = "Province_Id", referencedColumnName = "Id")
    @ManyToOne(optional = false)
    private Province provinceId;

    public District() {
    }

    public District(Integer id) {
        this.id = id;
    }

    public District(Integer id, String name, boolean isActive) {
        this.id = id;
        this.name = name;
        this.isActive = isActive;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean getIsActive() {
        return isActive;
    }

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

    @XmlTransient
    public Collection<Ward> getWardCollection() {
        return wardCollection;
    }

    public void setWardCollection(Collection<Ward> wardCollection) {
        this.wardCollection = wardCollection;
    }

    @XmlTransient
    public Collection<Farm> getFarmCollection() {
        return farmCollection;
    }

    public void setFarmCollection(Collection<Farm> farmCollection) {
        this.farmCollection = farmCollection;
    }

    @XmlTransient
    public Collection<Farmer> getFarmerCollection() {
        return farmerCollection;
    }

    public void setFarmerCollection(Collection<Farmer> farmerCollection) {
        this.farmerCollection = farmerCollection;
    }

    public Province getProvinceId() {
        return provinceId;
    }

    public void setProvinceId(Province provinceId) {
        this.provinceId = provinceId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.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 District)) {
            return false;
        }
        District other = (District) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "zw.co.telecel.camsapi.entities.District[ id=" + id + " ]";
    }

}

我的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>zw.co.telecel</groupId>
    <artifactId>CAMSAPI</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <name>CAMSAPI</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.0.1.RELEASE</spring.version>
        <jackson.version>1.9.10</jackson.version>
        <jdk.version>1.6</jdk.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>

    <dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Jackson JSON Mapper -->
        <!--        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>-->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
            <type>jar</type>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Postman中出现的错误(注意我已将内容类型设置为'application / json'):

<body>
        <h1>HTTP Status 415 - Unsupported Media Type</h1>
        <hr/>
        <p>
            <b>type</b> Status report
        </p>
        <p>
            <b>message</b>Unsupported Media Type
        </p>
        <p>
            <b>description</b>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
        </p>
        <hr/>
        <h3>GlassFish Server Open Source Edition  4.1.1 </h3>
    </body>

1 个答案:

答案 0 :(得分:0)

这可以通过在请求映射中添加消耗来解决,如下所示:

@RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json", consumes = MediaType.APPLICATION_JSON_VALUE)