java - Spring 3.0返回的json字符串显示为问号(ResponseEntity)

标签 java angularjs json spring unicode

我有用于练习的网络应用程序。 并且有关于 json 返回的问题。

编码为UTF-8的unicode字符串通常存储在orcl数据库中。 在服务器阶段这个 unicode 字符串是正常状态 但在前端(angularjs)中,这个 unicode 字符串显示为问号。 前端所有unicode字符串都显示为问号。

我现在已经尝试了很多方法并查找了很多地方来解决这个问题。 我不确定我必须为此做什么。

我使用 Spring 3.0.5 、Angular.js 1.2、oracle 数据库、tomcat 7。

这是 Controller 方法。

@RequestMapping(value = {"/categories"}, method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<String> getCategories() throws ParseException, UnsupportedEncodingException {

    List<Category> categories= postService.getCategories();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");

    if (categories == null) {
        return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
    }

    return new ResponseEntity<String>(JSONResponseUtil.getJSONString(categories), headers, HttpStatus.OK);
}

这是我的 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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    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.xsd
    http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@:1521:ORCL" />
    <property name="username" value="" />
    <property name="password" value="" />
    <property name="maxActive" value="20" />
    <property name="maxWait" value="6000" />
    <property name="poolPreparedStatements" value="true" />
    <property name="defaultAutoCommit" value="true" />
    <property name="initialSize" value="10" />
    <property name="maxIdle" value="20" />
    <property name="validationQuery" value="select sysdate from dual" />
    <property name="testWhileIdle" value="true" />
    <property name="timeBetweenEvictionRunsMillis" value="7200000" />
</bean>


<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>


<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="typeAliasesPackage" value="acutls.model" />
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="/WEB-INF/mybatis-config.xml" />
    <property name="mapperLocations">
        <array>
            <value>classpath*:/acutls/mybatis/repository/mapper/**/*.xml</value>
        </array>
    </property>     
</bean>

<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

和第二个 Spring 配置文件

<?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/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.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="acutls" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
</bean>
<context:annotation-config />
<mvc:annotation-driven/>
<mvc:resources location="/UploadedImage/" mapping="/UploadedImage/**"/>
<mvc:resources location="/resources/" mapping="/resources/**"/>

 <mvc:view-controller path="/Login" view-name="/resources/templates/login.html"/>
<mvc:view-controller path="/" view-name="/resources/templates/index.html"/> 

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=utf-8</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </list>
    </property>
</bean>


</beans>

和angular.js查看html文件,数据存储在$scope.categories

<div class="modal fade" id="beforeWriteModal" tabindex="-1"
    role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div align="center" class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">where did you travel?</h4>
            </div>
            <div class="modal-body-beforeWriteModal">
                <input class="form-control" ng-blur="checkPostInfo()" type="text" ng-model="post.title" placeholder="enter title here" required />
                <select class="form-control" ng-model="post.category" ng-options="c.categoryId as c.categoryName for c in categories"></select>
            </div>
            <div align="left" class="modal-footer">
                <input id="postcheckbtn" class="btn btn-primary" type="button"
                    value="submit" ng-click="hideinfomodal()" />
            </div>
        </div>
    </div>
</div>

和示例数据

 {
"postId": "POST14042622131875",
"realPath": "1398517998159_8.jpeg",
"title": "신혼여행",
"textContent": "",
"nickName": "Demian",
"userId": "Demian",
"categoryName": "스페인",
"categoryId": "ES"
}

和错误数据

{
"postId": "POST14042622131875",
"realPath": "1398517998159_8.jpeg",
"title": "????",
"textContent": "",
"nickName": "Demian",
"userId": "Demian",
"categoryName": "???",
"categoryId": "ES"
}

debug response screen capture

最佳答案

您应该设置 ResponseEntity header ,例如

@RequestMapping("/test22")
@ResponseBody
public ResponseEntity<String> test22(){
    MultiValueMap<String, String> map=new LinkedMultiValueMap<>();
    map.put("Content-Type", Lists.newArrayList("text/html;charset=UTF-8"));
    return new ResponseEntity<String>("you body",map , HttpStatus.OK);
}

未设置 header 内容类型将使用默认字符集 ISO-8859-1

StringHttpMessageConverter

@Override
protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
    if (this.writeAcceptCharset) {
        outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
    }
    Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
    StreamUtils.copy(str, charset, outputMessage.getBody());
}

关于java - Spring 3.0返回的json字符串显示为问号(ResponseEntity),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37856955/

相关文章:

javascript - ngTable 仅显示第一列

javascript - 如何动态地使用 json 数据填充下拉列表(部分分为三个不同的下拉列表)并在单击时遇到操作

java - JSON Jackson - 使用自定义序列化程序序列化多态类时出现异常

java - fragment .java 错误 : No suitable method in found and cannot resolve method 'inflate(int, boolean)'

javascript - 使用vm作为 Controller 时如何设置输入字段的初始值?

java - 在 List<Integer> 上使用 set 方法会导致不支持的操作异常

java - 如何在 Vaadin 中将 Keylistener 添加到 ListSelect?

java - 在 CorDapp 上本地部署节点时出现异常 - 节点信息生成

java - 从 ArrayList 创建 JTable

javascript - 刷新最初传入 AngularJS 中 modalInstance 的数据