spring-mvc - 将 UNICODE 字符转换为通过 Spring MVC @ResponseBody 返回的 JSON 字符串中的 HTML 实体
问题描述
我正在编写一个 Spring MVC 应用程序,在其中我从 JSP 进行 AJAX 调用,该调用将返回一个 JSON 字符串。JSON 字符串中的某些文本会包含特殊字符,例如:
带有 unicode 8226 的项目符号字符或带有 unicode 8217 的撇号(引号)字符等标点字符
在我的 JSP 中,当我用这些字符填充文本区域时,它通常保持其原始形式并且显示良好。但是,我在应用程序的某些部分使用数据表编辑器,并且上述字符显示为?(问号)在网格中。
我想,解决方案是在形成 JSON 字符串时将 unicode 字符转换为 HTML 实体。例如,在控制器中,如果我扫描字符串中是否存在 8226 字符并将其替换为 • 并将此 JSON 字符串发送到 Datatables 网格,那么我可以正确看到项目符号字符。
我的问题是:在 Spring MVC 或其他工具中是否有任何方法可以检测大于 256 的 unicode 字符的存在,并在返回 JSON 字符串时将它们替换为 HTML 实体?在我的应用程序中有许多返回 JSON 字符串的 AJAX 调用,并且在每个@RequestMapping
方法中调用转换工具都是一些工作。我在想是否有一个 Spring 拦截器可以进行这种转换。或者是否有任何策略ContentNegotiatingViewResolver
来处理这种转换?
任何帮助表示赞赏。
这是我在我的映射@RestController
:
@RequestMapping(value = "/trips/{projectId}", method = RequestMethod.GET)
public String getProjectTrips(@PathVariable BigInteger projectId) throws IOException {
return projectTripReportGridService.getGridData(projectId);
}
方法projectTripReportGridService.getGridData
是:
public String getGridData(BigInteger projectId) throws IOException {
List<ProjectTripReport> entityViews;
entityViews = projectTripReportRepo.findAllByProjectId(projectId);
for (ProjectTripReport si : entityViews) {
if(si.getTripReport().indexOf(8226) > 0){
StringBuilder sb = new StringBuilder();
String tempReport = "";
String wholeString = si.getTripReport();
while(wholeString.indexOf(8226) > 0){
tempReport = wholeString.substring(0, wholeString.indexOf(8226));
sb.append(tempReport);
sb.append("•");
wholeString = wholeString.substring(wholeString.indexOf(8226) + 1);
}
sb.append(wholeString);
si.setTripReport(sb.toString());
}
}
Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy[]{new OneToManyExclusionStrategy(), new JpaExclusionStrategy()}).create();
return gson.toJson(gson.toJsonTree(entityViews));
}
解决方案
我知道我在我的问题中要问的是如何从应用程序的中心位置以 UTF-8 格式对 JSON 响应进行“编码”以获取“所有”JSON 响应字符串。下面是答案。springConfig.xml中需要添加如下脚本
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
推荐阅读
- javascript - Switch 语句不接受输入
- python - 使用新数据更新条形图
- javafx - JavaFx - 表格视图不在鼠标滚轮上滚动(禁用表格视图的滚动),当将表格单元格放置为 web 视图时
- javascript - 滚动时需要修复 div,但当页脚显示时,不应修复 div
- flutter - 如何检查数组中是否存在特定字符并在 Dart 中创建两个不同的数组?
- mysql - mybatis 和 MySQL Workbench 中的相同查询但返回不同的结果值
- mysql - 如何在 AWS 中恢复 MySQL 架构
- wordpress - NInja Forms 的标签 {wp:post_title} 在英文版页面中不起作用
- c - 带有 Windows API 的两个 cpp 文件的消息队列
- c - C 中的哪些打印调用不会在后台调用 malloc()?