How do I send data between servlets?

送分小仙女□ 提交于 2021-02-08 08:20:53

问题


I am pretty new to servlets and web development in general.

So basically I have a servlet that queries a database and returns some values, like a name. What I want is to turn the name into a link that opens a details page for that name (which another servlet would handle). How can I send the name to the other servlet so it can query a database for the relevant details?

Maybe I'm taking the wrong approach?

Edit: I am using Tomcat 5.5


回答1:


Pass it as request parameter.

Either add it to the query string of the URL of the link to the other servlet which is then available by request.getParameter("name") in the doGet() method.

<a href="otherservlet?name=${name}">link</a>

Or add it as a hidden input field in a POST form which submits to the other servlet which is then available by request.getParameter("name") in the doPost() method.

<form action="otherservlet" method="post">
    <input type="hidden" name="name" value="${name}" />
    <input type="submit" />
</form>

See also:

  • Servlets info page - contains a Hello World



回答2:


Not sure if I understand correctly, but you may look at javax.servlet.RequestDispatcher and forward the url to the second servlet. The url could be created using the name:

http://myhost.mydomain/my.context/servlet2.do?name=John



回答3:


I would create the URL either in the first servlet or in a client using a configurable template for the URL. This way both servlets are clearly separated - you can even have each one on different machine.



来源:https://stackoverflow.com/questions/5364354/how-do-i-send-data-between-servlets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!