1、Spring可以通过配置
<!-- 解决@ResponseBody返回字符串时的乱码问题 -->
bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> <bean class="org.springframework.http.converter.FormHttpMessageConverter" /> <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" /> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /> <bean class="org.springframework.http.converter.ResourceHttpMessageConverter" /> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list><value>text/plain;charset=UTF-8</value></list> </property> </bean> </list> </property> </bean>
来控制Controller将返回值做包装,例如List,Map等数据包装成Json格式的数据,但是包装过程中会将去加载pojo对象中的实例对象,如List,Object等信息,但是这些对象是延迟加载的,到了Controller层session已经关闭了,只返回其Porxy,如果要加载就需要加载数据库load其信息,这样就会出现session close,无法加载的错误。
解决方式有n种,但是涉及到一个问题,如果过滤我们不想加载的数据,在pojo上加上如下属性:
@Entity
@Table(name="xxx")
@JsonFilter("xxxfilter")
public class XXX{
}
Controller
@RequestMapping(value = "x")
@ResponseBody
public String x(HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException {
List<X> orgs = 后台查询返回的结果集;
ObjectMapper objectMapper = new ObjectMapper();
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("xxxfilter", SimpleBeanPropertyFilter.serializeAllExcept("要过滤的属性"));
return objectMapper.filteredWriter(filterProvider).writeValueAsString(orgs);
}