On the project registration page, you need to determine whether the user name exists. This method is implemented using the remote method of the jquery verification framework.
1. js script:
Jquery. validator. addmethod ("usename", function (value, element ){
Return this. Optional (element) | value. length> = 4
& Value. Length <= 12 & (// D/. Test (value) |/[A-Z]
/I. Test (value) ;}, "the user name should contain 4-12 numbers and letters ");
$ ("Form"). Validate ({
Rules :{
Username :{
Required: True,
Remote: "checkuseravailable. Action" // check whether the user name exists.
}
},
Messages :{
Username :{
Required: "Enter the user name ",
Remote: "This user name has been registered" // Div displayed on the page when false is returned in the background
}
}
});
2. Java code:
Because jquery's remote method only allows true or false to be returned, when false is returned, the message content is output: "This user name has been registered ". There are two methods to implement struts2:
(1) using the response instance of the httpservletresponse object, the Java code is as follows:
String text = "true ";
If (memberservice. findbyusername (member. GetUserName ())! = NULL ){
TEXT = "false"; // if the user name already exists, false is output.
}
Httpservletresponse response = servletactioncontext. getresponse ();
Response. setcontenttype ("text/plain; charset = UTF-8 ");
Response. getwriter (). Write (text );
Return NULL;
Struts. xml configuration: you do not need to configure the <result> output item. The disadvantage of this method is that it depends on httpservletresponse.
(2) stream return type using struts2:
Boolean cansign = true;
// Whether the user name exists in the Database
If (memberservice. findbyusername (member. GetUserName ())! = NULL ){
Cansign = false; // indicates that the API exists and false is returned.
}
Inputstream = new bytearrayinputstream (cansign. tostring (). getbytes (); // convert true or false to a stream and provide the getter Method for inputstream.
Return success;
Struts. xml configuration:
<Result type = "stream">
<Param name = "contenttype"> text/plain </param>
<Param name = "inputname"> inputstream </param>
</Result>
The above contenttype cannot use the text/html type, or you do not need to configure this item. The default value is the text/plain type.