Escaping in JSP for JSP and JS

Escaping for JSP

A JSP page will eventually rendered as HTML content in browser. In that case, lots of character like <, &, > need to be escaped before directly display them on the HTML page. This is when we need the escape for xml for html for JPS page.

To escape, you could use this in JSP page
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
${fn:escapeXml(myString)}

or
<c:out value="${myString}"/>

Escaping for Javascript

Sometimes in JSP page we write Javascript code. The javascript code has its own understand of character like single quote ' and double quote ", this is when we need escape in JSP but for the javascript usage.

The best way to do that is create a utility tag libary
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

  <description>Papyrus Utils Tag Library</description>
  <display-name>Custom Utils Functions</display-name>
  <tlib-version>1.0</tlib-version>
  <short-name>utils</short-name>

  <function>
    <description>
        JavaScript Escape function
    </description>
    <name>escapeJS</name>
    <function-class>org.apache.commons.lang.StringEscapeUtils</function-class>
    <function-signature>java.lang.String escapeJavaScript(java.lang.String)</function-signature>
  </function>

</taglib>

and use the utility tag lib in JSP:

<%@ taglib prefix="utils" uri="/WEB-INF/tld/utils.tld"%>
<dsp:page>
  <dsp:getvalueof var="a" param="a" />
  <script type="text/javascript">
      alert('${utils:escapeJS(a)}');
      window.location.href = "home.htm";
    </script>
</dsp:page>

You will also need commons-lang-2.5.jar in the WEB-INF lib.

评论

此博客中的热门博文

Nu förbjuder Kina handel med elfenben

Fader av pingyins

Kineserna vill köpa Volvos kompetens