從服務器端動態返回驗證碼

今天寫了個簡單的驗證碼小程序,主要是經過服務器的servlet小程序來實現,代碼以下:javascript

1.web.xml配置:css

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>webProject</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!--註冊servlet-->
  <servlet>
      <servlet-name>loginServlet</servlet-name>
      <servlet-class>com.dxd.web.servlet.LoginServlet</servlet-class>
  </servlet>
  <!--開放servlet路徑-->
  <servlet-mapping>
      <servlet-name>loginServlet</servlet-name>
      <url-pattern>/login.do</url-pattern>
  </servlet-mapping>
  <servlet>
      <servlet-name>varifyCodeServlet</servlet-name>
      <servlet-class>com.dxd.web.servlet.VarifyCodeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>varifyCodeServlet</servlet-name>
      <url-pattern>/varifyCode.jpeg</url-pattern>
  </servlet-mapping>
  <!--註冊filter-->
  <filter>
      <filter-name>encodeFilter</filter-name>
      <filter-class>com.dxd.web.filter.EncodeFilter</filter-class>
  </filter>
  <!--開放filter路徑-->
  <filter-mapping>
      <filter-name>encodeFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--註冊filter-->
  <filter>
      <filter-name>varifyFilter</filter-name>
      <filter-class>com.dxd.web.filter.VarifyFilter</filter-class>
  </filter>
  <!--開放filter路徑-->
  <filter-mapping>
      <filter-name>varifyFilter</filter-name>
      <url-pattern>/mainPages/*</url-pattern>
  </filter-mapping>
</web-app>html

2.主頁面index.jspjava

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript">
    window.onload = function(){
        change();
        console.log(3);
    };
    function change(){
        document.getElementById("img").src = "${pageContext.request.contextPath}/varifyCode.jpeg?time="+new Date().getTime();
        
    }
</script>
<style type="text/css">
    #img{vertical-align:middle;}
</style>
</head>
<body>
    <center>
        <form action="/webProject/login.do" method="post">
            <h3>登陸界面</h3>
            <font color="green">${requestScope.info}</font><br><br>
            <input type="text" name="userName" style="height:24px;" placeholder="請輸入名稱"/><br><br>
            <input type="password" name="passWord" style="height:24px" placeholder="請輸入密碼"/><br><br>
            <image id="img" alt="photo" src="" style="width:60px; height:30px; cursor:pointer"
            onclick="change()" title="看不清請點擊下一張""/>
            <input type="text" name="varifyCode" placeholder="請輸入驗證碼" style="width:80px; height:24px;" /><br><br>
            <input type="submit" value="登陸"style=" border:none;
            width:137px;  height:24px; color:white;"/>
        </form>
    </center>
</body>
</html>web

3.登錄後界面,main.jsp小程序

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    <center>
        <h1>歡迎${sessionScope.userName}登陸本系統</h1>
    </center>
</body>
</html>服務器

4.登陸servletsession

package com.dxd.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登陸界面servle
 * @author Administrator
 *
 */
public class LoginServlet extends HttpServlet{
    {
        System.out.println("LoginServlet");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        String info = "";
        if(session != null){
            String varifyCode = request.getParameter("varifyCode");
            String varifyCodeSession = (String) session.getAttribute("varifyCode");
            if(varifyCode != null && varifyCode.equalsIgnoreCase(varifyCodeSession)){
                String userName = request.getParameter("userName");
                String passWord = request.getParameter("passWord");
                if(userName.equals("echo") && passWord.equals("123456")){
                    request.getRequestDispatcher("mainPages/main.jsp").forward(request, response);
                    session.setAttribute("userName", userName);
                    return;
                }else{
                    info = "用戶名或者密碼錯誤";
                }
            }else{
                info ="驗證碼錯誤";
            }    
        }else{
            info = "用戶非法操做";
        }
        request.setAttribute("info", info);
        System.out.println(request.getRemoteAddr()+"\t"+request.getRemoteHost());
        //response.sendError(404, "hhhhahh");
        request.getRequestDispatcher("index.jsp").forward(request, response);
        
        System.out.println("22");
    }
    
}
5.驗證碼servletapp

package com.dxd.web.servlet;

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.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class VarifyCodeServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    {
        System.out.println("VarifyCodeServlet");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        int width = 60;
        int height = 30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.BLUE);
        g.drawRect(0, 0, width-1, height-1);
        
        Random random = new Random();
        String[] str = new String[4];
        StringBuffer str1 = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            char chars = 0;
            int num = random.nextInt(62);
            if(num >= 0 && num<= 9){
                num+=48;
                chars = (char)num;
            }else if(num >= 10 && num <= 35){
                num+=55;
                chars = (char)num;
            }
            else if(num >= 36 && num <= 61){
                num+=61;
                chars = (char)num;
            }
            str[i] = String.valueOf(chars);
            str1.append(str[i]);
        }
        g.setFont(new Font("仿宋",Font.BOLD,20));
        g.setColor(Color.RED);
        g.drawString(str[0], 6, 25);
        g.drawString(str[1], 20, 20);
        g.drawString(str[2], 32, 18);
        g.drawString(str[3], 46, 28);
        
        g.setColor(Color.GREEN);
        for (int i = 0; i < 18; i++) {
            g.fillOval(random.nextInt(width), random.nextInt(height), 1, 1);
            if(i % 2 == 0){
                g.drawLine(random.nextInt(width), random.nextInt(height),random.nextInt(width), random.nextInt(height));
            }            
        }
        //釋放此圖形的上下文以及它使用的全部系統資源
        g.dispose();
        //獲取驗證碼
        HttpSession session = request.getSession(false);
        session.setAttribute("varifyCode", str1.toString());
        //將繪製圖像放進輸出流中
        ServletOutputStream output = response.getOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
        encoder.encode(image);
        System.out.println("888");
    }
    
}
6.字符集設置過濾器dom

package com.dxd.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * response,request字符集過濾器
 * @author Administrator
 *
 */
public class EncodeFilter implements Filter{
    {
        System.out.println("EncodeFilter");
    }
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        
    }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        //設置字符編碼
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html; charset=utf-8");
        //鏈
        System.out.println("123");
        chain.doFilter(servletRequest, servletResponse);
        System.out.println(321);
    }
}
7.main.jsp頁面訪問過濾器

package com.dxd.web.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * 設置非法訪問過濾器 * @author Administrator * */public class VarifyFilter implements Filter{    {        System.out.println("VarifyFilter");    }    @Override    public void destroy() {        // TODO Auto-generated method stub            }    @Override    public void init(FilterConfig arg0) throws ServletException {        // TODO Auto-generated method stub            }    @Override    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)            throws IOException, ServletException {        HttpServletRequest request = (HttpServletRequest) servletRequest;        HttpServletResponse response = (HttpServletResponse) servletResponse;        HttpSession session = request.getSession(false);        if(session != null && session.getAttribute("userName") != null){            chain.doFilter(servletRequest, servletResponse);        }else{            response.sendRedirect(request.getContextPath()+"/index.jsp");        }    }    }

相關文章
相關標籤/搜索