0

我是初学者。我知道这是基本的。在我的项目中,我使用的是 Java 和 MySQL 工作台。我正在使用选择框从用户那里读取数据,该选择框来自使用 ajax 的数据库。选择框的代码如下

<%
 String a =request.getParameter("course");
 if(a!=null)
   {
       ResultSet rs=s.selectsub(a);
       String Query="select * from  subject where course_id='"+a+"'";
 %>
 <select name="subject" id="subject">
   <option>Select Subject</option>
   <%
    while(rs.next())
    {
    %>
    <option value="<% out.println(rs.getString("subject_id")); %>">
    <% out.println(rs.getString("subject")); %></option>
   <% } %>
  </select>
<%
}
%>

并使用 post 方法将主题 ID 传递到另一个页面并尝试此代码

     String subject=request.getParameter("subject");
     int subjectid=Integer.parseInt(subject);

但是行整数转换不起作用。显示错误。错误是

org.apache.jasper.JasperException: An exception occurred processing JSP page /saveuser.jsp at line 29
26:          String email=request.getParameter("email");
27:          String designation=request.getParameter("designation");
28:          String subject=request.getParameter("subject");
29:          int subjectid=Integer.parseInt(subject);
30:          String institute=request.getParameter("institute");
31:          String inemail=request.getParameter("inemail");
32:          String uname=request.getParameter("uname");
4

3 回答 3

4

Integer.parseInt方法会将有效的整数值字符串转换为 int。否则会抛出异常。因此,请确保将有效的整数值传递给它。有时字符串中的尾随空格会导致异常。所以在输入字符串上调用 trim 方法来避免这种情况:

 int subjectid=Integer.parseInt(subject.trim());

还要确保主题不为空。所以这似乎更好:

 String subject=request.getParameter("subject");
 int subjectid = 0;
 if(subject !=null && !subject.isEmpty())
     subjectid=Integer.parseInt(subject.trim());
于 2013-08-27T06:57:04.740 回答
1

看起来您正在混合数据类型,试图转换getParameter("subject")为整数。

也许您有一个名为 的参数"subject_id",这可以工作吗?

 String subject_id_string=request.getParameter("subject_id");
 int subjectid=Integer.parseInt(subject_id_string);
于 2013-08-27T07:00:47.707 回答
1

使用Integer.parseInt(String)方法。

int subjectid = Integer.parseInt(subject.trim());

从文档

将字符串参数解析为有符号十进制整数。字符串中的字符必须都是十进制数字,除了第一个字符可以是ASCII减号'-'('\u002D')表示负值或ASCII加号'+'('\u002B')表示正值。返回结果整数值,就像参数和基数 10 作为参数提供给 parseInt(java.lang.String, int) 方法一样。

于 2013-08-27T07:02:04.127 回答