jsp开发中页面数据共享技术
Jsp中共享数据有两种情况:一是同一用户的不同页面之间共享数据;二是不同用户之间共享数据;
共享数据的方法有:(不同用户之间共享数据只能通过后面三种方法)
(1)把数据放在session中;(可以再整个回话过程传递)
(2)通过Cookie(Cookie是放在客户端的,考虑安全因素,使用比较少);
(3)通过隐藏表单把数据传递到下一页面(只能在相邻两个页面之间传递,安全性低);
(4)通过ServletContext对象;
(5)通过application对象;
(6)通过系统文件或数据库;
1、用session共享数据:
保存数据:
session.setAttribute(String,Object)——session只能保存对象,不能保存原生类型,如:
正确:session.setAttribute("count",new Integer(10));
错误:session.setAttribute("count",10);
读取数据:
session.getAttribute("count");
2、使用隐含表单
如:
保存数据:
<form action="next.jsp">
<input type="hidden" name="test" value="myvalue">
</form>
获取数据:
String test = request.getParameter("test");
3、使用ServletContext
首先通过getServletContext获取ServletContext对象;如:
<% String context = (String)getServletContext().getAttribute(new String("myvalue")); getServletContext().setAttribute("myvalue",context+(String)request.getParameter("context")+); %>