2015-08-22 46 views
0
import javax.servlet.GenericServlet; 
import javax.servlet.ServletResponse;`enter code here` 
import javax.servlet.ServletRequest; 
import javax.servlet.ServletException; 
import java.io.IOException; 
import java.lang.Exception; 
import java.io.PrintWriter; 
public class SumServlet extends GenericServlet 
{ 
    public void service(ServletRequest request,ServletResponse response)throws ServletException,IOException 
    { 

      String str1=request.getParameter("fname"); 
      String str2=request.getParameter(" sname"); 
      int num1=Integer.parseInt(str1); 
      int num2=Integer.parseInt(str2); 
      int sum=num1+num2; 
      PrintWriter out=response.getWriter(); 
      out.println("Given fnumber is "+str1); 
      out.println(" --------------"); 
      out.println("Given second number is"+str2); 
      out.println(" --------------"); 
      out.println("Sum of numbers is "+sum); 
    } 
} 



/*There is an exception arises with this program as http status 500:null. 
    java.lang.NumberFormatException: null 
     java.lang.Integer.parseInt(Unknown Source) 
     java.lang.Integer.parseInt(Unknown Source) 
     SumServlet.service(SumServlet.java:17) 
     org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52). 

當該程序是通過使用查詢passig值Tomcat服務器上運行作爲例外得到上述消息string..at上述casues的哪一行此例。給溶液來克服此異常。 。*/例外在servletsum程序

回答

0

致命小白代碼

public void service(ServletRequest request,ServletResponse response)throws ServletException,IOException 
    { 
      String str1=request.getParameter("fname"); 
      String str2=request.getParameter("sname");// " sname" is not "sname" 
      boolean err=true; 
      try{//try to convert String to int 
      int num1=Integer.parseInt(str1); 
      int num2=Integer.parseInt(str2);err=false; 
      }catch(Exception ex){} 
      if(err){out.println("Invalid number format provided");} 
      else{int sum=num1+num2; 
      PrintWriter out=response.getWriter(); 
      out.println("Given fnumber is "+str1); 
      out.println(" --------------"); 
      out.println("Given second number is"+str2); 
      out.println(" --------------"); 
      out.println("Sum of numbers is "+sum); 
      } 
    }