zoukankan      html  css  js  c++  java
  • 足球赛事管理系统总结

    今天我的选题基本功能都已实现,现在做一下总结。

    1.生成并验证验证码

    编写一个code类,生成并输出到一个文件夹,新建一个getCode的servlet,调用code类中的生成验证码图片的方法,在前台页面中的<image src="">中,src即为getCode的地址。在这个标签中绑定一个点击事件,可以点击验证码图片更换图片

    package Login;
    
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
        
    public class code {
    //生成验证码
        private int x = 200;
        private int y = 80;
        private int fontSize = 70;
        private StringBuilder sb = new StringBuilder();
        private Random random = new Random();
        private Color bgColor = new Color(255,255,255);
        private String[] fontsName = {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"};
        private String codes = "23456789abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
        //获取随机的字体
        private String getFont(){
            int index = random.nextInt(fontsName.length);
            String fontName = fontsName[index];
            return fontName;
        }
        //获取字母
        private String getChar(){
            int index = random.nextInt(codes.length());
            String ch = codes.charAt(index)+"";
            return ch;
        }
        //获取颜色
        private Color getColor(){
            int red = random.nextInt(150);
            int green = random.nextInt(150);
            int blue = random.nextInt(150);
            return new Color(red,green,blue);
        }
        //设置缓冲区
        private BufferedImage getBufferedImage(){
            BufferedImage bi = new BufferedImage(x,y,BufferedImage.TYPE_INT_RGB);
            Graphics2D pen = (Graphics2D)bi.getGraphics();
            pen.setColor(this.bgColor);
            pen.fillRect(0,0,x,y);
            return bi;
        }
        //给缓冲区添加字符串,添加干扰线
        private BufferedImage addCharAndLine(){
            BufferedImage bi = getBufferedImage();
            Graphics2D pen = (Graphics2D)bi.getGraphics();
            for(int i=0;i<4;i++){
            String font = getFont();
            int style = random.nextInt(4);
            pen.setColor(getColor());
            pen.setFont(new Font(font,style,fontSize));
            String s = getChar();
            sb.append(s);
            pen.drawString(s, 10+i*50, 65);
            }
            int lineNumber = 3;
            pen.setColor(Color.BLUE);
    //        pen.setStroke(new BasicStroke(1.5F));
            pen.setStroke(new BasicStroke(1.5F,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER));
            for(int i=0;i<lineNumber;i++){
                int x1 = random.nextInt(x);
                int y1 = random.nextInt(y);
                int x2 = random.nextInt(x);
                int y2 = random.nextInt(y);
                pen.drawLine(x1, y1, x2, y2);
            }
            return bi;
        }
        //获取验证码的值
        public String getText(){
            System.out.print(sb.toString());
            return sb.toString();
        }
        //获取一张验证码图片
        public BufferedImage getImage(){
            return addCharAndLine();
        }
        //输出图片
        public void outputImage(BufferedImage bi){
            String path = "C:\Users\admin\Pictures\yanzhengma\"+System.currentTimeMillis()+".jpg";
            System.out.print(path);
            try {
                ImageIO.write(bi, "JPEG", new FileOutputStream(path));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
    code
    package Login;
    
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class getCode
     */
    @WebServlet("/getCode")
    public class getCode extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public getCode() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            //response.getWriter().append("Served at: ").append(request.getContextPath());
            code code=new code();
            BufferedImage bi=code.getImage();
            String image_value=code.getText();
            System.out.print("image_value");
            code.outputImage(bi);
            request.getSession().setAttribute("image_value",image_value);
            //将图片响应给浏览器
            ImageIO.write(bi, "jpg", response.getOutputStream());
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            doGet(request, response);
        }
    
    }
    getCode
    <script>
    function getCode(){
            //点击验证码获取新的验证码
            var image=document.getElementById("code");
            var time=new Date().getTime();
            image.src="/shop/getCode?"+time;
            
        }
    </script>
    
    <img src="http://localhost:8080/shop/getCode" onclick="getCode()" name="code" id="code" style=" 100px;">
    login.html

    在code类中编写一个记录当前字母组合的方法,在getCode中调用这个方法,并将组合存入session中。在前台的输入框中绑定一个失去焦点事件,当焦点移开使用Ajax验证输入是否正确并进行提示。注意:使用Ajax需引入jquery.js

    code类同上

    getCode类同上

    <script type="text/javascript" src="../public/js/jquery-1.11.3.min.js"></script>
    <script>
    function checkCode(){
            var code_input=document.getElementById("code_input").value;
            var image=document.getElementById("code").value;
            var message="";
            $.ajax({
                url:"http://localhost:8080/shop/checkCode",
                type:"post",
                data:{code_input:code_input,image:image},
                dataType:"text",
                success:function(data){
                    if(data=="no"){
                        message="验证码输入不正确,请重新输入";
                        $("#code_message").css("color","red")
                    }
                    $("#code_message").html(message);
                }
            });
            if(message=="验证码输入不正确,请重新输入")
                code_flag=false;
            else code_falg=true;
        }
    </script>
    
    
    <input type="text" name="code" id="code_input" onblur="checkCode()" placeholder="验证码">
                    <img src="http://localhost:8080/shop/getCode" onclick="getCode()" name="code" id="code" style=" 100px;">
                    <span id="code_message"></span>
    login.html

    2.Ajax的使用

    在这次的练习频繁练习使用了Ajax,现在做一下总结:

    $.ajax({
    type:"",//传输方式,get/post
    url:"",//servlet地址
    data:{uesrname:username},//需要传输的数据,json格式
    success:function(data){
    },//成功后的回调函数
    dataType:""//返回的数据类型,最常用的text/json
    });

    dataType的选择要和后台所传类型相对应,如果要返回text,需要servlet中进行拼接:response.getWriter().write("{"isExit":"+isExit+"}");或直接输出想要输出的内容:response.getWriter().write("no");

    此时前台调用返回数据的方法:

    success:function(data){
    var obj = data;
    if(dbj==null){

    }
    if(obj!="yes"){

    }

    },

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商城登录页面</title>
    <link rel="stylesheet" href="../public/css/login.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../public/css/styles2.css">
    <script type="text/javascript" src="../public/js/jquery-1.11.3.min.js"></script>
    <script>
        var name_flag=false;
        var code_flag=false;
        function checkUsername(){
            var username=document.getElementById("username").value;
            var message="";
            //alert(username);
            $.ajax({
                   type:"post",
                   url:"http://localhost:8080/shop/checkLogin",
                   data:{uesrname:username},
                   success:function(data){
                       var obj = data;
                       if(dbj==null){
                           message="请输入用户名";
                          
                       }
                       if(obj!="yes"){
                          message="该用户名不存在";
                          alert(message)
                       }
                         
            },
              dataType:"text"
        });
            
    }
        
         
    </script>
    
    </head>
    <body>
    <div class="htmleaf-container">
        <div class="wrapper">
            <div class="container">
                <h1>Welcome</h1>
                
                
                    <input type="text" name="username" id="username" placeholder="Username" onblur="checkUsername()">
                    
            </div>
            
            
        </div>
    </div>
    </body>
    </html>
    login.html
    package Login;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    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 com.google.gson.Gson;
    
    import database.dao;
    import database.admin;
    /**
     * Servlet implementation class checkLogin
     */
    @WebServlet("/checkLogin")
    public class checkLogin extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * @return 
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            //response.getWriter().append("Served at: ").append(request.getContextPath());
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            
            String name=request.getParameter("username");
            dao dao=new dao();
            List<admin> list=new ArrayList<admin>();
            try {
                list=dao.getuser(name);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            boolean isExit=true;
            if(list!=null) {
               isExit=true;
               System.out.print("该用户存在");
               request.getSession().setAttribute("name", name);
            }else {
                System.out.print("该用户不存在");
               isExit=false;    
            }
            response.getWriter().write("{"isExit":"+isExit+"}");
            //response.getWriter().write(isExit);
            
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            doGet(request, response);
        }
    
    }
    checkLogin

    如果要返回json,需要在servlet中将数据写成json格式:

    Gson gson=new Gson();
    String json=gson.toJson(team);//team是一个list的数据
    System.out.print(json);
    response.getWriter().write(json);

    此时在前台调用返回的数据,需使用data.键名的形式

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%@page import="java.util.List" %>
        <%@page import="database.team" %>
         <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <link href="../public/css/bootstrap.css" type="text/css" rel="stylesheet" />
        <link href="../public/css/custom.css"  rel="stylesheet" />
        <script src="../public/js/jquery-1.11.3.min.js"></script>
        <script src="../public/js/bootstrap.js"></script>
    
    <script type="text/javascript">
    function loadTeam(){
        $.ajax({
            type:"post",
            url:"http://localhost:8080/shop/searchTeam",
            success: function(data){
                $(data).each(
                        
                        function (i, values) {
                            $("#list").append(
                                "<tr><td>"+(++i)+"</td>"
                                +"<td>"+values.id+"</td>"
                                +"<td>"+values.name+"</td></tr>"
                            );
                        });
            },
            dataType:"json"
        });
    }
    
    
    window.onload=loadTeam
    </script>
    </head>
    <body>
    <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">球队编号</th>
          <th scope="col">球队名称</th>
        </tr>
      </thead>
      <tbody id="list"> </tbody>
    </table>
    
    
    </body>
    </html>
    showTeam.jsp
    package team;
    
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    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 com.google.gson.Gson;
    
    import database.dao;
    import database.team;
    
    
    /**
     * Servlet implementation class searchTeam
     */
    @WebServlet("/searchTeam")
    public class searchTeam extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public searchTeam() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            //response.getWriter().append("Served at: ").append(request.getContextPath());
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            
            dao dao=new dao();
            List<team> list=new ArrayList<team>();
            try {
                list=dao.getAllTeam();
                if(list!=null) {
                    //查询结果不为空,将list发送给show.jsp
                    request.setAttribute("list", list);
                    Gson gson=new Gson();
                    String json = gson.toJson(list);
                    System.out.println(json);
                    response.getWriter().write(json);
                    //response.getWriter().write("查询结果不为空");
                }
                else {
                    //查询结果位空,返回一个信息
                    response.getWriter().write("查询结果为空");
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            doGet(request, response);
        }
    
    }
    searchTeam
  • 相关阅读:
    如何打开“USB调试”模式?
    Eclipse常用配置
    【luogu P5363】移动金币(博弈论)(DP)(数位DP)(MTT)
    【luogu P4245】【模板】任意模数多项式乘法(拆系数FFT)(MTT)
    【ybtoj高效进阶 21178】星际大战(并查集)
    【ybtoj高效进阶 21177】小小网格(杜教筛)(数论分块)(莫比乌斯反演)
    【luogu P4213】【模板】杜教筛(Sum)(数学)(整除分块)
    【luogu P6860】象棋与马(数学)(杜教筛)
    【luogu AT2376】Black and White Tree(结论)(博弈论)(二分图)
    SAM入门三题:字符串水题, LCS, P5546 [POI2000]公共串
  • 原文地址:https://www.cnblogs.com/wangzhaojun1670/p/13343415.html
Copyright © 2011-2022 走看看