我需要能够将对象中的值与int进行比较,但似乎无法使类型转换工作。我已经尝试了这里描述的所有方法:Session attribute access and converting to int?但它们都给我一个空指针异常。这是我没有工作的代码。如何将类型对象转换为jsp中的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'。 – cHao
如果'session'为'null',这段代码将抛出'NullPointerException'。如果'session.getAttribute(“test”)'返回null,那么带'parseInt'的版本将抛出相同的异常。你确定你已经调用'session.setAttribute(“test”,someInteger)'? –
如果你确定这个字符串只包含digist,那你为什么不用'Integer.parseInteger()' – NewUser