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

北战南征 提交于 2020-01-16 07:06: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/parsed?

For example:

textarea (named ta):

simple test with ampersand & in textarea

url:

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

回答1:


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.



来源:https://stackoverflow.com/questions/2351978/how-to-convert-entites-of-jsp-request-arguments-for-html-form-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!