【问题标题】:Spring MVC increase counter based on Session Requests/IP AdressesSpring MVC 根据会话请求/IP 地址增加计数器
【发布时间】:2018-05-07 19:06:15
【问题描述】:

我正在启动一个允许用户通过其内容获利的应用程序。我根据页面上的查看次数来确定赚到的金额,因此该页面需要一种经过验证的方式来计算查看次数。据我所知,让一个用户只能增加一次查看计数器(就像 YouTube 视频一样)的最佳方法是使用 Session RequestsIP Adresses.

这是我的控制器:

@RequestMapping("/viewPhoto/{id}")
    public String viewPhoto(@PathVariable int id, Model model) {
        Photo photo = photoService.getPhotoById(id);
        //irrelevant code
        Long commentNumber = commentService.getCommentNumber(id); //number of comments
        List<Comment> commentList = commentService.getComments(); //getting comments
        List<Reply> replyList = commentService.getRepliesByComment(); //getting replies for each comment
        model.addAttribute("replyList", replyList);
        model.addAttribute("commentList", commentList);
        model.addAttribute("photo", photo);
        model.addAttribute("commentNumber", commentNumber);
        //if the viewer is valid and hasn't viewed the photo, increment view count
        return "viewPhoto";
    }

如果我使用@SessionAttribute 检索会话对象,我如何使用它来验证视图是否唯一?

对不起,如果这是一个菜鸟问题。

提前谢谢你!

【问题讨论】:

    标签: java spring validation session model-view-controller


    【解决方案1】:

    我相信你可以使用HttpServletRequest.getRemoteAddress()提取访问者的IP地址

    下面是示例代码,没测试过,应该没问题。

    @RequestMapping("/viewPhoto/{id}")
    public String viewPhoto(@PathVariable int id, Model model, HttpServletRequest request) {
        Photo photo = photoService.getPhotoById(id);
        //irrelevant code
        Long commentNumber = commentService.getCommentNumber(id); //number of comments
        List<Comment> commentList = commentService.getComments(); //getting comments
        List<Reply> replyList = commentService.getRepliesByComment(); //getting replies for each comment
        model.addAttribute("replyList", replyList);
        model.addAttribute("commentList", commentList);
        model.addAttribute("photo", photo);
        model.addAttribute("commentNumber", commentNumber);
        //if the viewer is valid and hasn't viewed the photo, increment view count
    
        String remoteIP = request.getRemoteAddr();
        //enter logic here to check if user with this IP has already viewed or not
        return "viewPhoto";
    }
    

    【讨论】:

    • 感谢您的回答,但问题依旧,如何查看IP地址是否查看过照片? :)
    • 嗯,你需要有一个数据库或缓存,在其中保存图像/页面与 IP 地址的映射。一个糟糕而快速的实现可能是:Map&lt;Image, List&lt;IPAddress&gt;&gt; map = ..; if(map.get(image).contains(IPAddress)) { //not first visit }
    • 一开始我就想到了这个,但我认为在数据库中创建另一个表来存储视图并不是一个明智的决定。不过,这似乎是必要的。由于我存储了可以存储为字符串的 IP 地址,您认为我应该为视图创建另一个模型,还是会降低应用程序的速度?如果我制作另一个带有照片链接的模型,数据库对表中的行有限制,如果一张图片有 10 000 次查看,那么加载所有 10 000 个模型将成为问题。有没有其他的实现方式?
    猜你喜欢
    • 2011-04-25
    • 2011-03-11
    • 2017-03-30
    • 1970-01-01
    • 2011-10-08
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多