Use jquery-JSP to interact with Servlet data

Source: Internet
Author: User

Anyone who has experience in Java Web development knows that there are a variety of data interactions between JSP and Servlet, but the most common one is form submission (I am not wrong here -,-), use the action of the form tag in JSP to specify the destination of the form data to be sent. In the specified sending method (get or post), click submit, and use request on the servlet side. getparameter (key) is received, so that the data interaction between JSP and servlet can be achieved. The method I want to talk about today is to use the Ajax part of jquery to interact with servlet.

Anyone familiar with jquery knows that jquery itself is a lightweight JavaScript framework and can be said to be a good encapsulation of JavaScript. the most subtle of them is the simplification of Ajax operations... Easy to use. If you have to pick something wrong, I think there is only one thing (you should ....) : That is not conducive to learning for beginners, because jquery simplifies this part too easily. For beginners who want to know its internal implementation, it is impossible for them to do so, but I don't know why. Okay. You don't have to talk about it anymore. Just get started with the question.

Jquery's Ajax operations are mainly embodied in the following methods: $. get (), $. post (), $. ajax (). where $. ajax () is hard to understand and use. As for other methods, you can go to W3C or learn through other channels. Here I will not go into detail (in fact, I want to be lazy ..., i'm sure no one has sprayed it )~~~ Okay. Let's talk about the first $. Get ().

$. Get () is actually the same as when you use Form to submit data. There are several parameters in it:

URL Required. Specifies the URL of the request.
Data Optional. Specifies the data sent to the server together with the request.
Success (response, status, xhr)

Optional. Specifies the function that runs when the request is successful.

Additional parameters:

  • Response-contains the result data from the request
  • Status-contains the Request status
  • Xhr-contains XMLHTTPRequest object
Datatype

Optional. Specifies the expected server response data type.

By default, jquery performs intelligent judgment.

Possible types:

  • "XML"
  • "Html"
  • "Text"
  • "Script"
  • "JSON"
  • "Jsonp"

His usage method, eg:

$.get("demo_ajax_load.txt", function(result){    $("div").html(result);  });

The usage of $. Post () is similar to that of get, but there is not much difference.

Syntax
jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)
Parameters Description
URL Required. Specifies the URL to which the request is sent.
Data Optional. Ing or string value. Specifies the data sent to the server together with the request.
Success (data, textstatus, jqxhr) Optional. The callback function executed when the request is successful.
Datatype

Optional. Specifies the expected server response data type.

Intelligent judgment (XML, JSON, script, or HTML) is performed by default ).

Instance used:

$.post("demo_ajax_gethint.asp",{suggest:txt},function(result){    $("span").html(result);  });

Now, let's focus on the $. Ajax () method. The previous two methods can be extended from this method, simplified and evolved. Next, let's take a look at the syntax and parameters of $. Ajax.

Syntax
jQuery.ajax([settings])
Parameters Description
Settings

Optional. Set of key-value pairs used to configure Ajax requests.

You can use $. ajaxsetup () to set the default values of any options.

Example:

$.ajax({ url: "test.html", context: document.body, success: function(){        $(this).addClass("done");      }});

For more detailed parameter information, you can click this link to pre-read: Begin.

Okay. For example, I have a JSP file searchvender. jsp. There are several input boxes:

<Div class = "registerinput" style = "display: none; margin-top: 40px;"> <form style = "margin-Right: 50px; text-align: right; "> <label style =" font-size: 1em "> name </label> <input type =" text "name =" registername "Title =" Enter your real name "> <br> <label style =" font -Size: 1em "> email </label> <input type =" text "name =" registeremail "Title =" Enter the email address in the following format: xxx@xxx.com/CN "> <br> <label style =" font-size: 1em "> password </label> <input type =" passwo Rd "name =" registerpassword "Title =" enter the password. The password cannot contain invalid letters, such as: #, $ ,&... "> <br> <label style =" font-size: 1em "> contact </label> <input type =" text "name =" registerconnect "Title =" Enter the contact name "> <br> <label style =" font-size: 1em "> contact number </label> <input type =" text "name =" registerphone "Title =" Enter the contact's phone number "> <br> <label style =" font-size: 1em "> address </label> <input type =" text "name =" registeraddress "Title =" Enter your current residential address "> <br> <label styl E = "font-size: 1em "> zip code </label> <input type =" text "name =" registerpost "Title =" Enter the zip code of your current residential address "> </form> <! -- <Input type = "button" name = "yes" value = "OK" style = "margin-top: 30px;"> --> </div>

