首页 > 解决方案 > 将 ServletContext 属性的内容保存在 int 变量中

问题描述

在第一个 JSP 中,我创建了一个 servletcontext,在其中放置了一个具有 num 值的 Count 属性,在第二个 JSP simple 中,我从该上下文中获取了 Count 值,但它给了我错误。如何将 servletcontext 类型的对象保存在数组中?

jsp1:
<%!int num=0;%>
<%ServletContext cont = getServletConfig().getServletContext();
  num++;
  cont.setAttribute("Conta",num);
%>

jsp2:
<% ServletContext cont = getServletConfig().getServletContext();
   int contator=Integer.parseInt(cont.getAttribute("Conta"));
%>

标签: javajspservletsint

解决方案


Hard to say without the error, but I think I may have found it.

You are hitting an error when Integer.parseInt(String) receives an int/Integer, which is throwing most likely a method not found error. In this case [void setAttribute(String, Object)] will take the integer you are passing it and [Object getAttribute(String)] will return the integer. Integer.parseInt(String) will then fail.

If you refactor to not do the Integer.parseInt() and just cast the result to the int, you should be OK.


推荐阅读