Form HTML + JSP

0

I have created a html page with a simple form and I want to use the infos in jsp

1) Java class "Calculation":

package principal;
public class Calculo {
    public int n1;
    public int n2;
    public int resultado;
}

2) form html

<form method="POST">
    soma<input type="radio" name="soma"> | subtracao <input type="radio" name="sub"><br>
    valor1:<input type="text" name="valor01"/><br>
    valor2:<input type="text" name="valor02"/><br>
    <input type="submit" value="calcular"/><br>
</form>

3) jsp (within html)

<%
    Calculo c1 = new Calculo();
    int valor1 = Integer.parseInt(request.getParameter("valor01"));
    int valor2 = Integer.parseInt(request.getParameter("valor02"));

    c1.n1 = valor1;
    c1.n2 = valor2;

    c1.resultado = valor1+valor2;
    out.print(c1.resultado);
%>

I'm using tomcat 7, the error is as follows, on line 21:

org.apache.jasper.JasperException: An exception occurred processing JSP page /teste.jsp at line 21

Line 21:

int valor1 = Integer.parseInt(request.getParameter("valor01"));

I've tried everything, and I still can not, can anyone help me? vlw

    
asked by anonymous 22.09.2017 / 16:51

1 answer

0

Is the JSP in the same file as this form right? The first time, you have no passed parameters, so it tries to convert null to integer, and causes the exception. You need to check if you have the values in the request before using them. Try this:

<%
if (request.getParameter("valor01") == null || request.getParameter("valor02") == null) {
  out.print("<p>Informe os valores</p>");
} else {
  Calculo c1 = new Calculo();
  int valor1 = Integer.parseInt(request.getParameter("valor01"));
  int valor2 = Integer.parseInt(request.getParameter("valor02"));

  c1.n1 = valor1;
  c1.n2 = valor2;

  c1.resultado = valor1+valor2;
  out.print(c1.resultado);
}
%>
    
22.09.2017 / 18:36