Escape all strings in JSP/Spring MVC

前端 未结 3 1045
野趣味
野趣味 2020-12-25 13:59

I display strings in my JSP this way:

${someString}

this string may, of course, contain special html characters. Currently it is possible t

3条回答
  •  清歌不尽
    2020-12-25 14:16

    You can use JSTL core :

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

    Use tag to display Strings. 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:

    
       defaultHtmlEscape
       true
    
    

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

    
    

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

提交回复
热议问题