【发布时间】:2020-08-12 04:40:52
【问题描述】:
有什么方法可以识别两个或更多频繁的请求来自完全相同的浏览器/用户代理?我正在使用 Spring 3.0 版框架。
【问题讨论】:
标签: spring spring-mvc servlets spring-security user-agent
有什么方法可以识别两个或更多频繁的请求来自完全相同的浏览器/用户代理?我正在使用 Spring 3.0 版框架。
【问题讨论】:
标签: spring spring-mvc servlets spring-security user-agent
您可以向发送请求的浏览器添加具有唯一 ID 的 cookie。
以下请求将与该 cookie 一起发送,您可以使用它的值来检查此浏览器是否向您的服务发出请求。
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
public class ExampleController {
Map<String, String> agents = new HashMap<>();
@GetMapping("/foo")
public void foo(HttpServletResponse response, @CookieValue("agent-id") String agentId) {
// If the cookie is not present in the browser, the value of agentId is null
if (agentId == null) {
String newAgentId = UUID.randomUUID().toString();
agents.put(newAgentId, "request specific information");
Cookie newAgentIdCookie = new Cookie("agent-id", newAgentId);
response.addCookie(newAgentIdCookie);
System.out.println("Now I know you");
} else if (agents.containsKey(agentId)) {
System.out.println(agents.get(agentId));
}
}
}
【讨论】: