使用弹簧3的@ResponseBody返回对象不起作用

时间:2013-01-30 05:30:52

标签: java spring spring-mvc

我试图在控制器中使用@responseBody来返回一个对象,我得到了异常。我在应用程序中有jackson jar仍然说它出现以下错误ClassNotFoundException无法激活

HTTP Status 500 - 

--------------------------------------------------------------------------------

type Exception report

message 

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

root cause 

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0': Cannot create inner bean '(inner bean)' of type [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter] while setting bean property 'messageConverters' with key [6]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#8': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.codehaus.jackson.map.ObjectMapper 

root cause 

org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#8': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.codehaus.jackson.map.ObjectMapper

这是我的代码---->

 import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.SessionAttributes;
    import org.springframework.web.servlet.ModelAndView;

    import com.lol.laks.sample.beans.*;

    @Controller
    @SessionAttributes
    public class ContactsController {
      @RequestMapping(value = "/addContact", method = RequestMethod.POST,     produces="application/json")
        public @ResponseBody Contacts addContact(@ModelAttribute("contact") Contacts contact,BindingResult result) {

            System.out.println("First Name:" + contact.getFirstname() +
                        "Last Name:" + contact.getLastname());
            return contact;
        }

        @RequestMapping("/")
        public ModelAndView showContacts() {

            return new ModelAndView("contacts", "command", new Contacts());
        }
    }

这是jsp - >

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> (http://www.w3.org/TR/html4/loose.dtd%27%3E)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<body>
<form:form method="post" action="addContact">

<table>
<tr>
    <td><form:label path="firstname">First Name</form:label></td>
    <td><form:input path="firstname" /></td>
</tr>
<tr>
    <td><form:label path="lastname">Last Name</form:label></td>
    <td><form:input path="lastname" /></td>
</tr>
<tr>
    <td><form:label path="lastname">Email</form:label></td>
    <td><form:input path="email" /></td>
</tr>
<tr>
    <td><form:label path="telephone">Telephone</form:label></td>
    <td><form:input path="telephone" /></td>
</tr>
<tr>
    <td colspan="2">
        <input type="submit" value="Add Contact"/>
    </td>
</tr>
</table> 

</form:form>
</body>
</html> 

这是servlet.xml ---&gt;

<?xml version="1.0" encoding="UTF-8"?>
<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:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> (http://www.springframework.org/schema/context/spring-context-3.0.xsd%27%3E)

  <context:component-scan base-package="com.tcs.laks.sample" />

 <mvc:annotation-driven />
 <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
    <map>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
  </property>
  <property name="viewResolvers">
    <list>
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <!--  <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>
  <property name="defaultViews">
    <list>
      <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
        <property name="prefixJson" value="true"/>
      </bean>
    </list>
  </property>
</bean>   
</beans> 

这是豆子

import org.springframework.stereotype.Component;

@Component
public class Contacts {
        private String firstname;
        private String lastname;
        private String email;
        private String telephone;
        public String getFirstname() {
            return firstname;
        }
        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }
        public String getLastname() {
            return lastname;
        }
        public void setLastname(String lastname) {
            this.lastname = lastname;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public String getTelephone() {
            return telephone;
        }
        public void setTelephone(String telephone) {
            this.telephone = telephone;
        }
} 

请告诉我为什么当Spring 3自动将对象转换为json时,虽然包含了正确的jar,但它无法实例化该类?

2 个答案:

答案 0 :(得分:3)

在servlet.xml中包含mvc:annotation-driven应该可以工作。

如果你使用@responsebody,你将绕过viewresolvers。 如果MappingJacksonHttpMessageConverter存在于写入响应体的类路径中,它将实例化它。

希望这也有效。

答案 1 :(得分:1)

我找到答案Myself主要问题是添加了

的servlet.xml文件
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> 

完成了工作。