1 24 package org.riotfamily.website.filter; 25 26 import java.io.IOException ; 27 import java.util.regex.Pattern ; 28 29 import javax.servlet.FilterChain ; 30 import javax.servlet.ServletException ; 31 import javax.servlet.http.HttpServletRequest ; 32 import javax.servlet.http.HttpServletResponse ; 33 import javax.servlet.http.HttpServletResponseWrapper ; 34 35 import org.springframework.web.filter.OncePerRequestFilter; 36 37 44 public class BotSessionFilter extends OncePerRequestFilter { 45 46 public static final String DEFAULT_BOT_PATTERN = "bot|crawler|spider"; 47 48 private static final String USER_AGENT_HEADER = "User-Agent"; 49 50 private Pattern pattern = Pattern.compile(DEFAULT_BOT_PATTERN); 51 52 61 public void setPattern(String pattern) { 62 this.pattern = Pattern.compile(pattern); 63 } 64 65 69 protected boolean shouldNotFilter(HttpServletRequest request) { 70 return request.isRequestedSessionIdFromCookie() || !isBot(request); 71 } 72 73 78 protected boolean isBot(HttpServletRequest request) { 79 String agent = request.getHeader(USER_AGENT_HEADER); 80 if (agent != null) { 81 return pattern.matcher(agent.toLowerCase()).find(); 82 } 83 return false; 84 } 85 86 90 protected final void doFilterInternal(HttpServletRequest request, 91 HttpServletResponse response, FilterChain filterChain) 92 throws ServletException , IOException { 93 94 filterChain.doFilter(request, new NoRewriteResponse(response)); 95 } 96 97 100 private static class NoRewriteResponse extends HttpServletResponseWrapper { 101 102 public NoRewriteResponse(HttpServletResponse response) { 103 super(response); 104 } 105 106 public String encodeRedirectUrl(String url) { 107 return url; 108 } 109 110 public String encodeRedirectURL(String url) { 111 return url; 112 } 113 114 public String encodeUrl(String url) { 115 return url; 116 } 117 118 public String encodeURL(String url) { 119 return url; 120 } 121 } 122 123 } 124 | Popular Tags |