繁体   English   中英

有没有其他方法可以在jsp中将字符串值转换为整数值? 我正在尝试一个基本的jsp程序

[英]Is there any other way to convert string value into integer value in jsp? I am trying a basic program in jsp

索引.html

<html>
<head>
<title>AddModule | Home page</title>
<link rel="stylesheet" 
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
crossorigin="anonymous">
</head>
<body>
<div class="container">
   <div class="row">
   <div class="col-md-6 offset-md-3">
   <form action="op.jsp">
   <div class="card">
   <div class="card-header bg-dark text-white">
   <h3>Provide me a number</h3>
   </div>
   <div class="card-body">
   <div class="form-group">
   <input name="n1" type="number" class="form-control" placeholder="Enter n1">
   </div>
   <div class=form-group>
   <input name="n2" type="number" class="form-control" placeholder="Enter n2">
   </div>
   </div>
    <div class="card-footer text-center">
    <button type="submit" class="btn btn-primary">Divide</button>
   </div>
   
   </div>
   </div>
   </form>
   </div>
   </div>
   </body>
   </html>

在名为 java.lang.NumberFormatException 的 op.jsp 中获取异常

HTTP 状态 500 - 内部服务器错误

op.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Jsp Page</title>
</head>
<body>
<%
String n1= request.getParameter("n1");
String n2= request.getParameter("n2");
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
int c=a/b;
%>
<h3>Result is <%=c %></h3>
</body>
</html>

将值从字符串转换为整数时会产生异常

也试过下面的代码,但仍然无法正常工作

<%int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n1"));
int c=n1/n2 %>
<%
String n1 = request.getParameter("n1");
String n2 = request.getParameter("n2");
int n1Val,n2Val;
if(n1 != null){
n1Val=Integer.parseInt(n1);
}
if(n2!=null){
n2Val=Integer.parseInt(n2);
}int c;
if(n1 != null && n2!=null)c=n1Val + n2val;
%>

问题不在于您的代码,而在于您如何运行它。

您需要先访问index.html以允许您输入数字,然后点击Divide 这将使用n1n2作为参数调用op.jsp

如果您尝试直接访问op.jsp ,您的代码将在没有n1n2值的情况下运行。 如果您没有输入,那么尝试将输入解析为整数显然会失败。

如果要简化测试,可以使用op.jsp?n1=42&n2=7在 URL 中手动指定 HTTP GET 查询参数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM