在servlet之间传输值(Transmit value between servlets)

我写了一个html表单来检索用户的密码和用户名:

<form action="prueba-registro" method=get enctype=multipart/form-data> <h3> User information </h3> User name: <INPUT TYPE=TEXT NAME="realname"><BR> Password: <INPUT TYPE=PASSWORD NAME="mypassword"> <P><INPUT TYPE=SUBMIT VALUE="Register"> </form>

此信息在servlet(checkRegistration)中接收,该servlet检查此信息是否有效。 如果一切正常,servlet“checkRegistration”将调用另一个servlet:uploadFile

在servlet uploadFile中,允许用户将文件上载到服务器。 为了将信息存储在数据库中,我需要知道用户的名字。

我怎样才能将有关用户名的信息(在servler checkRegistration中可用)传递给servlet uploadFile?

谢谢

I've written a html form to retrieve password and user name from users:

<form action="prueba-registro" method=get enctype=multipart/form-data> <h3> User information </h3> User name: <INPUT TYPE=TEXT NAME="realname"><BR> Password: <INPUT TYPE=PASSWORD NAME="mypassword"> <P><INPUT TYPE=SUBMIT VALUE="Register"> </form>

This information is received in a servlet (checkRegistration) that checks if this information is valid. If everything is ok the servlet "checkRegistration" will call another servlet: uploadFile

In the servlet uploadFile the user is allowed to upload files to the server. In order to store the information in a database I need to know the name of the user.

How could I pass the information about the user name (whichi is available in the servler checkRegistration) to the servlet uploadFile?

Thanks

最满意答案

最常见的方法是将用户信息作为属性保存到其会话中。 您可以从请求访问会话:

HttpSession session = request.getSession();

相同的会话与用户发出的每个请求相关联。 会话具有一个属性映射,允许您获取和设置值。 例如,如果CheckRegistrationServlet发现登录成功,它可以执行以下操作:

request.getSession().setAttribute("LoggedIn", "true");

然后在UploadFileServlet中,在允许上传之前检查此属性:

if ("true".equals(request.getSession().getAttribute("LoggedIn")) { // perform file upload } else { // deny file upload }

当然,不是为“LoggedIn”属性保存“true”值,而是保存表示用户会话信息的对象。 您可以构建一个保存用户名的UserSession对象,并保存该对象而不是“true”字符串。

The most common way to do this is to save the user information to their session as an attribute. You can access the session from the request:

HttpSession session = request.getSession();

The same session is associated with every request that the user makes. The session has an attribute map that allows you to get and set values. For example, if CheckRegistrationServlet finds that the login is successful, it can do something like this:

request.getSession().setAttribute("LoggedIn", "true");

Then in the UploadFileServlet, check for this attribute before allowing the upload to take place:

if ("true".equals(request.getSession().getAttribute("LoggedIn")) { // perform file upload } else { // deny file upload }

Of course, instead of saving a "true" value for the "LoggedIn" attribute, it's common to save an object that represents the user's session information. You could build a UserSession object that holds the username, and save that instead of the "true" String.

更多推荐