19.1 Parsing Parameters

Java Servlet Programming, 2nd Edition > 19. Odds and Ends > 19.1 Parsing Parameters

 
< BACKCONTINUE >

19.1 Parsing Parameters

If you've tried your hand at writing your own servlets as you have been reading through this book, you've probably noticed how awkward it can be to get and parse request parameters, especially when the parameters have to be converted to some non-String format. For example, let's assume you want to fetch the count parameter and get its value as an int. Furthermore, let's also assume that you want to handle error conditions by calling handleNoCount( ) if count isn't given and handleMalformedCount( ) if count cannot be parsed as an integer. To do this using the standard Servlet API requires the following code:

int count; String param = req.getParameter("count"); if (param == null || param.length() == 0) {   handleNoCount(); } else {   try {     count = Integer.parseInt(param);   }   catch (NumberFormatException e) {     handleMalformedCount();   } }

Does this look like any code you've written? It's not very pretty, is it? A better solution is to hand off the responsibility for getting and parsing parameters to a utility class. The com.oreilly.servlet.ParameterParser class is just such a class. By using ParameterParser, we can rewrite the previous code to be more elegant:

int count; ParameterParser parser = new ParameterParser(req); try {   count = parser.getIntParameter("count"); } catch (NumberFormatException e) {   handleMalformedCount(); } catch (ParameterNotFoundException e) {   handleNoCount(); }

The parameter parser's getIntParameter( ) method returns the specified parameter's value as an int. It throws a NumberFormatException if the parameter cannot be converted to an int and a ParameterNotFoundException if the parameter isn't part of the request. It also throws ParameterNotFoundException if the parameter had a value of the empty string. This often happens with form submissions for text fields when nothing is entered, something that for all intents and purposes should be treated the same as a missing parameter.

If it's enough that a servlet use a default value if there's a problem with a parameter, as is often the case, the code can be simplified even further:

ParameterParser parser = new ParameterParser(req); int count = parser.getIntParameter("count", 0);

This second version of getIntParameter( ) takes a default value of 0 that is returned in lieu of throwing an exception.

There's also a capability to find out if any required parameters are missing from a request:

ParameterParser parser = new ParameterParser(req); String[] required = { "fname", "lname", "account" }; String[] missing = parser.getMissingParameters(required);

The method returns null if no parameters are missing.

And finally, ParameterParser supports internationalization using the setCharacterEncoding( ) method. This specifies the charset to be used in interpreting parameter values. The value may come from a user cookie, a hidden form field, or the user's session:

ParameterParser parser = new ParameterParser(req); parser.setCharacterEncoding("Shift_JIS"); String japaneseValue = parser.getStringParameter("latinName");

Internally ParameterParser uses the getBytes( ) trick demonstrated in Chapter 13, to handle the conversion. Parameter names must still be given in the Latin-1 charset because the value lookup uses the not-yet-internationalized Servlet API getParameter( ) and getParameterValues( ) methods.

19.1.1 ParameterParser Code

The ParameterParser class contains more than a dozen methods that return request parameters two for each of Java's native types. It also has two getStringParameter( ) methods in case you want to get the parameter in its raw String format. The code for ParameterParser is provided in Example 19-1; ParameterNotFoundException is in Example 19-2.

