日期:2014-05-17 浏览次数:20748 次
public class VoteLimitFilter implements Filter { private FilterConfig fc = null; private VoterDao voterDao; public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) srequest; HttpServletResponse response = (HttpServletResponse) sresponse; HttpSession session = request.getSession(); String dispatch = request.getParameter("dispatch"); String titleId =request.getParameter("titleId"); //白名单 List<String> whitelist = new ArrayList<String>(); whitelist.add("insertOrUpdateTitle"); whitelist.add("checkVoteById"); whitelist.add("showTitleList"); whitelist.add("prepareNew"); whitelist.add("showVoteResult"); whitelist.add("prepareInsertItem"); whitelist.add("getTitleById"); whitelist.add("getOptionById"); whitelist.add("updateItem"); whitelist.add("insertItem"); whitelist.add("deleteVote"); whitelist.add("getVoterList"); if(!whitelist.contains(dispatch)){ String ip = request.getRemoteAddr(); // 获取客户端IP int optionid = 1; // //获取选择的选项ID try { Date now = new Date(); // 获取当前时间 Date last = voterDao.getLastVoteTime(ip,Integer.parseInt(titleId)); // 获取该IP的上次对该标题的投票时间 if (last == null) { // 数据库中没有记录该IP,则该IP地址没有投过票 addCookie(request, response,titleId); // 在客户端的cookie中添加该用户投票记录 Voter voter = new Voter(); voter.setVote_title(Integer.parseInt(titleId)); voter.setVoter_Ip(ip); voter.setVoter_option(optionid); voter.setVote_time(StringUtil.timeTostr(now)); voterDao.saveVoteTime(voter); // 在数据库中记录该IP、选择的选项ID和投票时间 chain.doFilter(request, response); } else { // 该IP地址投过票,则接着判断客户端cookie中是否记录了用户投票情况(用来解决局域网中某个ip投票后,其他ip不能再进行投票的问题) boolean voteincookie = seeCookie(request); // 判断当前使用该IP的用户的客户端的cookie中是否记录了投票标记 if (voteincookie) { // 如果记录了该用户已经投过票 request.setAttribute("message", "● 您已经投过票了,1小时内不允许重复投票!"); RequestDispatcher rd = request .getRequestDispatcher("fail.jsp"); rd.forward(request, response); } else {