|
Uniform Resource Locators (URLs) are wonderful thingsthey allow us to point to information all over the Internet and local networks. We are all familiar with such strings as http://www.example.com/page.jsp?id=1. If you have done much in the way of web application development, you recognize that this string points to a specific JSP called page.jsp on a web server with a domain name of www.example.com and is sending a parameter called id with a value of 1. Special characters, such as ? and =, are used as tokens by the server to indicate how to parse the incoming request. Now, let's imagine that we want to use a parameter value that happens to have a ?, =, or even a space character. This is allowable according to the specification using a special encoding format (www-form-urlencoded, commonly referred to as URL encoding). Make sure, however, that you are encoding the data to be sent along as a parameter, not the URL itself. Listing 12-6 shows an example of how a complex URL parameter is encoded and then appended to the URL. Listing 12-6. URL Parameter Encoding Sourcepublic static void formURLEncodingDemo() { printHeader("Form URL Encoding Demo"); try { String badParameterValue = "http://www.example.org/page.jsp?foo=bar next"; System.out.println( "Here is an example of a difficult "); System.out.println("string to use as a URL parameter:"); System.out.println(badParameterValue); byte[] badURLresult = new URLCodec().encode(badParameterValue.getBytes()); System.out.println(); System.out.println("Here is the string, properly"); System.out.println("formatted for use as a link:"); System.out.println( "http://www.example.com/view.jsp?url=" + new String(badURLresult)); System.out.println(); } catch (Exception e) { e.printStackTrace(); } } As shown in Listing 12-7, the parameter passed along is another URL. This could be useful in a variety of situationsfor example, our web application might verify the availability of a web site, and so a URL needs to be passed along as a parameter. Listing 12-7. URL Parameter Encoding Results================================ Form URL Encoding Demo ================================ Here is an example of a difficult string to use as a URL parameter: http://www.example.org/page.jsp?foo=barnext Here is the string, properly formatted for use as a link: http://www.example.com/view.jsp?url=http%3A%2F%2Fwww.example. org%2Fpage.jsp%3Ffoo%3Dbar+next |
|