jsp登录页面随机验证码的生成

jsp登录页面随机验证码的生成

在这里出现一个很奇怪,也特别疑惑的问题,就是ajax回值,json解析一直出现乱码,req.responseText  取到的一直是乱码,搞了很久,都没有能弄出来。愁人。

 <script type="text/javascript">
      
      function login(){
      
     
        
         var req=new XMLHttpRequest();
         req.open("post", "LoginServlet", true);
          req.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
           
         //获取三个元素
         var user=document.getElementsByName("name")[0];
         var pwd=document.getElementsByName("password")[0];
         var code=document.getElementsByName("code")[0];
       /*   console.log(code.value);
         console.log("username="+user.value+"&pwd="+pwd.value+"&code="+code.value); */
         //发送
         req.send("username="+user.value+"&pwd="+pwd.value+"&code="+code.value);
         
         req.onreadystatechange=function(){
           //监听状态
           if(req.readyState==4&&req.status==200){
               alert( "11"+req.responseText);
              
            
                var obj=eval(req.responseText);
                 if(obj[0].code=="1000"){
                      //跳转页面
                       window.location.href="succeed.jsp";
                 }else{
                       alert(obj[0].msg);
                 } 
                 
           }
         
         }
      }
    </script>

这是我的js代码

LoginServlet.java

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
           req.setCharacterEncoding("utf-8");
          
	    //1.接收客户端发送过来的数据
		   String username=req.getParameter("username");
		   String pwd=req.getParameter("pwd");
		   String code=req.getParameter("code");
		   System.out.println("code"+code);

		//2.处理数据
		    HttpSession se=req.getSession(true);
		   //验证code是否正确
		    HashMap<String, String> map=new HashMap<String, String>();
		    ArrayList<HashMap<String, String>>rs=new ArrayList<HashMap<String,String>>();
		   
		    rs.add(map); 
		    
		    String codes=(String)se.getAttribute("code");
		    if(!codes.equalsIgnoreCase(code)){//告诉验证错误  code:1001  msg:登录成功
		        map.put("code", "1001");
		        map.put("msg","Validation Failure");//这里的是正常中文, 但是到页面接收,就变为乱码了
		        
		        //返回前端一个json字符串
		         String json=JSON.toJSONString(rs);
		         resp.setContentType("text/html,charset:GBK");
		         resp.getWriter().print(json); 
		         System.out.println( "11"+json);
		         resp.getWriter().flush();   
		        return;
		    }
		   
		//3.响应
		    resp.setContentType("text/html,charset:GBK");
		     HttpSession session=req.getSession();
		     session.setAttribute("user", 1);
		    map.put("code","1000");
	        map.put("msg", "登录成功");
	        resp.getWriter().print( JSON.toJSON(rs));
	        resp.getWriter().flush();   
	}

我改了很久都没改出来,如果有人知道,或者能变乱码改回来,就告诉我一下,好吗

下面是登录页面的岁间验证码的生成

结构目录

