【发布时间】:2018-11-16 23:36:24
【问题描述】:
我正在尝试处理 Java 中的会话。每次有人进入新页面时,我都需要增加视图值,但每个用户每次会话只增加一次。目前下面的代码并没有这样做,它一直在增加它。我认为问题可能是每次加载页面时,arraylist 都会再次新建?我不确定如何处理这个问题。因为刷新后对象不会留在数组中。
处理会话并尝试增加计数的代码 // 获取图片的名字 session.setAttribute("pictureName", pictureName);
// create a list of objects that will store all the pages a user visits
ArrayList<String> listOfObjects = new ArrayList<String>();
// make a image_id variable but assign it the value of the page name
String image_id = (String) session.getAttribute("pictureName");
// go and compare each element in the list, to the id.
// This should NOT match on the first viewing since it's the first time the user
// visits the page
// this should then increment the view count
if (Utilities.isFirstVisit(listOfObjects, image_id) == true) {
Utilities.IncreaseCount(out, pictureName);
out.println("its worked");
} else {
// if a match is found then the user has already visited this page
// therefore don't increment the view count for the love of christ
out.println("A match was found");
}
调用的方法将对象添加或不添加到数组列表中
public static boolean isFirstVisit(ArrayList <String> listOfObjects,
String image_id) {
System.out.println(listOfObjects);
System.out.println(image_id);
if(listOfObjects.contains(image_id)) {
System.out.println("It does contain");
System.out.println(image_id);
return false;
}
else {
listOfObjects.add(image_id);
System.out.println("It does not contain");
System.out.println(image_id);
return true;
}
}
增加浏览量的方法
//Increase the access count on the picture
public static void IncreaseCount(PrintWriter out, String pictureName) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
} catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query = "UPDATE Statistics SET AccessCount = AccessCount + 1 WHERE PictureNo = (SELECT PictureNo FROM Pictures WHERE FileName = '"
+ pictureName + "')";
stmt.executeUpdate(query);
stmt.close();
} catch (SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage());
}
}
#
更新只是在每个会话中更新一张图片,而不是在每个会话中更新所有访问过的图片
if(session.getAttribute("myVisitedPages") == null) {
ArrayList<String> listOfPages = new ArrayList<String>();
session.setAttribute("myVisitedPages", listOfPages);
if (Utilities.isFirstVisit(listOfPages, pictureName) == true) {
Utilities.IncreaseCount(out, pictureName);
out.println("its worked");
}
}
【问题讨论】:
-
您是将这个命中计数器存储在内存中还是某个数据库中?
-
在 mysql 数据库上是。我将使用我正在使用的方法更新 OP。
标签: java