Spring中的@ResponseBody mvc 4发送String但不向客户端发送任何其他Object

时间:2015-02-23 13:50:44

标签: java ajax spring

Spring Controller可以轻松地向客户端ajax / angularjs发送String类型的Object,但不能发送任何其他对象。

我在我的项目中使用Spring mvc 4.1.4,Maven,tiles,mysql,hibernate,jsp,ajax技术。 请帮我解决这个问题。

的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">

<servlet>
    <servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>


<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<welcome-file-list>
    <welcome-file>index.html</welcome-file>   
</welcome-file-list>
</web-app>

的pom.xml

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mylogistics</groupId>
<artifactId>MyLogistics</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>MyLogistics Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

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

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

    <dependency>
        <groupId>org.springframework.webflow</groupId>
        <artifactId>spring-webflow</artifactId>
        <version>2.4.1.RELEASE</version>
    </dependency>

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

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

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

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-asm</artifactId>
        <version>3.1.4.RELEASE</version>
    </dependency>



    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>

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

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

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


    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.2</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.2</version>
    </dependency>

    <dependency>
        <groupId>org.springmodules</groupId>
        <artifactId>spring-modules-validation</artifactId>
        <version>0.8a</version>
    </dependency>

    <dependency>  
     <groupId>javax.servlet</groupId>  
     <artifactId>jstl</artifactId>  
     <version>1.2</version>  
    </dependency>

    <dependency>  
     <groupId>javax.servlet</groupId>  
     <artifactId>javax.servlet-api</artifactId>  
     <version>3.0.1</version>  
     <scope>provided</scope>  
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
    </dependency>

    <dependency>  
        <groupId>javax.xml.bind</groupId>  
        <artifactId>jaxb-api</artifactId>  
        <version>2.2.6</version>  
    </dependency>  

    <dependency>  
        <groupId>javax.xml</groupId>  
        <artifactId>jaxb-impl</artifactId>  
        <version>2.1</version>  
    </dependency>

<!--Spring tiles  -->

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-core</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-jsp</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-api</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-servlet</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-template</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-request-api</artifactId>
        <version>1.0.6</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-request-servlet</artifactId>
        <version>1.0.6</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-mvel</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-request-freemarker</artifactId>
        <version>1.0.6</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-request-mustache</artifactId>
        <version>1.0.6</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-request-servlet-wildcard</artifactId>
        <version>1.0.6</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-portlet-wildcard</artifactId>
        <version>2.2.2</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-request-velocity</artifactId>
        <version>1.0.6</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-velocity</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-el</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-extras</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-compat</artifactId>
        <version>3.0.5</version>
    </dependency>


    <!--hibernate  -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.1.Final</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.4.3</version>
     </dependency>
     <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.4.3</version>
     </dependency>
     <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.3</version>
     </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.12</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

    <dependency>
        <groupId>net.java.dev.rome</groupId>
        <artifactId>rome</artifactId>
        <version>1.0.0</version>
    </dependency>

</dependencies>
<build>
    <finalName>MyTiles1-0.0.1-SNAPSHOT</finalName>
</build>
</project>

的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
   <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans.xsd 
   http://www.springframework.org/schema/mvc 
   http://www.springframework.org/schema/mvc/spring-mvc.xsd 
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.mylogistics.controller" />
<context:annotation-config />
<mvc:annotation-driven />

<bean id="viewResolver2"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="order" value="2"/>
    <property name="viewClass">
        <value>
            org.springframework.web.servlet.view.tiles3.TilesView
        </value>
    </property>
</bean>

<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/tiles.xml</value>
        </list>
    </property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/logistics"/>
        <property name="username" value="root" />
        <property name="password" value="" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="ds" />
     <property name="annotatedClasses">
        <list>
        <!--model package extention for db table  -->
            <value>com.mylogistics.model.User</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="userDAO" class="com.mylogistics.DAO.UserDAOImpl">
    <constructor-arg>
        <ref bean="sessionFactory" />
    </constructor-arg>
</bean>

<!--JSON Converter  -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        </list>
    </property>

</bean>
<bean id="jacksonMessageChanger"  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageChanger" />
        </list>
    </property>
</bean>

的index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MyLogistics</title>
<script type="text/javascript" src="/WEB-INF/js/jquery-1.11.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div>
    <center>
             hello 
                        <a href="/MyLogistics/login.html">login</a>
    </center>
 </div>
</body>
</html>

indexController.java

package com.mylogistics.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/index.html")
public class IndexController {
@RequestMapping
public String getIndexPage() {

    System.out.println("IndexController");
    return "index";
}
}

的login.jsp

<html>
<header>
</header>
<body>
<script type="text/javascript" src="/WEB-INF/js/jquery-1.11.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

<input type="button" value="hello" onclick = "test()"/> 
<input type="text" id="map"/>  
    <script type="text/javascript">
        function test(){
        console.log("enter into test function of ajax")
            var para = "branchType=rohit";
alert("abc");
            $.ajax({
                type: "POST",
                url: "/MyLogistics/hello.html",
                dataType: "json",
                /* data : JSON.stringify(user), */
                contentType: "application/json",
                data: para,
                success: function(response){
                    // we have the response
                    $('#map').val(response.value2);
                    alert(response);
                },
                error: function(e){
                    alert('Error: ' + e.error);
                }
            });
        }
</script>
</body>
</html>

loginController.java

package com.mylogistics.controller
@Controller
public class loginCntlr {

@RequestMapping("/login")  
public String home() {  
    System.out.println("INSIDE HOME");
    return "login";  
}

@RequestMapping(value = "/hello", method=RequestMethod.POST,headers="application/json")
public @ResponseBody Object helloTest(HttpServletRequest request,HttpServletResponse res){

    System.out.print("ok im here: "+request.getParameter("branchType"));

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("value1", "sanjana");
    map.put("value2", "shikha");

    System.out.println("ok im here: "+map.get("value1"));

    return map;
}
}

1 个答案:

答案 0 :(得分:0)

我解决了我的问题需要编辑。

<mvc:annotation-driven/>

将其添加为

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
    </mvc:message-converters>
</mvc:annotation-driven>

因为根据Spring 4 Migration Guide所有杰克逊1. *已被删除,您使用。

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

这个答案也很有用,SO question