Generation of random verification code for jsp login page
There is a very strange and especially puzzling problem here, that is, ajax return value, json parsing has always been garbled, what req.responseText gets has always been garbled, which has been done for a long time, but can't be found out. Worry about people.
<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"); //Get three elements 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); */ //Send out req.send("username="+user.value+"&pwd="+pwd.value+"&code="+code.value); req.onreadystatechange=function(){ //Listening state if(req.readyState==4&&req.status==200){ alert( "11"+req.responseText); var obj=eval(req.responseText); if(obj[0].code=="1000"){ //Jump page window.location.href="succeed.jsp"; }else{ alert(obj[0].msg); } } } } </script>
This is my js code
LoginServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); //1. Receive the data sent by the client String username=req.getParameter("username"); String pwd=req.getParameter("pwd"); String code=req.getParameter("code"); System.out.println("code"+code); //2. Processing data HttpSession se=req.getSession(true); //Verify that the code is correct 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)){//Tell validation error code: 1001 MSG: login succeeded map.put("code", "1001"); map.put("msg","Validation Failure");//Here's normal Chinese, but when it comes to page reception, it becomes garbled //Return the front-end json string 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. response resp.setContentType("text/html,charset:GBK"); HttpSession session=req.getSession(); session.setAttribute("user", 1); map.put("code","1000"); map.put("msg", "Login successfully"); resp.getWriter().print( JSON.toJSON(rs)); resp.getWriter().flush(); }
I haven't changed it for a long time. If anyone knows or can change the random code, let me know, OK
The following is the generation of the age verification code of the login page
Structure catalog
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"); //Get three elements 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); */ //Send out req.send("username="+user.value+"&pwd="+pwd.value+"&code="+code.value); req.onreadystatechange=function(){ //Listening state if(req.readyState==4&&req.status==200){ alert( "11"+req.responseText); var obj=eval(req.responseText); if(obj[0].code=="1000"){ //Jump page 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);/*shadow*/ } .login.info{ height:290px; width:100%; background:#f0f; } .login ul{ padding-top:40px;/*Upper spacing*/ font-size:17px; color:#454545; } .login ul li{ margin-bottom:25px;/*Column spacing*/ } .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;/*There can be block none table inline - block: become a quick element between lines*/ text-align:center;/*Alignment mode*/ } .login ul li .remem{ /*remember me*/ width:410px; font-size:15px; display:inline-block;/*There can be block none table inline - block: become a quick element between lines*/ text-align:right;/*Alignment mode*/ } .login ul li label{ width:160px; display:inline-block;/*There can be block none table inline - block: become a quick element between lines*/ text-align:right; } .login ul li .txt{ width:250px; height:40px; border:1px solid #eee; background:rgba(240,248,255,0.4);/*Background color set to white fff*/ text-indent:10px;/*Gap between account name and border entered*/ color:#909090; / * color of account name*/ } .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; /*Mouse pointer shape, and 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"> Sign in<br></div> </li> <li> <label for="">Account number:</label> <input class="txt" type="text" name="name" id="name"> </li> <li> <label for="">Password:</label> <input class="txt" type="password" name="password" id="password"> </li> <li> <label for="">Jurisdiction:</label> <select name="cx" id="cx"> <option value="Administrators">Administrators</option> </select> </td> </li> <li> <label for="">Verification Code:</label> <td height="30"></td> <td width="59" height="30"> <input type="text" class="input input-big" name="code" placeholder="Fill in the verification code on the right" data-validate="required:Please fill in the verification code on the right" /> <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="Sign in" οnclick="login()"> <a href="./register"><input class="btn" type="button" value="register"></a> </div> </div> </div> </div> <div class="footer">©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. Generate a validation String code=ValidationNumber.getStr(); //Store the verification in the session HttpSession session=request.getSession(true); session.setAttribute("code", code); //2. Generate a picture through verification BufferedImage img=ValidationNumber.creatImage(code); //3. Send pictures to the front end 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 { //Declare a String string static String valid="0123456789asdfghjklqwertyuiopzxcvbnmASDFGHJKLZXCVBNMQWERTYUIOP"; //Randomly generated string public static String getStr(){ //1. Initialize a variable string StringBuilder str=new StringBuilder(); //2. Get the character of string through random function Random ranodm= new Random(); for (int i = 0; i <4; i++) { //1. Generate random data 0-valisd.length-1; int num=ranodm.nextInt(valid.length()); char c=valid.charAt(num); //2. Append string str.append(c); } return str.toString(); } //Create a picture with verification code public static BufferedImage creatImage(String str){ int width=100; int height=33; //Create an empty picture BufferedImage img=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); //2 get the context of the current picture Graphics g=img.getGraphics(); //3 set the background color of the picture g.setColor(Color.gray); g.fillRect(0, 0, width, height); //Draw text g.setColor(Color.GREEN); g.setFont(new Font("Song style", 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. Receive the data sent by the client String username=req.getParameter("username"); String pwd=req.getParameter("pwd"); String code=req.getParameter("code"); System.out.println("code"+code); //2. Processing data HttpSession se=req.getSession(true); //Verify that the code is correct 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)){//Tell validation error code: 1001 MSG: login succeeded map.put("code", "1001"); map.put("msg","Validation Failure");//Here's normal Chinese, but when it comes to page reception, it becomes garbled //Return the front-end json string 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. response resp.setContentType("text/html,charset:GBK"); HttpSession session=req.getSession(); session.setAttribute("user", 1); map.put("code","1000"); map.put("msg", "Login successfully"); resp.getWriter().print( JSON.toJSON(rs)); resp.getWriter().flush(); } }
Click the verification code picture, and you can refresh it