13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

412Chapter 18Servlets: Java Pressed into Servicethe loop, <strong>on</strong>e for each iterati<strong>on</strong> of the loop. (If you’re not picturing that, bepatient. There are examples of this coming up. If you’re not c<strong>on</strong>versant inHTML, then you better check out some of the HTML references at the endof this chapter. We’re going to assume that you speak HTML fluently. Come<strong>on</strong>—we can’t cover everything in <strong>on</strong>e book.)The other side of dynamic c<strong>on</strong>tent comes from variable input. Google’ssearch engine, for example, generates different pages for different search strings.It is the variati<strong>on</strong> in user input that results in varying output pages. On a Webpage, user input typically comes from an HTML form. The form values canbe passed either as parameters <strong>on</strong> the URL or as POST values. URL parametersare also easy to generate by hand, or to code in place in tags. For example,is an HTML tag for a hyperlink which will invoke the doSuch servlet and passin the parameters cmd and value. (It’s a servlet not because the pathname is/servlet, but we use that for illustrative purposes. In fact, the servlet invokedmay not even be called doSuch; it all part of servlet mapping that recognizescertain URLs as aliases for particular servlets. See Chapter 19 for a fullerexplanati<strong>on</strong>.)The point is, we can invoke the same servlet repeatedly (even simultaneously)but with different values for our parameters, so we can program it fordifferent behaviors and different output.These parameters are available to the servlet via the request argument ofthe doGet() and doPost() methods. You can get an enumerator over all ofthe arguments (using getParameterNames()), or if you know it’s name (andyou likely would, since you’re writing the program) you can ask for a particularargument.The previous example used an argument called cmd, whose value we couldretrieve thus:String act = request.getParameter("cmd");The parameters all come as Strings. If your arguments are numeric, you’llhave to parse them (and error-check them—HTML forms are, understandably,weak <strong>on</strong> validating their input; t<strong>on</strong>s of JavaScript have been written to dealwith this, but this is bey<strong>on</strong>d the scope of this book.)Some parameters may have embedded spaces and other special charactersthat would disrupt a URL. To deal with that, browsers encode the characters

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!