1. 程式人生 > >SpringMVC專案新增@ResponseBody無效,Could not find acceptable representation

SpringMVC專案新增@ResponseBody無效,Could not find acceptable representation

配置:
spring-mvc.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
>
<!-- 註解掃描包:注入所有的註解包 --> <context:component-scan base-package="com.tgb" /> <!-- 開啟註解 --> <mvc:annotation-driven /> <!-- 不能同時訪問靜態資源和動態資源的問題 --> <mvc:default-servlet-handler/> <!-- 配置靜態資源,直接對映到對應的資料夾,不被DispatcherServlet處理,3.04新增功能,需要重新設定spring-mvc-3.0.xsd -->
<mvc:resources mapping="/img/**" location="/img/" /> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/html/**" location="/html/" /> <!-- 定義跳轉的檔案的前後綴 ,檢視模式配置 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 這裡的配置我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 --> <property name="prefix" value="/WEB-INF/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 檔案上傳配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <property name="maxUploadSize" value="100242880" /> <property name="maxInMemorySize" value="40960" /> </bean> </beans>

頁面返回異常json提示

    /**
     * 控制器內部的異常處理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        System.out.println("列印");
        return new Result(ResultCode.WEAK_NET_WORK);
    }

尷尬的發現返回不了json。報異常:
Could not find acceptable representation

經查閱資料發現存在兩種可能:

  1. 返回的實體物件沒有setter或者getter

  2. 沒有提供序列化的包,org.codehaus.jackson 和 com.fasterxml.jackson.core 至少提供一個. 建議使用後者。

看了下依賴,發現缺少jar包,引入後就可以了。
jackson-annotations-2.5.0.jar
jackson-core-2.5.0.jar
jackson-databind-2.5.0.jar