在JSP / Spring MVC中删除所有字符串 [英] Escape all strings in JSP/Spring MVC

查看:145
本文介绍了在JSP / Spring MVC中删除所有字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ {someString} 

这个字符串当然可以包含特殊的html字符。目前有可能HTML注入恶意代码(例如,如果someString是一个javascript包含 - < script src ...> )。



如何确保所有字符串在打印之前都被转义?



我正在使用Spring MVC和JSP。

解决方案

您可以使用 JSTL核心

 <%@ taglib prefix =curi =http://java.sun.com/jsp/jstl/core%> 

使用 < c:out value =$ {someString}/> / a>标签来显示字符串。 < c:out> 转义HTML字符,以便您可以避免跨站点脚本,您可以通过设置属性 escapeXml = true 。另一个优点是,如果评估为 null ,则还可以提供默认值。



您还可以使用 fn:escapeXml() EL函数。您需要包含 JSTL函数

 <%@ taglib prefix =fnuri =http: //java.sun.com/jsp/jstl/functions%> 

另一种可能的方式是构建一个定制的 ELResolver


启用EL表达式评估的变量和属性解析行为的定制。


本博客提供了一个如何完成的工作示例。






对于整个Spring MVC应用程序,您可以在 web.xml 中指定转义:

 < context-param> 
< param-name> defaultHtmlEscape< / param-name>
< param-value> true< / param-value>
< / context-param>

但是,转义仅适用于 spring 标签,如:

 < form:input path =formFieldhtmlEscape =true/> 

最后,您可以尝试第三方库 XSSFilter


I display strings in my JSP this way:

${someString}

this string may, of course, contain special html characters. Currently it is possible to HTML-inject malicious code (eg. if someString is a javascript include - <script src...>).

How can I make sure that all strings are escaped before printing?

I am using Spring MVC and JSP.

解决方案

You can use JSTL core :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Use <c:out value="${someString}"/> tag to display Strings. <c:out> escapes HTML characters so that you can avoid cross-site scripting, you can specify that by setting the attribute escapeXml=true. Another advantage is that you can also provide a default value in case the value evaluates to null.

You can also use fn:escapeXml() EL function. You need to include JSTL functions for that .

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Another possible way , will be build a custom ELResolver.

Enables customization of variable and property resolution behavior for EL expression evaluation.

This blog provides a working example of how it can be done.


For the entire Spring MVC app , you can specify the escaping in the web.xml:

<context-param>
   <param-name>defaultHtmlEscape</param-name>
   <param-value>true</param-value>
</context-param>

But then the escaping applies only to the spring tags , like :

<form:input path="formField" htmlEscape="true" />

Lastly , you can try the third-party library XSSFilter.

这篇关于在JSP / Spring MVC中删除所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