request.setAttribute()与request.getAttribute()取值问题

在项目的创建的过程中,我曾经想要从系统中得到一个参数,并让这个参数能够在web组件中传递使用。

以下为使用方式:

Timestamp voteTime = (Timestamp) request.getAttribute("voteTime");
		if(voteTime==null||(nowTime.compareTo(voteTime))>1){
			if(voteTime!=null)
				System.out.println("上次投票时间"+(request.getAttribute("voteTime"));
			else {
				System.out.println("voteTime==null");
			}
			request.setAttribute("voteTime", nowTime);
			System.out.println("成功投票,跳转投票处理页面"+nowTime);
			dispatcher = servletContext.getRequestDispatcher("/voteView.jsp");
		}else{
			System.out.println("距上次投票时间未超过1分钟,跳转等候页面"+voteTime);
			dispatcher = servletContext.getRequestDispatcher("/timeLoding.jsp");
		}

代码描述:先获取名为"voteTime"的参数(不论它是否已被赋值),然后在判断中对其进行处理:未赋值就先给它赋值;已经赋值的,便得到旧数据,再赋予新数据

但是却遇到一个问题:

request.getAttribute("voteTime")
不论"voteTime"是否已被赋值,获得到的永远是null。

所以查找了一下资料才知道:

request对象既是jsp的内置对象,也是jsp的作用域之一。

此处遇到的错误原因跟request的作用域有关,request只在forward跳转的前后有关。在servlet_1中使用setAttribute,在其联系的1.jsp 里可以使用getAttribute来取到其值。但在servlet_2中就不行了,因为过期了。

若想让参数在整个项目过程中前后可用,应将参数存在会话里

所以此处应改为:

Timestamp voteTime = (Timestamp) request.getSession().getAttribute("voteTime");
request.getSession().setAttribute("voteTime", nowTime);




  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值