get ready
New module 16_json_ajax_i18n and create a Tomcat instance
1. What is JSON?
JSON (JavaScript object Notation) is a lightweight data exchange format. Easy to read and write. It is also easy to machine parse and generate. JSON adopts a text format completely independent of language, and many languages provide support for JSON (including C, 2 + +, C, Java, JavaScript, Perl, python, etc.). This makes JSON an ideal data exchange format.
json is a lightweight data exchange format.
Lightweight means comparing with xml.
Data exchange refers to the transmission format of business data between client and server;
1.1. Use of JSON in JavaScript.
1.1.1 definition of json
json consists of key value pairs and is surrounded by curly braces (braces). Each key is enclosed by quotation marks, keys and values are separated by colons, and multiple sets of key value pairs are separated by commas.
1.1.2. json access
json itself is an object.
The key in json can be understood as an attribute in an object.
The key access in json is the same as accessing the properties of the object; json object.key
1.1.3. Two common methods of json
json exists in two forms
One is that the object exists in the form of a json object.
One is that it exists in the form of string, which we call json string.
Generally, when we want to manipulate the data in json, we need the format of json object.
Generally, when we want to exchange data between the client and the server, we use json strings.
JSON.stringify()
Convert json objects to json strings
JSON.parse()
Convert json string to json object
demonstration
New web/script / copy JQuery.js
New web/json.html
<!DoCTYPE html PUBLIC "-//w3c//DTD HTML 4.@1 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache"/> <meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="Expires" content="e"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> //Definition of json var jsonObj={ "key1":12, "key2":"abc", "key3":true, "key4":[11,"arr",false], "key5":{ "key5_1":551, "key5_2":"key5_2_value", }, "key6":[{ "key6_1_1":6611, "key6_1_2":"key6_1_2_value", },{ "key6_2_1":6621, "key6_2_2":"key6_2_2_value", }] }; //json access // alert(typeof (jsonObj));// object json is an object // alert(jsonObj.key1);//12 // alert(jsonObj.key2); // alert(jsonObj.key3); // alert(jsonObj.key4);// Get array //Traversal of array values in json // for (var i=0;i<jsonObj.key4.length;i++){ // alert(jsonObj.key4[i]); // } // alert(jsonObj.key5.key5_1);//551 // alert(jsonObj.key5.key5_2);//key5_2_value // alert(jsonObj.key6);// Get JSON array //Each element taken out is a JSON object // var jsonItem=jsonObj.key6[0]; // alert(jsonItem.key6_1_1);//6611 // alert(jsonItem.key6_1_2);//key6_1_2_value //json object to string // alert(jsonObj);//object var jsonObjString=JSON.stringify(jsonObj);//Especially like toString of objects in Java // alert(jsonObjString);//{"key1":12,"key2":"abc","key3":true,"key4":[11,"arr",false], // "key5":{"key5_1":551,"key5_2":"key5_2_value"},"key6":[{"key6_1_1":6611,"key6_1_2":"key6_1_2_value"}, // {"key6_2_1":6621,"key6_2_2":"key6_2_2_value"}]} // json string to json object var jsonObj2=JSON.parse(jsonObjString); alert(jsonObj2.key1);//12 alert(jsonObj2.key2);//abc </script> </head> <body> </body> </html>
1.2. Use of JSON in java
Import gson.jar into WEB-INF/lib and Add as Library
gson-2.2.4.jarFree download
1.2.1. Conversion between JavaBean and json
1.2.2. Conversion between list and json
1.2.3. Transformation between map and json
demonstration
New src/com.pojo/Person
package com.pojo; public class Person { private Integer id; private String name; public Person() { } public Person(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
New com/json/PersonListType
package com.json; import com.google.gson.reflect.TypeToken; import com.pojo.Person; import java.util.ArrayList; public class PersonListType extends TypeToken<ArrayList<Person>> { }
New com/json/PersonMapType
package com.json; import com.google.gson.reflect.TypeToken; import com.pojo.Person; import java.util.HashMap; public class PersonMapType extends TypeToken<HashMap<Integer,Person>> { }
New com/json/JsonTest
package com.json; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.pojo.Person; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JsonTest { // 1.2.1. Conversion between JavaBean and json @Test public void test1(){ Person person=new Person(1,"I'm so handsome"); //Create a Gson object instance Gson gson=new Gson(); //The toJson method can convert java objects into JSON strings String personJsonString = gson.toJson(person); System.out.println(personJsonString);//{"id":1,"name": "I'm so handsome"} //The fromJson method can convert JSON strings back to java objects //The first parameter is the JSON string //The second parameter is the java object type converted back Person person1 = gson.fromJson(personJsonString, Person.class); System.out.println(person1);//Person{id=1, name = 'I'm so handsome'} } // 1.2.2. Conversion between list and json @Test public void test2(){ List<Person> personList=new ArrayList<>(); personList.add(new Person(1,"Guoge")); personList.add(new Person(2,"a brand of instant noodles")); Gson gson=new Gson(); //Convert List to JSON string String personListJsonString = gson.toJson(personList); System.out.println(personListJsonString);//[{"id":1,"name": "Guoge"}, {"id":2,"name": "Master Kang"}] //FALSE // List<Person> list = gson.fromJson(personListJsonString, personList.getClass()); // System.out.println(list);//[{id=1.0, name = Guoge}, {id=2.0, name = Master Kang}] // Person person = list.get(0);//ClassCastException // System.out.println(person); List<Person> list = gson.fromJson(personListJsonString,new PersonListType().getType()); System.out.println(list);//[{id=1.0, name = Guoge}, {id=2.0, name = Master Kang}] Person person = list.get(0); System.out.println(person);//Person{id=1, name = 'Guoge'} } // 1.2.3, map and json mutual conversion @Test public void test3(){ Map<Integer,Person> personMap=new HashMap<>(); personMap.put(1,new Person(1,"I'm so handsome")); personMap.put(2,new Person(2,"You're handsome, too")); Gson gson=new Gson(); String personMapJsonString = gson.toJson(personMap); System.out.println(personMapJsonString);//{"1":{"id":1,"name": "I'm so handsome"}, "2":{"id":2,"name": "you're so handsome"}} // Map<Integer,Person> personMap2 =gson.fromJson(personMapJsonString, new PersonMapType().getType()); Map<Integer,Person> personMap2 =gson.fromJson(personMapJsonString, new TypeToken<HashMap<Integer,Person>>(){}.getType());//Anonymous inner class object System.out.println(personMap2);//{1=Person{id=1, name = 'I'm so handsome'}, 2=Person{id=2, name = 'you're so handsome'}} Person person = personMap2.get(1); System.out.println(person);//Person{id=1, name = 'I'm so handsome'} } }
2. AJAX request
2.1. What is AJAX request
AJAX, namely "Asynchronous Javascript And XML", refers to a web development technology for creating interactive web applications.
ajax is a technology that the browser asynchronously initiates a request to update the page locally through js.
The browser address bar will not change for partial updates requested by Ajax
Partial updates do not discard the contents of the original page
Asynchrony is self executing. Don't wait for other execution
2.2. Instance of native Ajax request
api
demonstration
New web/ajax.html
<!DOCTYPE html PUBLIC "-//W3c//DTD HTML 4.01 Transitional//eN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache"/> <meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="Expires" content="e"/> <meta http-equiv="Content-Type" content="text/html; charset=UtF-8"> <title>Insert title here</title> <script type="text/javascript"> //Here, we use JavaScript language to initiate Ajax requests and access JavaScript Ajax in the server Ajax servlet function ajaxRequest() { // 1. First, we need to create XMLHttpRequest var xmlhttprequest=new XMLHttpRequest(); // 2. Call the open method to set the request parameters xmlhttprequest.open("GET","http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=javaScriptAjax",true) // 4. Bind the onreadystatechange event before the send method to handle the operation after the request is completed. xmlhttprequest.onreadystatechange=function (){ if (xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200){ // alert(xmlhttprequest.responseText); var jsonObj=JSON.parse(xmlhttprequest.responseText); //Display the response data on the page // document.getElementById("div01").innerHTML=xmlhttprequest.responseText; document.getElementById("div01").innerHTML="No.:"+jsonObj.id+",full name:"+jsonObj.name; } } // 3. Call the send method to send the request xmlhttprequest.send(); } </script> </head> <body> <button onclick="ajaxRequest()">ajax.Request</button> <div id="div01"> </div> </body> </html>
Create com/servlet/BaseServlet and import servlet-api.jar
package com.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method; public abstract class BaseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Solve the Chinese garbled code problem of post request //The call must be valid until the request parameter is obtained. req.setCharacterEncoding("UTF-8"); //Resolve response garbled code resp.setContentType("text/html;charset=UTF-8"); String action=req.getParameter("action"); // System.out.println(action); //The value of action is consistent with the method name called // if ("login".equals(action)){ System.out.println("Handle login requirements"); // login(req,resp); // }else if ("regist".equals(action)){ System.out.println("Handle registration requirements"); // regist(req,resp); // } //reflex try { //Obtain the action business authentication string and the corresponding business method reflection object Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class); //Call target business method method.invoke(this,req,resp); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e);//Throw exception to Filter } } }
Create servlet / Ajax Servlet
package com.servlet; import com.google.gson.Gson; import com.pojo.Person; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AjaxServlet extends BaseServlet{ protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Ajax The request came"); Person person=new Person(1,"Guoge"); //json format string Gson gson=new Gson(); String personJsonString = gson.toJson(person); resp.getWriter().write(personJsonString); } }
Configure web.xml
<servlet> <servlet-name>AjaxServlet</servlet-name> <servlet-class>com.servlet.AjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxServlet</servlet-name> <url-pattern>/ajaxServlet</url-pattern> </servlet-mapping>
2.3 AJAX request in jQuery
$.ajax method url Indicates the address of the request type Indicates the type of request GET or POST request data Represents data sent to the server There are two formats: one:name=value&name=value two:{key:value} success Callback function of response after successful request dataType Data type of response Common data types: text Represents plain text xml express xml data json express json object
$.get Methods and $.post method(than $.ajax One is missing type) url Requested url address data Data sent callback Successful callback function type Data type returned
$.getJSON method url Requested url address data Data sent callback Successful callback function
Form serialization (serialize)
serialize() can get the contents of all form items in the form and splice them in the form of name = value & name = value.
demonstration
Modify Ajax Servlet
package com.servlet; import com.google.gson.Gson; import com.pojo.Person; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AjaxServlet extends BaseServlet{ protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Ajax The request came"); Person person=new Person(1,"Guoge"); //json format string Gson gson=new Gson(); String personJsonString = gson.toJson(person); resp.getWriter().write(personJsonString); } protected void jQueryAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQueryAjax == Method called"); Person person=new Person(1,"Guoge"); //json format string Gson gson=new Gson(); String personJsonString = gson.toJson(person); resp.getWriter().write(personJsonString); } protected void jQueryGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQueryGet == Method called"); Person person=new Person(1,"Guoge"); //json format string Gson gson=new Gson(); String personJsonString = gson.toJson(person); resp.getWriter().write(personJsonString); } protected void jQueryPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQueryPost == Method called"); Person person=new Person(1,"Guoge"); //json format string Gson gson=new Gson(); String personJsonString = gson.toJson(person); resp.getWriter().write(personJsonString); } protected void jQueryGetJSON(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQueryGetJSON == Method called"); Person person=new Person(1,"Guoge"); //json format string Gson gson=new Gson(); String personJsonString = gson.toJson(person); resp.getWriter().write(personJsonString); } protected void jQuerySerialize(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQuerySerialize == Method called"); System.out.println("user name:"+req.getParameter("username")); System.out.println("password:"+req.getParameter("password")); Person person=new Person(1,"Guoge"); //json format string Gson gson=new Gson(); String personJsonString = gson.toJson(person); resp.getWriter().write(personJsonString); } }
New web/Jquery_Ajax_request.html
<!DOCTYPE html PUBLIE "-//w3c//DTD HTML 4.O1 Transitional//EN" "http://www.w3.org/TR/htm14"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="Expires" content="0"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="script/jquery.js"></script> <script type="text/javascript"> $(function() { //ajax request $("#ajaxBtn").click(function () { $.ajax({ url:"http://localhost:8080/16_json_ajax_i18n/ajaxServlet", // data:"action=jQueryAjax", data:{action:"jQueryAjax"}, type:"GET", success:function (data) {//Parameters must have // alert("the data returned by the server is" + data); // var jsonObj=JSON.parse(data) // $("#msg").html("No.: + jsonObj.id +", sexual name; "+ jsonObj.name); $("#msg").html("ajax No.: + data.id + ", sex name;" + data. Name "); }, // dataType:"text" dataType:"json" }); }); //ajax--get request $("#getBtn").click(function () { url="http://localhost:8080/16_json_ajax_i18n/ajaxServlet"; data="action=jQueryGet"; callback=function (data) { $("#msg").html("get No.: + data.id + ", sexual name;" + data. Name "); }; type="json"; $.get(url,data,callback,type); }); //ajax--post request $("#postBtn").click(function () { $.post("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryPost",function (data) { $("#msg").html("post No.: + data.id + ", sex name;" + data. Name "); },"json"); });//ajax--jQueryGetJSON request $("#getJSONBtn").click(function () { $.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryGetJSON",function (data) { $("#msg").html("getJSON No.: + data.id + ", sex name;" + data. Name "); }); }); //ajax request $("#submit").click(function (){ //Serialize parameters // alert($("#form01").serialize()); $.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQuerySerialize&"+$("#form01").serialize(),function (data) { $("#msg").html("Serialize No.: + data.id + ", sex name;" + data. Name "); }) }); }); </script> </head> <body> <div> <button id="ajaxBtn">$.ajax request</button> <button id="getBtn">$.get request</button> <button id="postBtn">$.post request</button> <button id="getJSONBtn">$.getJSoN request</button> </div> <div id="msg"> </div> <br/><br/> <form id="form01" > user name:<input name="username" type="text" /><br/> password:<input name="password" type="password" /><br/> Drop down radio:<select name="single"> <option value="Single">Single</option> <option value="Single2">Single2</option> </select><br/> Drop down multiple selection:<select name="multiple"> <option selected="selected" value="Multiple1">Multiple1</option> <option value="Multiple2">Multiple2</option> <option selected="selected" value="Multiple3">Multiple3</option> </select><br/> check: <input type="checkbox" name= "check" value="check1"/> check1 <input type="checkbox" name="check" value="check2" checked="checked"/>check2<br/> Single choice: <input type="radio" name="radio" value="radio1" checked="checked"/> radio1 <input type="radio" name="radio" value="radio2"/>radio2<br/> </form> <button id="submit">Submit--serialize()</button> </body> </html>
3. Book city project phase IX
Import gson-2.2.4.jar package
3.1. Use AJAX to verify whether the user name is available
Modify register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Shang Silicon Valley member registration page</title> <%--Static inclusion base label, css Style, jquery file --%> <%@ include file="/pages/common/head.jsp"%> <script type="text/javascript"> //After the page is loaded $(function () { $("#username").blur(function (){ //1 get user name var username=this.value; $.getJSON("http://localhost:8080/book/userServlet","action=ajaxExistsUsername&username="+username,function (data){ // console.log(data); if (data.existsUsername){ $("span.errorMsg").text("User name already exists!"); }else { $("span.errorMsg").text("User name available!"); } }); }); //For the picture of the verification code, bind the click event $("#code_img").click(function (){ //There is a this object in the function function of the event response. This this object is the dom object that is currently responding to the event //src indicates the picture path of the verification code img tag. It is readable and writable. // alert(this.src); this.src="${basePath}kaptcha.jpg?d="+new Date(); }); //Click event to register binding $("#sub_btn").click(function () { //Authentication user name: it must be composed of letters, numbers and underscores, and the length is 5 to 12 digits //1 get the content in the user name input box var usernameText=$("#username").val(); //2 create regular expression object var usernamePatt=/^\w{5,12}$/; //3. test method verification if(!usernamePatt.test(usernameText)){ //4 prompt user for results $("span.errorMsg").text("Illegal user name!"); return false; } //Verification password: it must be composed of letters, numbers, underscores and 5 to 12 digits in length //1 get the content in the user name input box var passwordText=$("#password").val(); //2 create regular expression object var passwordPatt=/^\w{5,12}$/; //3. test method verification if(!passwordPatt.test(passwordText)){ //4 prompt user for results $("span.errorMsg").text("Illegal password!"); return false; } //Verify and confirm password: same as password //1 get the content of the confirmation password var repwdText=$("#repwd").val(); //2 compare with password if (repwdText!=passwordText){ //3 prompt user $("span.errorMsg").text("The confirmation password and password are inconsistent!"); return false; } //Mailbox validation: xxxxx@xxx.com //1 get the content in the mailbox var emailText=$("#email").val(); //2 create regular expression object var emailPatt=/^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/; //3. test method verification if(!emailPatt.test(emailText)){ //4 prompt user for results $("span.errorMsg").text("Illegal email format!"); return false; } //The verification code now only needs to verify that the user has entered. Because we haven't talked about the server yet. Verification code generation. var codeText=$("#code").val(); //Remove the space before and after the verification code alert("Before going to the space["+codeText+"]"); codeText=$.trim(codeText); alert("After removing the space["+codeText+"]"); if (codeText==null||codeText==""){ //Prompt user for results $("span.errorMsg").text("Verification code cannot be empty"); return false; } $("span.errorMsg").text(""); }); }); </script> <style type="text/css"> .login_form { height: 420px; margin-top: 25px; } </style> </head> <body> <div id="login_header"> <img class="logo_img" alt="" src="static/img/logo.gif"> </div> <div class="login_banner"> <div id="l_content"> <span class="login_word">Welcome to register</span> </div> <div id="content"> <div class="login_form"> <div class="login_box"> <div class="tit"> <h1>Registered Silicon Valley member</h1> <span class="errorMsg"> <%-- <%=request.getAttribute("msg")==null?"":request.getAttribute("msg")%>--%> ${requestScope.msg} </span> </div> <div class="form"> <form action="userServlet" method="post"> <input type="hidden" name="action" value="regist"/> <label>User name:</label> <input class="itxt" type="text" placeholder="enter one user name" <%-- value="<%=request.getAttribute("username")==null?"":request.getAttribute("username")%>"--%> value="${requestScope.username}" autocomplete="off" tabindex="1" name="username" id="username"/> <br/> <br/> <label>User password:</label> <input class="itxt" type="password" placeholder="Please input a password" autocomplete="off" tabindex="1" name="password" id="password"/> <br/> <br/> <label>Confirm password:</label> <input class="itxt" type="password" placeholder="Confirm password" autocomplete="off" tabindex="1" name="repwd" id="repwd"/> <br/> <br/> <label>E-mail:</label> <input class="itxt" type="text" placeholder="Please enter email address" <%-- value="<%=request.getAttribute("email")==null?"":request.getAttribute("email")%>"--%> value="${requestScope.email}" autocomplete="off" tabindex="1" name="email" id="email"/> <br/> <br/> <label>Verification Code:</label> <input class="itxt" type="text" name="code" style="width: 80px;" id="code"/> <%-- <img alt="" src="kaptcha.jpg" style="float: right;margin-right: 40px;width: 100px;height: 28px;">--%> <img id="code_img" alt="" src="kaptcha.jpg" style="width: 110px;height: 30px;"> <br/> <br/> <input type="submit" value="register" id="sub_btn"/> </form> </div> </div> </div> </div> </div> <%--Static include footer content--%> <%@include file="/pages/common/footer.jsp"%> </body> </html>
Modify UserServlet
package com.atguigu.web; import com.atguigu.pojo.User; import com.atguigu.service.UserService; import com.atguigu.service.impl.UserServiceImpl; import com.atguigu.utils.WebUtils; import com.google.gson.Gson; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY; public class UserServlet extends BaseServlet { private UserService userService = new UserServiceImpl(); /** * Logout (logout) * @param req * @param resp * @throws ServletException * @throws IOException */ protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1. Destroy the user login information in the Session (or destroy the Session) req.getSession().invalidate(); // 2. Redirect to the home page (or login page). resp.sendRedirect(req.getContextPath()); } /** * Function of handling login * @param req * @param resp * @throws ServletException * @throws IOException */ protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. Get requested parameters String username = req.getParameter("username"); String password = req.getParameter("password"); //2. Call XxxService.xxx() to process business User loginUser = userService.login(new User(null, username, password, null)); //If it is equal to null, the login fails if (loginUser==null){ // Save the error information and the echoed form item information to the Request field req.setAttribute("msg","Wrong user name or password!"); req.setAttribute("username",username); // Jump back to login page req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp); }else { // success //Save user login information req.getSession().setAttribute("user",loginUser); // Jump to the success page login_success.jsp req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp); } } /** * Function of processing registration * @param req * @param resp * @throws ServletException * @throws IOException */ protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get the verification code in the Session String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY); //Delete the verification code in the Session req.getSession().removeAttribute(KAPTCHA_SESSION_KEY); // 1. Get requested parameters String username = req.getParameter("username"); String password = req.getParameter("password"); String email = req.getParameter("email"); String code = req.getParameter("code"); // Map<String, String[]> parameterMap = req.getParameterMap(); // for (Map.Entry<String, String[]> entry:parameterMap.entrySet()) { // System.out.println(entry.getKey()+"="+ Arrays.asList(entry.getValue())); // } // User user=new User(); // WebUtils.copyParamToBean(req,user); / / inject assignment, corresponding to setXxx in User class User user = WebUtils.copyParamToBean(req.getParameterMap(),new User());//Injection assignment, corresponding to setXxx in User class // 2. Check whether the verification code is correct = = = write dead. The verification code is required to be: abcde if (token!=null&&token.equalsIgnoreCase(code)){ // 3. Check that the user name is available if (userService.existsUsername(username)){ System.out.println("user name["+username+"]Already exists!"); // Save the echo information to the Request field req.setAttribute("msg","User name already exists!!"); req.setAttribute("username",username); req.setAttribute("email",email); // Jump back to the registration page req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp); }else { // Save available Service calls to the database userService.registUser(new User(null,username,password,email)); // Skip to register_success.jsp req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp); } }else { // Save the echo information to the Request field req.setAttribute("msg","Verification code error!!"); req.setAttribute("username",username); req.setAttribute("email",email); System.out.println("Verification Code["+code+"]Wrong,"); req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp); } } protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get the requested parameter username String username=req.getParameter("username"); //Call userService.existsUsername(); boolean existsUsername = userService.existsUsername(username);//Here, rename the original existUsername -- "existsUsername" //Encapsulate the returned result as a map object Map<String,Object> resultMap=new HashMap<>(); resultMap.put("existsUsername",existsUsername); Gson gson=new Gson(); String json = gson.toJson(resultMap); resp.getWriter().write(json); } }