繁体   English   中英

在Spring 3中使用@ResponseBody返回对象不起作用

[英]Returning object using @ResponseBody with spring 3 doesn't work

我正在尝试在控制器中使用@responseBody来返回对象,如果我遇到异常。 我在应用程序中仍然有杰克逊罐子,但仍然显示以下错误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 --->

<?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,为什么它无法实例化该类?

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

如果您使用@responsebody,您将绕过viewresolvers。 如果您的类路径中存在MappingJacksonHttpMessageConverter,则AnnotationMethodHandlerAdapter将实例化MappingJacksonHttpMessageConverter,该类路径将写入响应主体。

希望这也可以。

我找到了答案“我自己”,主要问题是在添加servlet.xml文件时

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> 

做了工作。

暂无
暂无

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

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