开发者

How to convert entites of JSP request arguments for html form textarea?

开发者 https://www.devze.com 2022-12-21 23:29 出处:网络
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/p

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:

textare开发者_Python百科a (named ta):

simple test with ampersand & in textarea

url:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消