There is also a click button

The code in the script, When I click the button

function usertoregister(){var name=$("input[name='registername']").val().trim();var email=$("input[name='registeremail']").val().trim();var password=$("input[name='registerpassword']").val().trim();var connect=$("input[name='registerconnect']").val().trim();var phone=$("input[name='registerphone']").val().trim();var address=$("input[name='registeraddress']").val().trim();var post=$("input[name='registerpost']").val().trim();var obj=new registerobj(name,password,email,connect,phone,address,post);var jsonstring=JSON.stringify(obj);$.ajax({type:"POST",url:"SearchVenderRegisterServlet",async:false,data:jsonstring+"\n",success:function(data,textStatus){if(textStatus=="success"){alert(data);$("#loginorregister").dialog("close");}}});}

The usertoregister () method is called. This method first obtains the values in each input box.

var name=$("input[name='registername']").val().trim();var email=$("input[name='registeremail']").val().trim();var password=$("input[name='registerpassword']").val().trim();var connect=$("input[name='registerconnect']").val().trim();var phone=$("input[name='registerphone']").val().trim();var address=$("input[name='registeraddress']").val().trim();var post=$("input[name='registerpost']").val().trim();

Then generate a JavaScript Object

var obj=new registerobj(name,password,email,connect,phone,address,post);

Of course, you have to declare this object in JavaScript.

function registerobj(name,password,email,connect,phone,address,post){    this.name=name;    this.password=password;    this.email=email;    this.connect=connect;    this.phone=phone;    this.address=address;    this.post=post;    }

Then convert the JavaScript Object To a json string.

var jsonstring=JSON.stringify(obj);

Next we will use today's leading role, $. Ajax,

$.ajax({type:"POST",url:"SearchVenderRegisterServlet",async:false,data:jsonstring+"\n",success:function(data,textStatus){if(textStatus=="success"){alert(data);$("#loginorregister").dialog("close");}}});

The parameter meanings in this part of the Code are:

Type indicates the method in which data is sent. There are two methods: Get and post. If we do not declare the method, the system will automatically help us determine.

async:false,

It indicates whether the request is asynchronous or synchronous. True indicates asynchronous, and false indicates synchronous. The default value is true.

data:jsonstring+"\n",

The data YOU WANT TO TRANSMIT

success:function(data,textStatus){if(textStatus=="success"){alert(data);$("#loginorregister").dialog("close");}}

The function executed when the request is successful. data indicates the returned data, and textstatus indicates the returned status: "success", "fail"

The JSP code has been read. Let's take a look at the servlet code.

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");response.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();String json=getJsonString(request);System.out.println(json);JSONObject jsonObject=JSONObject.fromObject(json);User user=(User) JSONObject.toBean(jsonObject, User.class);System.out.println("username:"+user.getName());out.write("success");out.flush();out.close();}protected String getJsonString(HttpServletRequest request){StringBuffer json=new StringBuffer();try {String line=null;BufferedReader reader = request.getReader();while((line=reader.readLine())!=null){json.append(line);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return json.toString();}

In the next step, we need to import the JSON jar package and its auxiliary package. If you need it, you can download it from my resources.
I have uploaded it, and I have nothing to say about other code. It's just some simple stream operations, mainly these two sentences.

JSONObject jsonObject=JSONObject.fromObject(json);User user=(User) JSONObject.toBean(jsonObject, User.class);

The first sentence is to convert a JSON string into a JSON object, and the second sentence is to convert a JSON object into a Java object. Of course, there is no doubt that we must also have a corresponding Java object.

public class User {private String name=null;private String password=null;private String email=null;private String connect=null;private String phone=null;private String address=null;private String post=null;public User(String name, String password, String email, String connect,String phone, String address, String post) {this.name = name;this.password = password;this.email = email;this.connect = connect;this.phone = phone;this.address = address;this.post = post;}public User() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getConnect() {return connect;}public void setConnect(String connect) {this.connect = connect;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getPost() {return post;}public void setPost(String post) {this.post = post;}}

Now, all the code is complete ~~~ Haha... Float, sleep ....

Related Article

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.