-1

my java file is as follows-----

package servletjsp;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddServlet extends HttpServlet 
{
    public void service(HttpServletRequest req,HttpServletResponse res) 
    {
        int i=Integer.parseInt(req.getParameter("num1"));
        int j=Integer.parseInt(req.getParameter("num2"));

        int k=i+j;
        System.out.println("the result is "+ k);
    }
} 

My html file is as follows----

<!DOCTYPE html>
<html>
    <body>
        <form action="add">
            Enter 1st number: <input type="text"  name=num1><br>
            Enter 2nd number: <input type="text"  name=num1><br>
            <input type="submit">
        </form>
    </body>
</html> 

my web.xml file is as follows----

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" 
         version="3.1">
    <servlet>
        <servlet-name>abc</servlet-name>
        <servlet-class>servletjsp.AddServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>abc</servlet-name>
        <url-pattern>/add</url-pattern>
    </servlet-mapping>  
</web-app>

when I clicked on submit code in web browser, it was returning HTTP Status 405 get method is not suppported; now it is returning HTTP Status 500.

java.lang.NumberFormatException.

Please give me the correct code so that it may add 2 numbers.

geco17
  • 5,152
  • 3
  • 21
  • 38
Ritik Agrawal
  • 9
  • 1
  • 1
  • 2
  • thanks but still it gives error.... HTTP status 500 – Ritik Agrawal Jul 04 '18 at 17:18
  • 1
    So you get a Status 500 java.lang.NumberFormatException. The stack trace of the exception should tell you where and why this exception is thrown. Have you done some debugging? Printed the value of the parameters before trying to parse them? What do you enter in the two fields? Note that you should NOT override service(). Read the javadoc of HttpServlet. – JB Nizet Jul 04 '18 at 17:18
  • here is the error...Exception java.lang.NumberFormatException: null java.lang.Integer.parseInt(Integer.java:542) java.lang.Integer.parseInt(Integer.java:615) servletjsp.AddServlet.service(AddServlet.java:12) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) Note The full stack trace of the root cause is available in the server logs. .........................please tell what to do – Ritik Agrawal Jul 04 '18 at 17:20
  • then it might be the problem with the values you enter. Maybe you would want to debug and check what values are being passed from UI – Dhruv Singhal Jul 04 '18 at 17:20
  • 1
    So, one of the parameters is null. Can't you really find which one? And find out why? What does your form submit? – JB Nizet Jul 04 '18 at 17:22
  • I passed Integer values in those fields. – Ritik Agrawal Jul 04 '18 at 17:22
  • 1
    Do you have a field for num1 and a field for num2 in your form? Why is num1 not null, and num2 null? Read your HTML source carefully. – JB Nizet Jul 04 '18 at 17:23
  • Thank you all!!!! – Ritik Agrawal Jul 04 '18 at 17:31
  • But i wanna know why it was giving HTTP status 405? get method is not supported – Ritik Agrawal Jul 04 '18 at 17:33
  • We can't tell you that since you didn't post the code causing the error. My guess is that you implemented doGet(), but the default method when submitting a form is POST, not GET. Unless of course you specify `method="get"` on the form. – JB Nizet Jul 04 '18 at 17:35

5 Answers5

1

You get a NumberFormatException because Integer.parseInt(String) throws it if the String argument can't be converted to an integer. See the documentation.

You need to wrap the integer parsing in a try-catch and handle the exception if you don't want it to be thrown, OR check ahead of time that the String supplied is really an integer.

Also take a good look at your form. You have

    <form action="add">
        Enter 1st number: <input type="text"  name=num1><br>
        Enter 2nd number: <input type="text"  name=num1><br>
        <input type="submit">
    </form>

This has num1 twice, which will give you null when you try to get the parameter for num2 in your req.

Change it to

    <form action="add">
        Enter 1st number: <input type="text"  name="num1"><br>
        Enter 2nd number: <input type="text"  name="num2"><br>
        <input type="submit">
    </form>

For example:

String num1 = req.getParameter("num1");
String num2 = req.getParameter("num2");

try {
    int i = Integer.parseInt(num1);
    int j = Integer.parseInt(num2);

    int k = i + j;
    // TODO do something with k
} catch (NumberFormatException e) {
    // log exception and / or notify user
    System.out.println("At least one invalid number in the given numbers: " + num1 + ", " + num2);
    e.printStackTrace();
    // show an error message to the user somewhere in your frontend
    req.setAttribute("error", "your error message");
}

EDIT

As pointed out in the comments, I've chosen to catch the unchecked exception NumberFormatException, log it and set an attribute in the request to show the user a meaningful error message.

I did this because by letting the unchecked exception bubble up in the event that at least one of the numbers entered is not parsable to an integer value, it would have to be dealt with further up the chain in order to display something meaningful to the user and not a generic internal server error message.

An alternative to using the logic described above would be using regex to validate the input for each of the integers.