index.jsp

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	 <script type="text/javascript">
      
      function login(){
      
     
        
         var req=new XMLHttpRequest();
         req.open("post", "LoginServlet", true);
          req.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
           
         //获取三个元素
         var user=document.getElementsByName("name")[0];
         var pwd=document.getElementsByName("password")[0];
         var code=document.getElementsByName("code")[0];
       /*   console.log(code.value);
         console.log("username="+user.value+"&pwd="+pwd.value+"&code="+code.value); */
         //发送
         req.send("username="+user.value+"&pwd="+pwd.value+"&code="+code.value);
         
         req.onreadystatechange=function(){
           //监听状态
           if(req.readyState==4&&req.status==200){
               alert( "11"+req.responseText);
              
            
                var obj=eval(req.responseText);
                 if(obj[0].code=="1000"){
                      //跳转页面
                       window.location.href="succeed.jsp";
                 }else{
                       alert(obj[0].msg);
                 } 
                 
           }
         
         }
      }
    </script>
    <style type="text/css">
        *{
        	margin: 0;
        	padding: 0;
        }
        html,body{
        	height: 100%;
        } 
        ul,li{
        	list-style: none;
        }
        input{
        	border-radius: 10px;
        	box-shadow:0 0 7px #202;
        }
        a:link{
        	color:white; 
        }
        a:visited{
        	color:white;
        }
        a:hover{
        	color: #454545;
        	text-decoration:none;
        	font-weight: bolder;
        }
        a:active{
        	font-weight: normal;
        }

        .header{		/*HOSPITAL MIS*/
        	width:600px;
        	height: 750px;
        	position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            font-size: 70px;
            font-family: San Francisco;
        	display:inline-block; 
	   		text-align:center;
        	color:rgba(240,248,255,0.6);

        }

        .login{				/*login bar*/
            width: 500px;
            height: 455px;
            background-color: rgba(240,248,255,0.3);
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            border-radius: 13px;
            box-shadow:0 0 15px rgba(255,255,255,0.8);/*阴影*/
        }

        .login.info{		
        	 height:290px; 
	  	 	 width:100%;
	  	 	 background:#f0f;
        }

        .login ul{
        	padding-top:40px;/*上间距*/
        	font-size:17px;
        	color:#454545;

        }	

        .login ul li{
	        margin-bottom:25px;/*列间距*/
	    }

	    .login ul .manage{		/*I'm manager*/
	    	width: 200px;
	    	margin-top: 380px;
	    	margin-left: 150px;
	    	position: absolute;
	    	font-family: San Francisco;
	    	font-size: 16px;
	    	text-align: center;
	    	text-decoration: underline;
	    }

	    .login ul li .topic{		/*LOGIN*/
	    width:520px;
	    margin-top: -10px;
	    font-size:35px;
	    display:inline-block;/*里面可以有block none table  inline—block:变成行间快捷元素*/  
	    text-align:center;/*对齐方式*/
	    }

	    .login ul li .remem{		/*remember me*/
	    width:410px;
	    font-size:15px;
	    display:inline-block;/*里面可以有block none table  inline—block:变成行间快捷元素*/  
	    text-align:right;/*对齐方式*/
	    }

	    .login ul li label{
	    width:160px;
	    display:inline-block;/*里面可以有block none table  inline—block:变成行间快捷元素*/  
	    text-align:right;
	    }

	    .login ul li .txt{
	    width:250px;	
	    height:40px;
	    border:1px solid #eee;
	    background:rgba(240,248,255,0.4);/*背景颜色设为白色fff*/
	    text-indent:10px;/*输入的账户名和边框的间隙*/
	    color:#909090;/*账户名的颜色*/
	    }

	    .log{
	     	width: 100%;
	     	text-align:center;
	    }

	    .btn{
	     	margin-top: 20px;
	    	width: 70%;
	    	height: 40px;
	    	background-color:rgba(240,248,255,0.4);
	    	border: white;
	    	font-size: 16px;
	    	box-shadow:0 0 2px #FFFFE0;
	    	cursor: pointer; /*鼠标指针形状,还有move*/
	    }
	        .outer{
        height: 100%;    
        position: relative;
        background-image: url("./images/1.jpg");
        background-repeat: no-repeat;
        background-size: cover;
        }
        .footer{
	    	position: absolute;
	    	text-align: center;
	    	color: rgba(240,248,255,0.9);
	    	font-size: 15px;
	    	font-family:San Francisco;
	    	left: 45%;
	    	bottom:0%;
	    }
</style>

  </head>
  
  <body>
<%
request.setCharacterEncoding("GBK");
%>
<div class="outer">
		<div class="header">SCHOOL MIS</div>
			<div class="login">
				<div class="info">
				
				
					
		
					<ul>
					<li>
						<a href="./manage_login" class="manage"></a>
						<div class="topic"> 登录<br></div>
					</li>
					<li>
						<label for="">账号:</label>
						<input class="txt" type="text" name="name" id="name">
					</li>
					<li>
						<label for="">密码:</label>
						<input class="txt" type="password"  name="password"  id="password">
					</li>
					<li>
						<label for="">权限:</label>
						<select name="cx" id="cx">
                    <option value="管理员">管理员</option>
                  </select>
                </td>
					</li>
					<li>
						<label for="">验证码:</label>
				<td height="30"></td>
                <td width="59" height="30">       <input type="text" class="input input-big" name="code" placeholder="填写右侧的验证码" data-validate="required:请填写右侧的验证码" />
                           
                <td width="102"> <img src="ValidCodeServle" alt="" width="100" height="32" class="passcode" style="height:43px;cursor:pointer;" οnclick="this.src=this.src+'?'"> 
					</li>
				
						</ul>
						<div class="log">
							<input class="btn" type="button"  value="登录"   οnclick="login()">
						
							<a href="./register"><input class="btn" type="button" value="注册"></a>
						</div>
					</div>
				</div>
		</div>
		<div class="footer">&copy;Hospital MIS:Zzy</div>
















