java秒杀商品项目中使用验证码恶意防刷的例子,给出具体代码
时间: 2024-03-04 22:51:14 浏览: 149
好的,下面是Java秒杀商品项目中使用验证码防刷的具体代码实现:
1. 在前端页面上加入验证码组件,比如Google reCAPTCHA或者阿里云的验证码组件等等。这里以Google reCAPTCHA为例,前端代码如下:
```
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
```
2. 在后端控制器中,对用户提交的验证码进行校验。如果验证码输入错误,则返回错误信息,防止用户恶意提交表单。这里以Spring Boot为例,后端代码如下:
```java
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@Controller
public class CaptchaController {
@Autowired
private DefaultKaptcha captchaProducer;
@PostMapping("/checkCaptcha")
@ResponseBody
public Map<String, Object> checkCaptcha(HttpServletRequest request, HttpServletResponse response,
@RequestBody Map<String, String> params) throws IOException {
// 从请求参数中获取验证码
String captcha = params.get("captcha");
// 从Session中获取生成的验证码
String kaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
// 对比验证码是否一致
Map<String, Object> result = new HashMap<>();
if (captcha == null || !captcha.equalsIgnoreCase(kaptcha)) {
result.put("success", false);
result.put("errMsg", "验证码输入错误!");
return result;
} else {
result.put("success", true);
return result;
}
}
@PostMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
// 生成验证码
String text = captchaProducer.createText();
BufferedImage image = captchaProducer.createImage(text);
// 将验证码存入Session中
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
// 输出验证码图片
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
@Autowired
public void setCaptchaProducer(DefaultKaptcha captchaProducer) {
this.captchaProducer = captchaProducer;
}
}
```
3. 在数据库中对每个用户的IP地址和访问时间进行记录,如果发现某个IP地址在短时间内多次访问相同的商品页面,就认为该IP地址可能是恶意刷单,可以将该IP地址拉黑,禁止其继续访问。这里以Redis为例,后端代码如下:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class IpLimitService {
private static final String IP_LIMIT_KEY_PREFIX = "ipLimit:";
@Autowired
private RedisTemplate<String, Integer> redisTemplate;
/**
* 判断IP地址是否被限制访问
*/
public boolean isIpLimited(String ip) {
String key = IP_LIMIT_KEY_PREFIX + ip;
Integer count = redisTemplate.opsForValue().get(key);
if (count == null) {
return false;
}
return count >= Constants.IP_LIMIT_THRESHOLD;
}
/**
* 增加IP地址的访问次数
*/
public void incrIpCount(String ip) {
String key = IP_LIMIT_KEY_PREFIX + ip;
Integer count = redisTemplate.opsForValue().get(key);
if (count == null) {
redisTemplate.opsForValue().set(key, 1, Constants.IP_LIMIT_DURATION, TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().increment(key, 1);
}
}
}
```
4. 对于高并发场景,可以使用分布式缓存来存储已经拉黑的IP地址,以减轻数据库的压力。这里以Redis为例,后端代码如下:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class IpLimitService {
private static final String IP_LIMIT_KEY_PREFIX = "ipLimit:";
private static final String BLACKLIST_KEY = "ipLimit:blacklist";
@Autowired
private RedisTemplate<String, Integer> redisTemplate;
/**
* 判断IP地址是否被限制访问
*/
public boolean isIpLimited(String ip) {
String key = IP_LIMIT_KEY_PREFIX + ip;
Integer count = redisTemplate.opsForValue().get(key);
if (count == null) {
return false;
}
if (count >= Constants.IP_LIMIT_THRESHOLD) {
// 将IP地址添加到黑名单中
redisTemplate.opsForSet().add(BLACKLIST_KEY, ip);
return true;
}
return false;
}
/**
* 判断IP地址是否在黑名单中
*/
public boolean isIpBlacklisted(String ip) {
return redisTemplate.opsForSet().isMember(BLACKLIST_KEY, ip);
}
/**
* 增加IP地址的访问次数
*/
public void incrIpCount(String ip) {
String key = IP_LIMIT_KEY_PREFIX + ip;
Integer count = redisTemplate.opsForValue().get(key);
if (count == null) {
redisTemplate.opsForValue().set(key, 1, Constants.IP_LIMIT_DURATION, TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().increment(key, 1);
}
}
}
```
以上就是Java秒杀商品项目中使用验证码防刷的具体代码实现,供您参考。
阅读全文