日期:2014-05-16  浏览次数:20332 次

Spring Json View之其他配置

其它配置?

  1. ContentType
  2. Encoding
  3. Javascript 劫持保护

?

1. Content type

?

?? 你可以像下面展现的那样,通过在JsonView设置contentType的值来改变输出内容的文本类型。?

<beans>

<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">

<property name="contentType"><value>application/json</value></property>

</bean>

</beans>

?

?

?

2. Encoding

?

?? 你可以像下面展现的那样,通过在JsonView设置encoding的值来改变输出内容的字符编码。?

<beans>

<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">

<property name="encoding"><value>ISO-8859-1</value></property>

</bean>

</beans> 

?

?3.Javascript 劫持保护

?

?? 为了防止出现如Fortify主页所述的Javascript劫持这种情况发生,通过设置hijackSafe属性为true,json对象会被随意地封装在Javascript注释里。

?

???

?

<beans>
    <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
        <property name="hijackSafe"><value>true</value></property>
    </bean>
</beans>

?

?

????效果: /*JSON{"command":{"placeofbirth":"Sydney"}}JSON*/

???

??? 默认以 '/* JSON.... JSON*/' 文本封装,您也可以通过设置hijackSafePrefixPostFix属性来进行配置。

???

 <beans>
    <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
        <property name="hijackSafe"><value>true</value></property>
        <property name="hijackSafePrefixPostFix"><value>TEST</value></property>
    </bean>
  </beans>

?

? 效果:/*TEST{"command":{"placeofbirth":"Sydney"}}TEST*/

?

? 在客户端代码可以删除封装。例如

?

var resp = eval("("+data.substring(data.indexOf("\/\*JSON")+6, data.lastIndexOf("JSON\*\/"))+")");<<<Monospaced>>>

?

? 感谢Hodge提出的建议。