1、概念
Ajax不是一种新的编程语言, 而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。
2、使用原因
传统的网页(即不用ajax技术的网页) , 想要更新内容或者提交一个表单, 都需要重新加载整个网页。
使用Ajax技术的网页,通过在后台服务器进行少量的数据交换, 就可以实现异步局部更新。
3、验证码,前端代码
<script src="js/jQuery.js"></script>
<script type="text/javascript">
$(function(){
//实现点击更换图片
$("#imgCode").click(function(){
$(this).attr("src","${pageContext.request.contextPath}/codeImage.action?"+new Date());
});
//点击登录时
$("#loginBtn").click(function(){
if($("#username").val()==""){ alert("用户名不能为空");return;}
if($("#password").val()==""){alert("密码不能为空");return;}
if($("#code").val()==""){alert("验证码不能为空");return;}
//通过ajax获取数据
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/codeValue.action",
success:function(returnDate){
if($("#code").val().toLowerCase()==returnDate.code.toLowerCase()){
if($("#username").val()!="" && $("#password").val()!=""){
$("#form1").submit();
}
}else{
alert("验证码错误");
}
}
});
});
});
</script>
//from表单部分
<form action="${pageContext.request.contextPath}/login.action" method="post" id= "form1">
<table>
<tr><td>用户名:</td><td colspan="2"><input type="text" name="username" id="username" /></td></tr>
<tr><td>密码:</td><td colspan="2"><input type="password" name="password" id="password"/></td></tr>
<tr>
<td>验证码:</td>
<td colspan="1"><input type="text" name="code" id="code"/></td>
<td colspan="1">
<img id="imgCode" src="${pageContext.request.contextPath}/codeImage.action" title="看不清楚,点击更换验证码"/>
</td>
</tr>
<tr><td colspan="3" style="color: red">${requestScope.loginErr}</td></tr>
<tr><td><input type="button" value="登录" name="login" id = "loginBtn" /></td></tr>
</table>
</form>
4、验证码,后端代码
@WebServlet("/codeImage.action")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CodeImage random =new CodeImage();
random.getRandCode(request, response);//获取验证码
}
//Ajax部分
@WebServlet("/codeValue.action")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Object mm = session.getAttribute("imageCode");
response.setContentType("application/json");
Code code = new Code(mm.toString());
Gson gson = new Gson();//maven中引入依赖
String jString = gson.toJson(code);
response.getWriter().println(jString);
}
//自己写的验证码类
public class CodeImage {
private int height = 40;
private int width = 80;
private int lineNum = 40;
private int stringNum = 4;
private Random random = new Random();
private String randomString = "123456789ABCDEFHIJKLMNPQRSTUVWXYZ";
private Font getFont(){
Font font = new Font("宋体",Font.CENTER_BASELINE,25);
return font;
}
private Color getColor(){
Color color = new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
return color;
}
private void drawLine(Graphics gh){
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(13);
int y1 = random.nextInt(15);
gh.drawLine(x, y, x+x1, y+y1);
}
private String drawData(Graphics gh,String data,int num){
gh.setFont(getFont());
gh.setColor(getColor());
String randData = String.valueOf(randomString.charAt(random.nextInt(randomString.length())));
data = data + randData;
gh.drawString(randData, num*18, 16);
return data;
}
public void getRandCode(HttpServletRequest request,HttpServletResponse response){
HttpSession session = request.getSession();
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics gh = image.getGraphics();
gh.fillRect(0, 0, width, height);
gh.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
gh.setColor(getColor());
for(int i=0;i<lineNum;i++){
drawLine(gh);
}
gh.translate(3, 10);
String data = "";
for(int i=0;i<stringNum;i++){
data = drawData(gh,data,i);
}
session.setAttribute("imageCode", data);
gh.dispose();
try {
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}