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

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

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

 

这是我的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 map=new HashMap();
		    ArrayList>rs=new ArrayList>();
		   
		    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();   
	}

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

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

jsp登录页面随机验证码的生成_第1张图片

结构目录

jsp登录页面随机验证码的生成_第2张图片

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+"/";
%>



  
    
    
    My JSP 'index.jsp' starting page
      
	
	
	    
	
	
	
	 
    

  
  
  
<%
request.setCharacterEncoding("GBK");
%>
SCHOOL MIS

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. 
* * 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

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 map=new HashMap();
		    ArrayList>rs=new ArrayList>();
		   
		    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();   
	}

}

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

jsp登录页面随机验证码的生成_第3张图片

jsp登录页面随机验证码的生成_第4张图片

 

 

你可能感兴趣的:(javaweb)