错误406:在Spring 3.x中无法返回JSON响应

时间:2015-01-30 11:02:31

标签: java json spring hibernate spring-mvc

我尝试使用spring mvc和hibernate输出Json响应。当我试图按照我的控制器设计点击网址时。我收到此错误

HTTP状态406         此请求标识的资源只能生成具有根据请求不可接受的特征的响应"接受" headers()。

我在我的pom.xml中添加了 jackson-mapper-asl

我的Web.xml

        <?xml version="1.0" encoding="UTF-8"?>
        <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">

        <display-name>restApp</display-name>

         <servlet>
         <servlet-name>spring</servlet-name>
         <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
          </servlet-class>
          <load-on-startup>1</load-on-startup>
         </servlet>

        <servlet-mapping>
         <servlet-name>spring</servlet-name>
         <url-pattern>/</url-pattern>
         </servlet-mapping>
        </web-app>

我的 dispatcher-servlet.xml(spring-servlet.xml)

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.1.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <context:component-scan base-package="model,controller,dao,service" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />
    <!--  
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        id="jspViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
          <map>
              <entry key="html" value="text/html"/>
              <entry key="json" value="application/json"/>
              <entry key="xml"  value="application/xml"/>
          </map>
        </property>
         <property name="viewResolvers">
            <list>
              <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
                <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                <property name="prefix" value="/WEB-INF/jsp/"/>
                <property name="suffix" value=".jsp"/>
              </bean>
            </list>
        </property>
    </bean>

    <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        id="dataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/world"></property>
        <property name="username" value="root"></property>
        <property name="password" value="Tpg@1234"></property>
    </bean>

    <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        id="sessionFactory">
        <property name="dataSource" ref="dataSource"></property>
        <property name="annotatedClasses">
            <list>
                <value>model.Book</value>   
                <value>model.Chapter</value>
                <value>model.Status</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>            
        </property>
    </bean>

    <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager"
        id="hibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>


    <bean id="persistenceExceptionTranslationPostProcessor"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <bean id="BookDao" class="dao.BookDaoImpl"></bean>
    <bean id="ChapterDao" class="dao.ChapterDaoImpl"></bean>
    <bean id="Bookservice" class="service.BookServiceImpl"></bean>
    <bean id="ChapterService" class="service.ChapterServiceImpl"></bean>

</beans>

这是我的控制器。

@Controller
@RequestMapping(value="/book")
public class BookController {

@Autowired
BookService bookService;

@Autowired
BookDao bookDao;

static final Logger logger = Logger.getLogger(BookController.class);

@RequestMapping(value="/add", method = RequestMethod.POST,headers="Accept=*/*")
public @ResponseBody
Status addBook(@RequestBody Book book){
    try{
        bookService.addBook(book);
        return new Status(1,"book added successfully");
    }catch(Exception e){
        return new Status(0, e.toString());
    }
}


@RequestMapping(value="/{bookId}",method = RequestMethod.GET,headers="Accept=*/*")
public @ResponseBody
Book getBook(@PathVariable("bookId")Integer bookId){
    Book book = null;
    try{
        book = bookService.getBookById(bookId);
    }catch(Exception e){
        e.printStackTrace();
    }
    System.out.println("book returned");
    System.out.println(book);
    return book;
}

@RequestMapping(value="/list",method=RequestMethod.GET,headers="Accept=*/*")
public @ResponseBody
List<Book> getBookList(){
    List<Book> bookList = null;
    try{
        bookList = bookService.getBookList();
    }catch(Exception e){
        e.printStackTrace();
    }
    System.out.println("bookList returned");
    System.out.println(bookList);
    return bookList;
}

@RequestMapping(value = "/delete/{bookId}", method = RequestMethod.GET,headers="Accept=*/*")
public @ResponseBody
Status deleteEmployee(@PathVariable("bookId") long bookId) {

    try {
        bookService.deleteBook(bookId);;
        return new Status(1, "Employee deleted Successfully !");
    } catch (Exception e) {
        return new Status(0, e.toString());
    }

}

现在,当我试图点击网址时,它会发出错误&#34; HTTP状态406&#34;。 由该请求识别的资源仅能够根据请求生成具有不可接受的特征的响应&#34;接受&#34; headers()。

在点击网址后,Hibernate查询在控制器中正常运行。只是因为我没有得到JSON回复。

我的POJO课程(Book.java)

@Entity
@Table(name="book")
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class Book implements Serializable{

@Id
@Column(name="bookId")
@GeneratedValue
private Integer bookId;

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

@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(
        name="BookChapter",
        joinColumns = @JoinColumn(name="BOOK_ID"),
        inverseJoinColumns = @JoinColumn(name="CHAPTER_ID")
)
public Set<Chapter> chapter;

public Integer getBookId() {
    return bookId;
}

public void setBookId(Integer bookId) {
    this.bookId = bookId;
}

public String getBookName() {
    return bookName;
}

public void setBookName(String bookName) {
    this.bookName = bookName;
}

public Set<Chapter> getChapter() {
    return chapter;
}

public void setChapter(Set<Chapter> chapter) {
    this.chapter = chapter;
}

}

0 个答案:

没有答案