赞
踩
在做Javaweb的时候,一般会在登陆页面中添加一个校验码,就是为了方式机器恶意的进行登陆。
首先,看看前端页面怎么编写。
<div class="default" >
<input id="user_input_verifyCode"name="user_input_verifyCode"
value="${user_input_verifyCode}" type="text" placeholder="验证码 " />
<div class="vcode" id="vcodeDiv">
<img id="verifyCodeImage" title="验证码看不清?点击获取新验证码" src="" οnclick="getValidateCode()" />
<a id="changeVerifImageRegister" href="javascript:void(0);" οnclick="javascript:changeImage();" title="验证码看不清?点击获取新验证码">看不清图片?</a>
<input name="code" type="hidden" id="code" value="dologin" />
</div>
</div>
图片上添加一个点击函数,每点击一次,就更换一次
<script type="text/javascript"> //当项目第一次运行时,验证码类没有被请求,因此是这没有被生成验证码的,所以人为对发送一次请求,保证页面刷新后能出现验证码 var num=1; $(function(){ $('#verifyCodeImage').attr('src','${pageContext.request.contextPath }/checkCode?num='+num); }); </script> <script type="text/javascript"> // 这是一个获取时间的函数 function genTimestamp() { var time = new Date(); return time.getTime(); } function changeImage() { $('#verifyCodeImage').attr('src', '${pageContext.request.contextPath }/checkCode?timestamp=' + genTimestamp()); } // 在请求的后面加上时间,是为了让每次请求都不一样,不然浏览器就不会向服务器发送请求,直接从缓存中获取请求的值。 </script>
后台数据controller
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.io.output.ByteArrayOutputStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class VerificationCodeController { @Autowired @Qualifier("AhualyService") private AhualyService ahualyservice; @RequestMapping(value="/checkCode") /** * 获取验证码 */ @ResponseBody public void toCreateCode(HttpServletRequest request,HttpServletResponse response,HttpSession session,Integer num) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); ServletOutputStream out = null; drawImg(output,session); try { out = response.getOutputStream(); output.writeTo(out); } catch (IllegalStateException e) { e.printStackTrace(); } } /** * 绘画验证码 */ private String drawImg(ByteArrayOutputStream output,HttpSession session) { Random random = new Random(); String code = ""; // 随机产生5个字符 for (int i = 0; i < 5; i++) { code += randomChar(); } // 定义图片的宽度和高度 int width = (int) Math.ceil(5 * 20); int height = 30; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图片的上下文 Graphics gr = image.getGraphics(); // 设定图片背景颜色 gr.setColor(Color.WHITE); gr.fillRect(0, 0, width, height); // 设定图片边框 gr.setColor(Color.GRAY); gr.drawRect(0, 0, width - 1, height - 1); // 画十条干扰线 for (int i = 0; i < 5; i++) { int x1 = random.nextInt(width); int y1 = random.nextInt(height); int x2 = random.nextInt(width); int y2 = random.nextInt(height); gr.setColor(randomColor()); gr.drawLine(x1, y1, x2, y2); } // 设置字体,画验证码 gr.setColor(randomColor()); gr.setFont(randomFont()); gr.drawString(code, 10, 22); // 图像生效 gr.dispose(); // 输出到页面 try { //将验证码保存到session中,为登陆的时候做校验使用 session.setAttribute("code",code.toLowerCase()); System.out.println("session=="+session.getAttribute("code")); ImageIO.write(image, "jpg", output); } catch (IOException e) { e.printStackTrace(); } return code; } /** * 随机参数一个字符 */ private char randomChar() { Random r = new Random(); String s = "abcdefghjkmnprstuvwxyzABCDEFGHJKMNPRSTUVWXYZ23456789"; return s.charAt(r.nextInt(s.length())); } // 生成随机的颜色 private Color randomColor() { int red = r.nextInt(150); int green = r.nextInt(150); int blue = r.nextInt(150); return new Color(red, green, blue); } private String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312" }; private Random r = new Random(); // 生成随机的字体 private Font randomFont() { int index = r.nextInt(fontNames.length); String fontName = fontNames[index];// 生成随机的字体名称 int style = r.nextInt(4); int size = r.nextInt(3) + 24; // 生成随机字号, 24 ~ 28 return new Font(fontName, style, size); } }
通过以上步骤就可以实现前端登陆验证码的绘制了。
登陆的时候,前端传入的值中带有验证码,后端需要判断
if(!user_input_verifyCode.toLowerCase().equals(session.getAttribute("code"))){
mv.addObject("message", "验证码错误!请重新输入!!!");
// 服务器内部跳转到登录页面
mv.setViewName("forward:/loginForm");
}
以上就是完整的步骤了。下面是一张效果图。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。