作业5:

login.jsp

<span>
      <label for="code" style="width:64px;height:32px;display:inline-block;line-height:32px;">验证码:</label>
      <input type="text"   id="checkcode" name="checkcode"  style="width:130px; height:30px;display:inline-block;line-height:32px;margin:0" />
       <img  class="btnSearch" id="code" src="${pageContext.request.contextPath }/validatecode.jsp"  οnclick="javascript:document.getElementById('code').src='${pageContext.request.contextPath }/validatecode.jsp?'+Math.random();" />
</span><br/>  


validatecode.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.Random"%>
<%@ page import="java.io.OutputStream"%>
<%@ page import="java.awt.Color"%>
<%@ page import="java.awt.Font"%>
<%@ page import="java.awt.Graphics"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="javax.imageio.ImageIO"%>
<%
    int width = 80;
    int height = 32;
    //create the image
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    // set the background color
    g.setColor(new Color(0xDCDCDC));
    g.fillRect(0, 0, width, height);
    // draw the border
    g.setColor(Color.black);
    g.drawRect(0, 0, width - 1, height - 1);
    // create a random instance to generate the codes
    Random rdm = new Random();
    String hash1 = Integer.toHexString(rdm.nextInt());
    //System.out.print(hash1);
    // make some confusion
    for (int i = 0; i < 50; i++) {
        int x = rdm.nextInt(width);
        int y = rdm.nextInt(height);
        g.drawOval(x, y, 0, 0);
    }
    // generate a random code
    String capstr = hash1.substring(0, 4);
    session.setAttribute("key", capstr); 
    g.setColor(new Color(0, 100, 0));
    g.setFont(new Font("Candara", Font.BOLD, 24));
    g.drawString(capstr, 8, 24);
    g.dispose();
    response.setContentType("image/jpeg");
    out.clear();
    out = pageContext.pushBody();
    OutputStream strm = response.getOutputStream();
    ImageIO.write(image, "jpeg", strm);
    strm.close();
%>  


后台action    struts2


        String key = (String) ServletActionContext.getRequest().getSession().getAttribute("key");
        if (key == null || !key.equals(ServletActionContext.getRequest().getParameter("checkcode"))) {
            
            ServletActionContext.getRequest().setAttribute("msg", "验证码错误");
            return "input";
        }  

posted @ 2020-05-11 12:03  blinkQ  阅读(133)  评论(0)    收藏  举报