</html>

ValidCodeServle.java

package util;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;

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

public class ValidCodeServle extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("GBK");
		response.setContentType("text/html");
		//1.生成一个验证吗
	    String code=ValidationNumber.getStr();
	    //把验证吗存放在session中
	    HttpSession session=request.getSession(true);
	    session.setAttribute("code", code);
	//2.通过验证吗生成一个图片
	    BufferedImage img=ValidationNumber.creatImage(code);
	//3.将图片发送给前端 
	    ImageIO.write(img, "png", response.getOutputStream());
	}

}

ValidationNumber.java

扫描二维码关注公众号,回复: 8870244 查看本文章
package util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ValidationNumber {
  //声明一个String 字符串
  static String valid="0123456789asdfghjklqwertyuiopzxcvbnmASDFGHJKLZXCVBNMQWERTYUIOP";
	
  //随机生成字符串
  	public static String getStr(){
  	   //1.初始化一个可变字符串
  		StringBuilder str=new StringBuilder();
  	   //2.通过随机函数获取 字符串的字符
  	    Random ranodm= new Random();
  		for (int i = 0; i <4; i++) {
		  //1.生成随机数据 0-valisd.length-1;
  		    int num=ranodm.nextInt(valid.length());
  			char c=valid.charAt(num);
  	      //2.追加字符串
  			str.append(c);	
		}
  		return str.toString();
  	}
  	
  	//通过验证码 创建一张图片
  	public static BufferedImage creatImage(String str){
  	    int width=100;
  	    int height=33;
  	    //创建一个图片 空的图片
  		BufferedImage img=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
  		//2获取当前图片的上下文
  		Graphics g=img.getGraphics();
  		//3设置图片的背景颜色
  		g.setColor(Color.gray);
  		g.fillRect(0, 0, width, height);

  		//绘制文字
  		g.setColor(Color.GREEN);
  		g.setFont(new Font("宋体", Font.CENTER_BASELINE, 18));
  		g.drawString(str,15,20);
  		return img;
  	}
  	
	
	
}

LoginServlet.java

package util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.registry.infomodel.User;
import javax.xml.ws.Response;

import com.alibaba.fastjson.JSON;

public class LoginServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	  doPost(request, response);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
           req.setCharacterEncoding("utf-8");
          
	    //1.接收客户端发送过来的数据
		   String username=req.getParameter("username");
		   String pwd=req.getParameter("pwd");
		   String code=req.getParameter("code");
		   System.out.println("code"+code);

		//2.处理数据
		    HttpSession se=req.getSession(true);
		   //验证code是否正确
		    HashMap<String, String> map=new HashMap<String, String>();
		    ArrayList<HashMap<String, String>>rs=new ArrayList<HashMap<String,String>>();
		   
		    rs.add(map); 
		    
		    String codes=(String)se.getAttribute("code");
		    if(!codes.equalsIgnoreCase(code)){//告诉验证错误  code:1001  msg:登录成功
		        map.put("code", "1001");
		        map.put("msg","Validation Failure");//这里的是正常中文, 但是到页面接收,就变为乱码了
		        
		        //返回前端一个json字符串
		         String json=JSON.toJSONString(rs);
		         resp.setContentType("text/html,charset:GBK");
		         resp.getWriter().print(json); 
		         System.out.println( "11"+json);
		         resp.getWriter().flush();   
		        return;
		    }
		   
		//3.响应
		    resp.setContentType("text/html,charset:GBK");
		     HttpSession session=req.getSession();
		     session.setAttribute("user", 1);
		    map.put("code","1000");
	        map.put("msg", "登录成功");
	        resp.getWriter().print( JSON.toJSON(rs));
	        resp.getWriter().flush();   
	}

}

点击验证码图片,就可以刷新了

发布了155 篇原创文章 · 获赞 1 · 访问量 2254

猜你喜欢

转载自blog.csdn.net/zhupengqq1/article/details/104090938
今日推荐