【发布时间】:2019-03-07 21:50:46
【问题描述】:
我有一个包含两种方法的控制器。第一个生成一个随机验证码值,第二个将其与用户编写的输入进行比较。问题是当多个用户尝试验证验证码值时,最后生成的值已正确验证,以便为其他用户预览生成的值。
@Controller
@RequestMapping
public class CaptchaController {
private Producer captchaProducer = null;
@Autowired
private DataCaptcha dataCaptcha;
@Autowired
public void setCaptchaProducer(Producer captchaProducer) {
this.captchaProducer = captchaProducer;
}
@RequestMapping(value = "/generate-captcha.json", method = RequestMethod.GET, produces = "application/json")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String captchaText = captchaProducer.createText();
dataCaptcha.setCaptcha(captchaText);
dataCaptcha.setPasoCaptcha(false);
System.out.println("$$$$$$$$$$$$$$$$ "+ dataCaptcha.getCaptcha()); // output: null
BufferedImage bi = captchaProducer.createImage(captchaText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
out.flush();
out.close();
return null;
}
@RequestMapping(value = "/validate-captcha.json", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody Map<String, Object> validarCaptcha(HttpServletRequest request,
@RequestParam(value = "valueCaptcha", defaultValue = "") String valueCaptcha) {
String captchaId = dataCaptcha.getCaptcha();
Boolean rpta = StringUtils.equalsIgnoreCase(captchaId, valueCaptcha);
String message = "";
String messageType = "OK";
Map<String, Object> response = new HashMap<String,Object>();
if (!rpta) {
message = "incorrect captcha";
messageType = "ERROR";
dataCaptcha.setPasoCaptcha(false);
} else {
dataCaptcha.setPasoCaptcha(true);
}
response.put("messageType", messageType);
response.put("message", message);
response.put("object", rpta);
return response;
}
}
该错误是由于@Controller bean 单例造成的,我需要在我的 bean 中使用 Prototype 范围。所以我尝试了不同的方法来做到这一点:
数据验证码:
import lombok.Getter;
import lombok.Setter;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
@Getter
@Setter
public class DataCaptcha {
private String captcha;
private boolean pasoCaptcha;
}
他们都没有工作。尝试调试并在控制器上的此特定行中
String captchaText = captchaProducer.createText();
dataCaptcha.setCaptcha(captchaText);
captchaText 有一个值,但是在使用 setCaptcha 并检查对象 dataCaptcha 之后,captcha 字段是空。
我正在使用 Spring Boot 2.0.3
【问题讨论】:
-
dataCaptcha可能需要成为会话范围的 bean - this 可能会有所帮助。
标签: java spring spring-boot scope captcha