ASP  «Prev  Next»

Lesson 9The ASP Server Object
Objective Use the ASP Server object to URL encode a page URL containing spaces.

ASP Server Object

The Web server plays the major role in any ASP application and the Server object is at the heart of ASP, but the object itself only has a few methods. Two of the Server object's methods encode text using either URL encoding or HTML encoding.

URL encoding

Scripts that process HTML Forms often involve URL encoding. As discussed previously, when you use the POST method, the browser will URL-encode input values for you and Request.Form will decode them.
If you want to pass strings through URLs, using the GET method, sometimes you put characters in a URL that are not allowed to be in a URL. As an example, consider a request to see a U of C T-shirt. We might want to call a page displaying that individual item. In larger websites, this would be a template filled in with photo or drawing, description, ordering information, and price. The T-shirt to be displayed is passed via the URL (which we read with the Request.QueryString() method). The URL might appear as:

http://www.mywebserver.com/product.asp?shirt=U of C Tshirt

The browser would stop interpreting the URL after the U because of the space between U and of. We need to URL-encode the string before passing it. If we call the item page from a hyperlink the code might look like this:
<A HREF="<%=Application("acWebHome")%>
<%Server.URLEncode("product.asp?shirt=U of C Tshirt")%>">
U of C Tshirt
</a>

Here is an explanation of the above code:
URL Encoding
  1. Blue Dot: This is the standard HTML code for a hyperlink anchor
  2. red dot: This is a variable containing our homepage URL (we first defined this in the lesson where we set up the Global.asa file. It will be replaced with the "real" URL for our site.
  3. Green Dot: URLEncode the string: product.asp?shirt=U of C Tshirt; the trailing"> is for the HREF
  4. Orange Dot: The text of the A HREF.
  5. Violet Dot: The code for the end of the hyperlink achor tag is shown above in purple.

URL Encoded String
The complete (and allowable) URL would now appear as:
http://www.mywebserver.com/product.asp?shirt=U%20of%20C%20Tshirt

The users' browser automatically converts each %20 to a space.

HTML encoding

HTML encoding works the same way but encodes characters differently, since what's acceptable in HTML is different from what's allowed in URLs. Note that HTMLEncode() does not produce formatted HTML output from your text. It only substitutes acceptable characters for unacceptable ones. In the next lesson, you will incorporate user information and an ad rotator into the course project