Struts2 + Ajax checks whether the user name is unique.

Source: Internet
Author: User

Struts2 + Ajax checks whether the user name is unique.

After two days, I finally figured out how to use Ajax in the Struts2 framework to detect the existence of user names. Although the speed is really slow compared to those of the experts, it is still a sense of accomplishment.

Let's rest and get down to the truth. Directly run the Code:

Action:

1 package com. bbs. action; 2 3 import javax. servlet. http. httpServletRequest; 4 import javax. servlet. http. httpServletResponse; 5 import org. apache. struts2.ServletActionContext; 6 7 import com. bbs. model. *; 8 import com. opensymphony. xwork2. *; 9 10 @ SuppressWarnings ("serial") 11 public class CheckUser extends ActionSupport {12 // private String username; 13 public String execute () throws Exception {14 HttpServletRequest req = ServletActionContext. getRequest (); 15 HttpServletResponse res = ServletActionContext. getResponse (); 16 String username = req. getParameter ("username"); 17 res. setContentType ("text/html; charset = UTF-8"); 18 String responseStr = ""; 19 UserDAO udao = new UserMySQLDAO (); 20 if (udao. valiUserByName (username) {21 res. getWriter (). print ("exists"); 22} else {23 responseStr = "you can use this user name"; 24 res. getWriter (). print (responseStr); 25} 26 return null; 27} 28}

The package in the first line is my own Action package. Many examples on the Internet are JavaScript communication with JSP or Servlet communication, but there are few examples of passing parameters with Action. However, I want JSP to be purely presented, and adding Servlet will destroy the original clear MVC Architecture. Therefore, I believe that my persistence is correct.

As for how to check whether the user name exists in the database, this is a very easy problem. I will not talk about it here. I will focus on how I am structured and other irrelevant details, or the explanations that can be searched in one search are ignored in a concise and concise manner.

JavaScript:

1 var req; 2 var span; 3 function Check (field) {4 span = document. getElementById ("result"); 5 if (field. value = '') {6 span. style. color = "red"; 7 span. innerHTML = "username cannot be blank"; 8 return false; 9} 10 if (window. XMLHttpRequest) {// other non-ie browsers support 11 req = new XMLHttpRequest (); 12} else if (window. activeXObject) {// Microsoft's IE supports 13 req = new ActiveXObject ("Microsoft. XMLHTTP "); 14} 15 16 req. onreadystatechange = press; 17 req. open ("POST", "http: // localhost: 8080/BBS/CheckUser? Username = "+ field. value, true); 18 req. setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); 19 req. send (""); 20} 21 22 function press () {23 if (req. readyState <4) {24 span. style. color = "blue"; 25 span. innerHTML = "detecting"; 26} 27 if (req. readyState = 4) {28 if (req. status = 200) {29 if (req. responseText = "exists") {30 span. style. color = "red"; 31 span. innerHTML = "username already exists"; 32} else {33 span. style. color = "green"; 34 span. innerHTML = "you can use this user name"; 35} 36} 37} 38}

This code is used to detect Ajax user names. Line 5-9 is the code for detecting empty user names. It is easy to understand. The focus is on the subsequent parts. First, create an XMLHttpRequest object, which is the core part of Ajax implementation and can only be used

Send a request to the backend in two steps: Open the connection and send the request.

Open the connection using the open method.

The prototype of the open method is open ("method", "URL", [, asyncFlag [, "userName" [, "password"]).

Method: POST/GET. The differences between the two methods are not described in detail. Note that there must be double quotation marks. I did not add any quotation marks, so I found the reason for it for a long time and sweated.

AsyncFlag: true indicates asynchronous, which should be selected in general; false indicates synchronization.

The following username and password are used for some remote services.

Send a request using the send method.

Send (content); // content is the request parameter. Generally, this parameter can be omitted.

SetRequestHeader (): Set the request header before sending.

The onreadystatechange parameter is used to set the corresponding callback function.

The following press is the callback function.

Descriptions of status are described below.

The span is used to show the statement after the user name input box.

HTML code:

1 <input  id="regusername" type="text" name="username" size="50" maxlength="12" value=""  autocomplete="off" onblur="Check(this)"/>    2 <span id = "result"></span>    

Action:

1 <package name="server" namespace="/"  extends="struts-default">2         <action name="CheckUser" class="com.bbs.action.CheckUser">3             <result name="success">Welcome.jsp</result>4             <result name="input">Register.jsp</result>5          </action>6 </package>

In fact, the result part here does not matter, because note that the last return value of the previous Action is null. Why is it null? Because the previous JavaScript section uses responseText to compare it with a string to produce different results.

If it is success or input, the redirected page (Welcome. jsp/Register. jsp) is directly returned. Here, I have been tossing for a long time.

In addition, although responseText is a string, in fact, it cannot be processed completely according to the string processing method. At the beginning, I used the equals function and didn't respond, then change to = to achieve the effect.

In a word, I am still satisfied with the effort, but I still feel that I am very good at cooking, but as long as I believe that I can do it, you will be able to do it. Do not be impatient when encountering difficulties. There will always be a solution. Although it is a bit chicken soup, I hope you will remember it.

Next, we plan to implement Ajax paging.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.