我有一个技术问题,我不确定正确的解决方法:
在我正在开发的网页中,我必须存储会话中的当前用户名(登录的人)以“标记”一个动作。(例如,“用户在“上创建了这个文件”)。我的算法从会话中检索用户名,但显然每个用户都会改变。因此,始终是登录用户之一,而不是创建者姓名。
任何提示任何人?
谢谢!
我有一个技术问题,我不确定正确的解决方法:
在我正在开发的网页中,我必须存储会话中的当前用户名(登录的人)以“标记”一个动作。(例如,“用户在“上创建了这个文件”)。我的算法从会话中检索用户名,但显然每个用户都会改变。因此,始终是登录用户之一,而不是创建者姓名。
任何提示任何人?
谢谢!
那么从逻辑上讲,这些是您想要的步骤吗?
我认为您可能缺少系统存储内容的部分(例如在数据库中)。
编辑:如果您不需要持久性,您可以将共享数据存储在 ServletContext 中。请注意,这不是一个严肃的解决方案,但可以用于快速原型或演示。甚至不要考虑在生产中这样做,它有问题。
在您的 servlet 中执行以下操作:
private static Map<String, FileData> fileAccess;
private class FileData {
String userName;
Date timeStamp = new Date();;
String fileName;
FileData(String userName, String fileName) {
this.userName = userName;
this.fileName= fileName;
}
}
public void init(ServletConfig config) {
String attributeKey = "fileAccess";
fileAccess = config.getServletContext().getAttribute(attributeKey);
if (fileAccess == null) {
fileAccess = new HashMap<String, FileData>();
config.getServletContext().setAttribute(attributeKey, fileAccess);
}
}
// in this example a POST means a user accesses a file
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
// get the user name from the current session
String userName = req.getSession().getAttribute("userName");
// get the file name from the request (posted from the file access form)
String fileName = req.getParameter("fileName");
// check if we have the necessary data
if (userName == null || fileName == null) {
resp.getWriter().write("Invalid file access request");
resp.getWriter().flush();
return;
}
// create and fill file data wrapper
FileData fileData = new FileData(userName, fileName);
// store the file data in the shared fileAccess map.
// synchronized to block simultaneous acccess from different threads
synchronized (fileAccess) {
// note: any previously stored FileData object gets replaced
fileAccess.put(fileName, fileData);
}
// display the result to the user
display(fileData, resp);
}
// in this example a GET means a user views a file
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
// get the file name parameter from the request (sent as part of the view-file request)
String fileName = req.getParameter("fileName");
// check if we have the necessary data
if (fileName == null) {
resp.getWriter().write("Invalid view file request.");
resp.getWriter().flush();
return;
}
// get the file data from the shared fileAccess map.
// synchronized to block simultaneous acccess from different threads
synchronized (fileAccess) {
FileData fileData = fileAccess.get(fileName);
// display the result to the user
display(fileData, resp);
}
}
private void display(FileData fileData, HttpServletResponse resp) {
resp.getWriter().write("File accessed:");
resp.getWriter().write("User: " + fileData.userName);
resp.getWriter().write("File: " + fileData.fileName);
resp.getWriter().write("Timestamp: " + fileData.timeStamp);
resp.getWriter().flush();
}