【问题标题】:How to pass an integer value from one jsp page to other jsp page?如何将整数值从一个jsp页面传递到另一个jsp页面?
【发布时间】:2019-07-15 10:05:42
【问题描述】:

我有两个文件 abc.jsp 和 def.jsp。在 abc.jsp 中,它包含以下代码:

<%
        String selectedCourse = request.getParameter("course");
        int count = 0;

        if(selectedCourse.equals("PHP")){
            count = count + 1;
        }

    %> 

我想要 def.jsp 中的这个计数值,那么我该如何传递这个值呢?

【问题讨论】:

  • 我要传整数,我可以传字符串,但不能传整数!
  • 完全一样,只是使用Integer而不是int(即对象,而不是原始类型)。
  • 我不明白:/你能用这段代码解释一下吗?
  • 每次访问abc.jsp 页面时,都会将计数初始化为0,因此它之前的值会丢失。尝试将count 存储在session 中并从中检索计数session 然后用 1 添加它,还有 count 已经在会话中,您可以在任何页面中获取它,即通过编写 int count = session.getAttribute("count");

标签: java jsp


【解决方案1】:

abc.jsp

<%!
private synchronized void incrementCounter() {
  Integer count = session.getAttribute("count");
  if (count == null) {
    count = new Integer(0);
  }
  count++;
  session.setAttribute("count", new Integer(count));
}
%>

<%
String selectedCourse = request.getParameter("course");
if(selectedCourse.equals("PHP")){
  incrementCounter();
}
%> 

def.jsp

<%
int count = session.getAttribute("count"); 
%>

反正这样的逻辑不应该在JSP中,而是属于一个控制器(servlet)。

【讨论】:

    【解决方案2】:

    使用会话属性

    abc.jsp

    <%
        String selectedCourse = request.getParameter("course");
        int count = 0;
    
        if(selectedCourse.equals("PHP")){
            count = count + 1;
        }
         session.setAttribute("count", count);
    %> 
    

    def.jsp

    int count1 = Integer.parseInt(session.getAttribute("count").toString());
    
    out.write("count:"+count1);
    

    【讨论】:

    • 不工作,总是获取计数 0 的初始化值!
    • int count1 = Integer.parseInt(session.getAttribute("count").toString()); out.write("count:"+count1);
    • int count1 = Integer.parseInt(session.getAttribute("count").toString());不工作,运行后捕获 nullPointerException!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多