Another validation consideration that was not touched upon here is the possibility of an overflow. This can happen in two cases:

  1. The user enters an integer that is larger than Integer.MAX_VALUE.
  2. The user enters two integers whose sum is larger than Integer.MAX_VALUE.

In the first case, for example

System.out.println(Integer.parseInt("" + (Integer.MAX_VALUE + 1)));

will print -2147483648

And in the second case

int a = Integer.parseInt("" + (Integer.MAX_VALUE));
int b = Integer.parseInt("" + (Integer.MAX_VALUE));

System.out.println(a + b);

will print -2. In both cases the result should clearly be positive.

geco17
  • 5,152
  • 3
  • 21
  • 38
  • I believe that's not what the question is demanding... by handling this particular exception in this case will not help in finding what went wrong while sending data to server. – Dhruv Singhal Jul 04 '18 at 17:28
  • @RitikAgrawal Please give it a try and let me know how it goes. I've included some sample code. If you feel the answer was sufficient, consider marking it as accepted. – geco17 Jul 04 '18 at 17:36
  • _You need to wrap the integer parsing in a try-catch and handle the exception_ No, unchecked exceptions should not be handled in try-catch block. – Dhruv Singhal Jul 04 '18 at 17:40
  • @DhruvSinghal Thanks for your comment. I would argue that in this particular case it is better to handle a possible unchecked exception, for the sake of simplicity. What would you have suggested instead of catching the exception? – geco17 Jul 04 '18 at 18:02
  • As I said, we should not handle it. Just consider one thing. What if you handled the exception (in the first place you would not have known there is an exception without the data), returned success from catch block (just to make sure server does not crash), but still don't get the desired result? I guess in that case it would have been much difficult to track the issue without knowing that values you passed are ACTUALLY invalid. – Dhruv Singhal Jul 04 '18 at 18:10
  • Just look at it in this way... getting NullPointerException/NumberFormatException/any other unchecked exception allowed you to realise that you gave incorrect data to process – Dhruv Singhal Jul 04 '18 at 18:12
  • @Dhruv: how this answer shows exception handling is ok. Letting the exception be thrown outside of the servlet so the container logs it and shows an error page isn’t ideal either. – Nathan Hughes Jul 04 '18 at 20:13
  • @Nathan so you are suggesting it IS ok to handle NumberFormatException inside try/catch block? Purpose of my saying so is that if you really want to get rid of these types of exception, maybe applying validations will do better than enclosing the code in try/catch. I am emphasizing this because there are many problems related to this type of practise, that can lead to even more confusion. – Dhruv Singhal Jul 05 '18 at 01:53
  • @Dhruv: I agree validation is a better alternative. But this is such a crappy little toy example I don’t think it’s worth getting too worked up about. My own pet peeve here is where the code doesn’t distinguish between GET and POST. – Nathan Hughes Jul 05 '18 at 02:41
  • Cool no problem... just wanted to encourage the use of validation rather than try/catch blocks. Anyway no problem as long as the desired functionality is being achieved. – Dhruv Singhal Jul 05 '18 at 03:24
1

It seems you are parsing the request parameter "num2" but in your html, your input is only "num1" duplicated.

So in the servlet, you are requesting parameter "num2" which does not exists, giving a null value, giving you the Exception java.lang.NumberFormatException: null.

First you need to correct your HTML inputs, and is encouraged to use a try-catch block to parse those input values in the servlet (to handle different cases: null values, non numeric, float values, etc).

Yorsh
  • 50
  • 6
  • handling numberFormatException might lead to 200 server response, further making it difficult to find out the mistake. Only checked exceptions should be handled, unchecked exceptions should not be handled. – Dhruv Singhal Jul 04 '18 at 17:32
0

Try to add three or four numbers instead of just two. I think it will help you understand what went wrong.

kumesana
  • 2,495
  • 1
  • 9
  • 10
0

As already pointed out by most of the answers, the problem was with the form itself.

But having looked at all the answers, one thing has been encouraged by most of them - handling the unchecked exception in try/catch block (in this case, java.lang.NumberFormatException).

Please pay attention! Unchecked Exceptions are NEVER meant to be handled inside try/catch block (even if you want to get rid of exception). You need to realise that the idea of handling unchecked exception arouse ONLY after getting incorrect data. AND it can lead to normal functioning of server, returning you the incorrect result and making it much difficult to track the mistake.

And without the data, it is impossible to even guess the exception that might occur. So please don't encourage handling of unchecked exception in try/catch block. If you really want to handle the unchecked exceptions, do it by using validations (e.g. conditions). That way you will ensure that the data will pass certain condition according to your requirement, and you can check if invalid input is there.

Note: It is even more disastrous to throw such exceptions.

Dhruv Singhal
  • 145
  • 2
  • 17
0

You should run the application from the html page and not from the servlets. I have faced the similar problem when I am using Run button from the Servlet file. When you are on html page just right click and then choose Run-> Run on Servel. This is how I resolved this error.

user11908262
  • 143
  • 3
  • 11