Use ajax in struts2 to verify whether a mailbox (user name) is registered
Action class:
Package com. grace. myblog. view. action; import java. io. printWriter; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. struts2.ServletActionContext; import org. springframework. stereotype. controller; import com. grace. myblog. domain. user; @ Controllerpublic class EmailCheckAction {/*****/private static final long serialVersionUID = 1L; public String execute () throws Exception {try {String responseText = ""; httpServletRequest request = ServletActionContext. getRequest (); String email = request. getParameter ("email"); System. out. println ("---" + email); User user = registerService. findByEmail (email); // query the database by email to determine whether the mailbox has been registered if (user = null) {responseText = "2 ";} else {responseText = "1";} HttpServletResponse response = ServletActionContext. getResponse (); response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter (); out. print (responseText); out. flush (); out. close ();} catch (Exception e) {e. printStackTrace ();} return null ;}}
Code in js
Function checkUserMail () {/* email check ajax */var email = document. getElementById ("email "). value; var xhr = ajaxFunction (); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {var data = xhr. responseText; // obtain the text if (data = "1") {document. getElementById ("emailcheck "). innerHTML = "this email address has been registered"; return false;} else {document. getElementById ("emailcheck "). innerHTML = "congratulations, this email has not been registered"; return true ;} }}} Xhr. open ("get", "emailCheck. action? Email = "+ email, true); xhr. setRequestHeader (" Content-type "," application/x-www-form-urlencoded "); xhr. send ();}
function ajaxFunction(){ var xmlHttp; try{ // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e){ try{// Internet Explorer xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } }return xmlHttp; }
Sturts. xml configuration
/* Use the annotation method, so the default class name is lower-case first letter */
You only need to add the following line of code to the jsp page where you want to display the prompt.