views:

372

answers:

1

I am new to JSP and generating a form with a text area. Is there a library to convert the text from/to an HTML's FORM TEXTAREA that will convert to/from entities for the URL to be properly formatted/parsed?

For example:

textarea (named ta):

simple test with ampersand & in textarea

url:

http://.../myapp.jsp?ta=simple+test+with+ampersand+%26+in+textarea
+2  A: 

If you are using scriptlets, you can use the URLEncoder.encode(String string, String encoding) to encode Strings in safely for use in URLs. It throws UnsupportedEncodingException, so make sure you catch that. Here's an example JSP that encodes your string and displays it as the body of the document.

<%@ page language="java"
  import="java.net.URLEncoder"
  contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;

<%

String encoded = null;
try {
    encoded = URLEncoder.encode("simple test with ampersand & in textarea", "UTF-8");
} catch (Exception e) {

}

%>
<html>
  <head>
    <title>MyTitle</title>
  </head>
  <body>
    <%=encoded%>
  </body>
</html>

It would be better practice to use JSTL, in this case specifically the <c:url> tag which will automatically encode its content. For example, to get the encoded String URL you mentioned in your question, you might do this:

<c:url var="myEncodedURL" value="http://.../myapp.jsp"&gt;
  <c:param name="ta" value="simple test with ampersand & in textarea"/>
</c:url>

Which you could then access with the expression ${myEncodedURL}. If you're not using JSTL at the moment then there's a learning curve involved - you'll need to set up the taglib, import it at then use it. You can see more on how to use this JSTL tag on developerworks.

Brabster
I am getting the compiler error, URLEncoder cannot be resolved. What do I need to import? Can you provide any header or environment configuration that I require to use URLEncoder?BTW - I will take your recommendation to switch over to JSTL.
mobibob
Brabster - you might want to review my second question about importing StringEscapeUtils from apache.org.commons.lang that is also not resolving. I will give you credit for both if I get this to work!Thanks in advance.
mobibob
You need to import java.net.URLEncoder - if you use an IDE like Eclipse or NetBeans it will help you find the imports you need.
Brabster
Already been there :)
Brabster
It sounds like you might be quite new to Java and JSP. I can recommend the javapassion free tutorials if you are interested in understanding the language better for the future http://www.javapassion.com/j2ee/ (for JSP, etc.)
Brabster
PERFECT! I will start on the tutorials today!
mobibob