【问题标题】:How to typecast object to int in jsp如何在jsp中将对象类型转换为int
【发布时间】:2013-11-21 05:15:07
【问题描述】:

我需要能够将对象中的值与 int 进行比较,但我似乎无法让类型转换工作。我已经尝试了这里描述的所有方法:Session attribute access and converting to int? 但它们都给了我一个空指针异常。这是我的代码不起作用。

这是将值放入会话的代码。

<script>sessionStorage.clickcount=1;</script>
<input type ="hidden" name="ttmp" value="222" id="ttmp" />
<script>document.getElementById('ttmp').value = sessionStorage.clickcount;</script>

在脚本之前和之后的输入行中尝试过。

<%
  String value = request.getParameter("ttmp");
  if (value != null) {
    session.setAttribute("test", value);
  }
  Integer userid = Integer.parseInt(session.getAttribute("test").toString());
  ...
  if (userid == 1) {
  ...
  }
%>

【问题讨论】:

  • 字符串不是整数,因此将字符串转换为整数没有意义。如果您想将字符串转换为数字,请查看Integer.parseInt
  • 如果sessionnull,此代码将抛出NullPointerException。如果session.getAttribute("test") 返回null,带有parseInt 的版本将抛出相同的异常。你确定你打电话给session.setAttribute("test", someInteger)
  • 如果你确定字符串只包含 digist 那么你为什么不使用Integer.parseInteger()
  • 我已经尝试过了,但它给了我一个不同的错误。

标签: java jsp


【解决方案1】:

试试这个Integer.parseInt((String)session.getAttribute("test"))

<%
  String value = request.getParameter("ttmp");
  if (value != null) {
    session.setAttribute("test", value);
  }
  Integer userid = Integer.parseInt((String)session.getAttribute("test"));
  ...
  if (userid == 1) {
  ...
  }
%>

【讨论】:

  • 这给了我这个错误:PWC6199: Generated servlet error: no suitable method found for parseInt(java.lang.Object) method java.lang.Integer.parseInt(java.lang.String) is not适用(实际参数 java.lang.Object 无法通过方法调用转换转换为 java.lang.String)方法 java.lang.Integer.parseInt(java.lang.String,int) 不适用(实际和形式参数列表不同长度)
  • @user2532973 将其转换为字符串然后转换,检查我更新的答案
  • 现在我得到一个不同的错误:java.lang.NumberFormatException: null
  • @user2532973 你确定 session.getAttribute("test") 不为 null。我认为 session.getAttribute("test")return null.check it
  • 我将 ttmp 的值设置为 2,但仍然出现 Null 错误
【解决方案2】:

现在就试试吧。

<%
String value = request.getParameter("ttmp");
if (value != null) {
session.setAttribute("test", value);
}
int userid=0;
if ((session.getAttribute("test") != null) && (session.getAttribute("test") != "")) 
{
    userid = Integer.parseInt(session.getAttribute("test").toString());
}
%>

【讨论】:

  • 字符串值 = request.getParameter("ttmp"); value 变量应该包含一些以后可以转换为整数的数字。
  • 我将 ttmp 的值设置为 2,但仍然出现 Null 错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 2019-06-24
  • 1970-01-01
  • 2016-03-12
  • 2015-02-12
  • 1970-01-01
相关资源
最近更新 更多