我得到的错误是:HTTP状态500 -内部服务器错误类型异常报告
我正在学习一个教程,并按照指导者的话去做。
我得到的错误是:无法分析空字符串服务器遇到意外情况,无法完成请求。java.lang.NumberFormatException:无法分析空字符串
Servlet1.java
package com.servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/servlet1")
public class Servlet1 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
int number1=Integer.parseInt(req.getParameter("num1"));
int number2=Integer.parseInt(req.getParameter("num2"));
int sum=number1+number2;
req.setAttribute("s", sum);
RequestDispatcher rd=req.getRequestDispatcher("/servlet2");
rd.forward(req, resp);
}
}
字符串
Servlet2.java
package com.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/servlet2")
public class Servlet2 extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
int number1=Integer.parseInt(req.getParameter("num1"));
int number2=Integer.parseInt(req.getParameter("num2"));
resp.setContentType("index/html");
int product=number1*number2;
int sum=(int) req.getAttribute("s");
PrintWriter out=resp.getWriter();
}
}
型
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>This is the Form</h1>
<br>
<br>
<form action="servlet1" method="post">
<label>Enter the first number:</label>
<input type="text" name"num1"/>
<label>Enter the second number:</label>
<input type="text" name"num2"/>
<button type="submit">Submit</button>
</form>
</body>
</html>
型
1条答案
按热度按时间svdrlsy41#
servlet中的这种解析逻辑是不安全的:
字符串
如果参数是
null
或不是数字,Java将无法从参数中解析int
。在您的特定情况下,其中一个参数是null
。但通常情况下,由于它是用户输入,您需要验证参数num1
和num2
是否可以解析,或者您需要捕获异常并处理它(显示有意义的错误,如“请输入正确的数据”等)。你可以检查这个question,你会得到的想法。此外,HTML中还有一个错误,缺少
=
,因此您的输入没有名称,这里您已经失去了参数,它们将无法正确到达servlet。代码应该看起来像这样:型