Search code examples
javahtmljspgetparameter

JSP request get parameter throws an exception


I'm beginning JSP. I have the following HTML form.

<form method='POST' enctype='multipart/form-data'>
    <input type="text" name="sittingPlaces">
    <textarea name="invitees"></textarea>
    <input type="submit" value="Submit">
</form>

And the following java code.

if (request != null && request.getContentType() != null) {
    int sittingPlaces = Integer.parseInt(request.getParameter("sittingPlaces"));
    String invites = request.getParameter("invitees");
}

I get an error at

int sittingPlaces = Integer.parseInt(request.getParameter("sittingPlaces"));

Any idea why? Thanks loads.


Solution

  • Check if a string request.getParameter("sittingPlaces") is a valid number with the following method:

    public boolean isInteger(String str) {
        try {
            Integer.parseInt(str);
        } catch (NumberFormatException e) {
            return false; // The string isn't a valid number
        }
        return true; // The string is a valid number
    }
    

    Or you can implement it inside your code:

    if (request != null && request.getContentType() != null) {
        String sittingPlacesStr = request.getParameter("sittingPlaces");
        try {
            int sittingPlaces = Integer.parseInt(sittingPlacesStr);
            String invites = request.getParameter("invitees");
        } catch (NumberFormatException | NullPointerException e) {
            // handle the error here
        }
    }
    

    The problem you are facing is that NumberFormatException is thrown because Java fails to convert your String to Integer because it does not represent a valid Integer. You should use a try-catch statement (just like in the example method above), to filter that Exception, as you have no control over the request coming from the client.

    Additionaly:

    You should also check if the request.getParameter("sittingPlaces") expression returns a valid string, and not a null: String sittingPlaces = request.getParameter("sittingPlaces");

    if (sittingPlaces != null {
        // Continue your code here
    } else {
        // The client request did not provide the parameter "sittingPlaces"
    }