Sunday, 26 June 2016

How to retrieve HTML form parameters from the request ?


All form data from both the query string + post body are aggregated into the request parameter set.
The parameters sent in URI query string are stored by the servlet container as a set of name/value pairs.


Multiple parameter values can exist for any given parameter name. (Like, a=123&a=567)
 

Methods in ServletRequest interface
  • getParameter : returns value for a given parameter
  • getParameterNames : returns array of all names of parameters (No value)
  • getParameterValues : returns an array of String objects containing all the parameter values associated with a parameter name

Scenario : If a request is made with :

  • A query string of a=hello
    and
  • A post body of a=goodbye&a=world
The resulting parameter set would be ordered a=(hello, goodbye, world)

What are the triggers that cause a browser to use a HTTP method ?


HTTP POST
  • Allows the client to send data of unlimited length to server
  • Usage : Useful when sending sensitive information like, Credit card numbers

HTTP GET

  • Retrieves whatever information sent in Request URI

HTTP HEAD

  • It is a GET request that returns no body in the response, on the request header fields.
  • The client sends a HEAD request when it wants to see only the headers of a response, such as Content Type or Content-Length.
    • This method counts the number of output bytes in the response to set the Content-Length header accurately.
  • Usage :
    • can be used for obtaining meta-information about the entity implied by the request without transferring the entity-body itself.
    • often used for testing hypertext links for validity, accessibility, and recent modification.

What methods I should ovveride in a servlet ?


For creating a website, create a HTTP servlet.
  • Extend HttpServlet (an Abstract class)
  • Override at least one method (usually one of the following) :
    • doGet : to support HTTP GET requests
    • doPost :  for HTTP POST requests
    • doPut :  for HTTP PUT requests
Don't override service method, as it handles HTTP requests by dispatching them to handler methods for each type of HTTP request.


Study material for SCWCD

What are the common Exception handling rules ?


Exception handling rules


#1. Prefer exceptions over Returning Error Codes
if (deletePage(page) == E_OK) {
   if (registry.deleteReference(page.name) == E_OK) {
     ....
   } else {
      .....
   }
} else {
   ....
}

try {
   deletePage(page);

   registry.deleteReference(page.name);
} catch (Exception e) {
    logger.log(e.getMessage());
}



#2. Extract Try/Catch Blocks
Example. More better than above - 1 method with core logic , other with try/catch block only
try {
   deletePageAndAllReferences(page);
} catch (Exception e) {
   logError(e);
}


private void deletePageAndAllReferences(Page page) throws Exception {….}


#3. Use Unchecked Exceptions
Checked exceptions :
  • increases error handling in many parts of our system
  • Breaking Encapsulation
So, Use checked exceptions only when :
  • If the caller knows & wants how to handle it
  • Dealing with Critical Systems or libraries

#4. Don’t Eat the Exception
try {
  ...
} catch (Exception ex) { }


try {
   ...
} catch (Exception ex) {
   ex.printStackTrace();
}



#5. Resist Temptation to write a Single Catchall
Single handler for many errors reduces the reliability of your program.

#6. Always use Catchall after handling known ones
You may not be sure that you handled all possible exceptions, so provide a default handler (catchall)

#7. Don’t Return NULL
Returning null needs its handling at all the places, which makes code awful.
Solution
  • Return a special case object
  • Wrap with another method that throws exception

#8. Don’t Pass NULL
Passing NULL should be handled inside the method or NullPointerException will be thrown
Unless the used API is passing NULL, you should avoid it.

What are the common Method writing rules ?


METHOD WRITING RULES

#1. Small
Method should be :
  • Small
  • A screen-full or 
  • should hardly ever be 20 lines long.
Example
public static String renderPage (PageData pageData, boolean isSuite) throws Exception {
   if (isTestPage(pageData))
         includeSetupAndTeardownPages(pageData, isSuite);
   return pageData.getHtml();
}


#2. Do One Thing
  • Method should do one thing only and should do it well.

#3. One Level of Abstraction per Method
  • Don't mix levels of abstraction within a method 
    • Confusion between a essential and detail

#4. Avoid switch statements
  • It violates "Do One Thing" rule
  • Convert switch statement into Abstract Factory
  • Always not possible but Try to get rid of Switch statements

#5. Use descriptive names
Consider : 
  • It may take time to choose a good name
  • Name can be long

#6. Minimize method arguments
  • Pass the objects

#7. Have no side effects
Example : Below method name is checkPassword but it also initializing session
public boolean checkPassword(String userName, String password) {
  User user = UserGateway.findByName(userName);
  if (user != User.NULL) {
     String codedPhrase = user.getPhraseEncodedByPassword();
     String phrase = cryptographer.decrypt(codedPhrase, password);
     if ("Valid Password".equals(phrase)) {
          Session.initialize();
          return true;
     }
  }
  return false;
}


Problem. If someone doesn't know it is also initializing session, and calls it just for checking password only, it may cause data loss.

Solution. If we can't divide it, change its name to : checkPasswordAndInitializeSession


#8. Separate Command from Query
Methods should either do something or answer something
if (set("username", "unclebob"))...

if (attributeExists("username")) {
  setAttribute("username", "unclebob");
  ...
}


What are the common Naming rules ?


NAMING RULES

#1. Use Intention-Revealing Names
int d; // elapsed time in days
int elapsedTimeInDays;

#2. Avoid Disinformation
Use below name only if this variable is a List type
accountList

#3. Long names which can take long time to differentiate
XYZControllerForEfficientHandlingOfStrings
XYZControllerForEfficientStorageOfStrings

#4. Use searchable names
Karakter
7
DAYS_PER_WEEK
week



#5. Make Meaningful Distinction
public static void copyChars(char a1[], char a2[]) {
  for (int i = 0; i < a1.length; i++) {
     a2[i] = a1[i];
  }
}


public static void copyChars(char[] source, char[] destination) {
   for (int i = 0; i < source.length; i++) {
      destination[i] = source[i];
   }
}



#6. Use Pronounceable Names
genymdhms

#7. Avoid Encodings
Example : Prefixing member variable with 'm_'
m_countryCode

Example : Interfaces & Implementation
Interface IShapeFactory {...}
Class ShapeFactory implements IShapeFactory {...}


Interface ShapeFactory {...}
Class ShapeFactoryImpl implements ShapeFactory {...}



#8. Avoid Mental Mapping
String url;
instead of 
String r;

#9. Don’t Be Cute
DeleteItems()
instead of
HolyHandGrenade()

dispatchRequest()
instead of
edenyFelRequest()

* Names based on cultural base or sense of humor will only be remembered by people who know it


#10. Pick One Word per Concept
Example : using fetch(), retrieve(), and get() in the same layer
* Caller will be confused which method to call ?


#11. Don’t Add Extra-free Context
Example : Prefixing every class with MBS in a Mobile Banking System
class MBSCustomer
class MBSSimCard