这里需要用到一个工具包hutool
代码及注解
package cn.xc.servlet.user;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.xc.util.SessionKey;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/getCode")
public class GetCode extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取验证码图片
CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(60, 30, 4, 20);
//获取验证码内容,并存到session
String code = captcha.getCode();
req.getSession().setAttribute(SessionKey.CODE_KEY,code);
//把验证码图片发送给前端
captcha.write(resp.getOutputStream());
}
}
前端代码
<form>
<table>
<tr>
<td>
<span>用户名:</span>
</td>
<td>
<input type="text" class="text" id="userName">
</td>
</tr>
<tr>
<td>
<span>密码:</span>
</td>
<td>
<input type="password" class="text" id="pwd">
</td>
</tr>
<tr>
<td>
<span>验证码:</span>
</td>
<td>
<input type="text" id="captcha" class="text">
</td>
<td>
<!--这里图片路径为上面 servlet 的路径 onclick点击事件绑定JS文件的方法-->
<img src="getCode" id="m" alt="点击更换" title="点击更换" onclick="getCode()" >
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="登录" id="butt">
</td>
</tr>
</table>
</form>
JS代码
function getCode() {
// 将图片路径设为上面servlet的路径,并在后面添加时间参数,如未加参数则获取到的还是之前的验证码图片起不到刷新的效果
$("#m").attr("src", "getCode?date=" + new Date().getTime());
}
运行效果