如何在jsp页面和servlet之间共享数据 [英] How do I share data between a jsp page and servlet

查看:169
本文介绍了如何在jsp页面和servlet之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个.jsp页面和几个servlet。

I have several .jsp pages and several servlets.

我需要将一些信息保存到会话变量中。在jsp页面中,我只是引用

I need to save some information to a session variable. In the jsp page I simply refer to

session.get...()

session.set...()

没有明确声明HttpSession对象。

Without explicitly declaring an HttpSession object.

但是在servlet中应用适当的编程规则并且我必须首先创建一个对象。

But in the servlet the proper rules of programming apply and I have to create an object first.

我关心的是我是否创建了这样的对象

My concern is if I create an object like this

HttpSession session = new HttpSession();

然后用这样的东西写信给它

and then write to it using something like this

session.setAttribute("files",fileList);

我担心的是我没有写入.jsp中引用的同一个会话对象文件。

my concern is that I am not writing to the same session object that was being referenced in the .jsp file.

我该怎么做才能在任何jsp或servlet中写入同一个对象。

What do I do so that I can write to the same object in any jsp or servlet.

推荐答案

您需要通过调用 HttpServletRequest.getSession()方法来获取HttpSession。

You need to obtain the HttpSession by calling the HttpServletRequest.getSession() method.

HttpServletRequest传入您的 doGet()方法。如果此请求尚未启用会话,则 getSession()将创建一个会话。如果会话已经到位并与此请求相关联,则getSession()将检索现有会话。如果使用此标准机制,那么您将自动在JSP和servlet之间共享相同的会话。

The HttpServletRequest is passed in to your doGet() method. If no session was already in place for this request, then getSession() will create one. If a session is already in place and associated with this request, then getSession() will retrieve the existing one instead. If you use this standard mechanism, then you will automatically share the same session between your JSPs and servlets.

你永远不应该试图直接构造HttpSession,因为它是由容器管理的。实际上,你不能通过调用 new HttpSesion()来创建一个新的,因为HttpSession只是一个接口,无法实例化。

You should never be trying to construct an HttpSession directly, as it is managed by the container. Indeed, you cannot create a new one by calling new HttpSesion() because HttpSession is merely an interface and cannot be instantiated.

这篇关于如何在jsp页面和servlet之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