如何从一个servlet传递一个字符串值到另一个servlet?

4
我有一个jsp页面,通过'request.getParameter'在servlet1中获取了一个字符串值,我想要链接servlet1和servlet2,并将我在servlet1中获取的字符串值发送到servlet2。
请帮忙。
提前感谢您。

将其保留在会话中,然后使用session.getAttribute()检索它。 - SpringLearner
你能重定向到servlet2吗?请在这里分享重定向代码。 - user2575725
谢谢朋友们,它正在运行。 - mujib009
3个回答

9

您需要设置请求属性。

在您的servlet1中实现。

request.setAttribute("attributeName",yourStringVAlue);
RequestDispatcher rd = request.getRequestDispatcher("yourServletPattern");
rd.forward(request,response);

在你的Servlet2中
String someName = (String)request.getAttribute("attributeName");

RequestDispatcher rd = request.getRequestDispatcher("yourServletPattern"); 这里的 "yourServletPattern" 是指你的 Servlet2 名称吗?如何设置? - mujib009
yourServletPattern是您在web.xml中配置的servlet模式。 您的servlet需要在web.xml中进行配置。 如需更多信息,请参阅此教程。 http://www.thejavageek.com/2013/08/11/mvc-architecture-with-servlets-and-jsp/ - Prasad Kharkar

2

在Servlet 1中:

request.setAttribute("myAwesomeAttributeName",myAwesomeAttributeValue);

然后通过servlet 2接收它:

request.getAttribute("myAwesomeAttributeName");

-1
你可以使用 ServletContext 在你的 Servlet 1 中使用 setAttribute
ServletContext servletcontext = getServletContext();
servletcontext.setAttribute("Email", email);

在你的servlet中使用getAttribute
ServletContext servletcontext = getServletContext();
String ReferMail = (String)sc.getAttribute("Email");

2
不好的建议。只有在网络应用程序同时仅由一个用户使用时才能正常工作。 - BalusC
我在本地服务器上学习这些知识。当我直接使用setAttribute和getAttribute时,值会以null的形式插入到我的数据库(MySQL)中。这就是为什么我使用servletContext的原因。感谢您的回复。 - Peace_M1ker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接