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">
<%
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">
<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.