我正在做一些测试,我想使用 java servlet session 来记住用户已经看过的图像,并且只打印出用户还没有看过的图像的图像名称。例如,如果 Images=2,我应该只显示 img1.png、img2.png,如果 Images=3,它应该只显示 img3.png,因为名称 img1.png、img2.png 已经显示。我的代码工作,但我不确定如何设置会话,以便我按预期工作。
http://localhost:8080/XXXX/test?Images=3
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;
public class ImageServlet extends HttpServlet {
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
File imagePath=new File(getServletContext().getRealPath("/images"));
File[] imageFiles=imagePath.listFiles();
String Imagesname=req.getParameter("Images");//geting Images from index.html
int result = Integer.parseInt(Imagesname);
for (int i = 0; i < result; i++) {
if(session.isNew()){
out.print(imageFiles[i].getName());
}else{
out.print("welcome back");
}
}
}
}