Example 19-1. The ParameterParser Class
package com.oreilly.servlet; import java.io.*; import java.util.*; import javax.servlet.*; public class ParameterParser {   private ServletRequest req;   private String encoding;   public ParameterParser(ServletRequest req) {     this.req = req;   }   public void setCharacterEncoding(String encoding)                  throws UnsupportedEncodingException {     // Test the encoding is valid     "".getBytes(encoding);     // Getting here means we're valid, so set the encoding     this.encoding = encoding;   }   public String getStringParameter(String name)       throws ParameterNotFoundException {     String[] values = req.getParameterValues(name);     if (values == null) {       throw new ParameterNotFoundException(name + " not found");     }     else if (values[0].length() == 0) {       throw new ParameterNotFoundException(name + " was empty");     }     else {       if (encoding == null) {         return values[0];       }       else {         try {           return new String(values[0].getBytes("8859_1"), encoding);         }         catch (UnsupportedEncodingException e) {           return values[0];  // should never happen         }       }     }   }   public String getStringParameter(String name, String def) {     try { return getStringParameter(name); }     catch (Exception e) { return def; }   }   public boolean getBooleanParameter(String name)       throws ParameterNotFoundException, NumberFormatException {     String value = getStringParameter(name).toLowerCase();     if ((value.equalsIgnoreCase("true")) ||         (value.equalsIgnoreCase("on")) ||         (value.equalsIgnoreCase("yes"))) {         return true;     }     else if ((value.equalsIgnoreCase("false")) ||              (value.equalsIgnoreCase("off")) ||              (value.equalsIgnoreCase("no"))) {         return false;     }     else {       throw new NumberFormatException("Parameter " + name + " value " + value +                                       " is not a boolean");     }   }   public boolean getBooleanParameter(String name, boolean def) {     try { return getBooleanParameter(name); }     catch (Exception e) { return def; }   }   public byte getByteParameter(String name)       throws ParameterNotFoundException, NumberFormatException {     return Byte.parseByte(getStringParameter(name));   }   public byte getByteParameter(String name, byte def) {     try { return getByteParameter(name); }     catch (Exception e) { return def; }   }   public char getCharParameter(String name)       throws ParameterNotFoundException {     String param = getStringParameter(name);     if (param.length() == 0)       throw new ParameterNotFoundException(name + " is empty string");     else       return (param.charAt(0));   }   public char getCharParameter(String name, char def) {     try { return getCharParameter(name); }     catch (Exception e) { return def; }   }   public double getDoubleParameter(String name)       throws ParameterNotFoundException, NumberFormatException {     return new Double(getStringParameter(name)).doubleValue();   }   public double getDoubleParameter(String name, double def) {     try { return getDoubleParameter(name); }     catch (Exception e) { return def; }   }   public float getFloatParameter(String name)       throws ParameterNotFoundException, NumberFormatException {     return new Float(getStringParameter(name)).floatValue();   }   public float getFloatParameter(String name, float def) {     try { return getFloatParameter(name); }     catch (Exception e) { return def; }   }   public int getIntParameter(String name)       throws ParameterNotFoundException, NumberFormatException {     return Integer.parseInt(getStringParameter(name));   }   public int getIntParameter(String name, int def) {     try { return getIntParameter(name); }     catch (Exception e) { return def; }   }   public long getLongParameter(String name)       throws ParameterNotFoundException, NumberFormatException {     return Long.parseLong(getStringParameter(name));   }   public long getLongParameter(String name, long def) {     try { return getLongParameter(name); }     catch (Exception e) { return def; }   }   public short getShortParameter(String name)       throws ParameterNotFoundException, NumberFormatException {     return Short.parseShort(getStringParameter(name));   }   public short getShortParameter(String name, short def) {     try { return getShortParameter(name); }     catch (Exception e) { return def; }   }   public String[] getMissingParameters(String[] required) {     Vector missing = new Vector();     for (int i = 0; i < required.length; i++) {       String val = getStringParameter(required[i], null);       if (val == null) {         missing.addElement(required[i]);       }     }     if (missing.size() == 0) {       return null;     }     else {       String[] ret = new String[missing.size()];       missing.copyInto(ret);       return ret;     }   } } 
Example 19-2. The ParameterNotFoundException Class
package com.oreilly.servlet; public class ParameterNotFoundException extends Exception {   public ParameterNotFoundException() {     super();   }   public ParameterNotFoundException(String s) {     super(s);   } } 


Last updated on 3/20/2003
Java Servlet Programming, 2nd Edition, © 2001 O'Reilly

< BACKCONTINUE >


Java servlet programming
Java Servlet Programming (Java Series)
ISBN: 0596000405
EAN: 2147483647
Year: 2000
Pages: 223

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net