记录网页登录日志

来源:互联网 发布:淘宝卖家后台操作流程 编辑:程序博客网 时间:2024/04/27 21:42

        前两天老师讲了关于日志记录的过滤器,今天想了一下,发现老师的设计有点问题,因为老师的版本根本就记录不了用户的信息,现在来说一下我的思路:

        首先,一个非常重要的问题时,在点登录时,根本没有验证用户是否合法或者是存在,所以在过滤的时候老师就先获取用户的持久化类,再判断:

UserInfo userInfo = (UserInfo)request.getSession().getAttribute("user_info");int userId = 0;if (userInfo != null) {userId = userInfo.getUser_id();}


所以每次记录的都是userId = 0,只要把doFilter()方法调用完了再操作,就可以获得用户的持久化类了,相应的代码如下:

public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest)req;HttpServletResponse response = (HttpServletResponse)resp;String date = sdf.format(new Date());long start = System.currentTimeMillis();chain.doFilter(req, resp);long end = System.currentTimeMillis();UserInfo userInfo = (UserInfo)request.getSession().getAttribute("user_info");int userId = 0;if (userInfo != null) {userId = userInfo.getUser_id();}LogService logService = new LogService();int newId = logService.getMaxId();logService.insertNewLog(newId, date, userId, end - start);System.out.println("-----log filter-----");//chain.doFilter(req, resp);}


明显在chain.doFilter()返回后再判断才能正确记录用户的信息,因为返回后如果能登录,session已经保存了user的信息了

原创粉丝点击