程序报错java.lang.NumberFormatException: null

程序报错java.lang.NumberFormatException: null

SumServlet.java:

package com.imoc.servleet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/sum")
public class SumServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String num=request.getParameter("num");
int number=Integer.parseInt(num);
if(number<100){
int sum=0;
for(int i=0;i<=number;i++){
sum+=i;
}
request.setAttribute("sum",num);
request.getRequestDispatcher("/result").forward(request,response);
}else {
response.getWriter().println("<h1>数字超出范围</h1>");
}
}
}

ResultServlet.java:

package com.imoc.servleet;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/result")
public class Result extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sum=(String)request.getAttribute("sum");
response.getWriter().println("<h1>"+sum+"</h1>");
}
}

sum.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/sum" method="get">
<input type="text" name="num" placeholder="请输入100以内的数字"><button type="submit" value="求累加和"></button>
</form>
</body>
</html>

报错:

​java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at com.imoc.servleet.SumServlet.doGet(SumServlet.java:16)


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕小小 2021-10-14 10:25:30

同学你好,代码经过测试未出现上述的异常,建议同学重启启动后在文本框中输入正确的整数后再测试运行试一下。

另外代码中还存在如下问题:

1、按钮没有文字显示,如下图所示。因按钮使用的是button标签建议在标签中输入文本内容。https://img1.sycdn.imooc.com//climg/616790eb09b9d90803150057.jpg

2、向request对象中设置属性sum时,建议将num修改为sum。

3、当输入数字超出范围时,页面可能会出现乱码,建议设置下响应的编码格式。

4、发送请求给/result时会出现类型转换异常,可将获取到的数据直接响应。

https://img1.sycdn.imooc.com//climg/6167937e09dfaa1c09650105.jpg

参考代码如下:

sum.html:

https://img1.sycdn.imooc.com//climg/61679123096c2e7507000100.jpg

SumServlet.java:

https://img1.sycdn.imooc.com//climg/616794920958ccde07510314.jpg

ResultServlet.java:

https://img1.sycdn.imooc.com//climg/616794a5098558c508660172.jpg

祝学习愉快~

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师