JQuery Ajax Process Full parsing

Source: Internet
Author: User

Original: http://www.cnphp6.com/archives/57826

Instance parsing Java + JQuery + JSON working process (login)

This article mainly explains the interactive process of JSON data transfer using jquery in Java environment.

Refer to the author's account Management System (Personal Edition) source code download explanation

I. Introduction of related technologies and tools

1. A brief introduction to JSON, JSON is a lightweight data interchange format. Easy for people to read and write. It is also easy for machine parsing and generation. The data is represented by the key-value pair form, and the data storage form of map in Java is similar, please refer to http://www.json.org/json-zh.html for details.

2, corresponding to the background JSON data processing tool Json-lib, contains a variety of format data tool classes, such as: JavaBean, arrays, sets (Collection), etc., reference API documentation.

3, the data representation of the jquery framework, if you are familiar with jquery, you will find that the use of jquery data transfer is in JSON format, for example, we often use the $.ajax method:

JS Code

    1. $.ajax ({
    2. Url:url,
    3. Data: {
    4. Id:chkvalue
    5. },
    6. Cache:false,
    7. DataType: "JSON",
    8. Success:function (Result) {
    9. alert (result);
    10. }
    11. );

where {...} represents data in JSON format

Second, the way of the front office

In order to be able to understand the system login to explain, the end will be an example of the way to explain

1. Login Page

Code See HTTP://CODE.GOOGLE.COM/P/FINANCE-P/SOURCE/BROWSE/TRUNK/LOGIN.JSP

Java code

    1. User name:
    2. <input id= "LoginName" name= "LoginName" size= "20″type=" text "/>
    3. Password:
    4. <input id= "password" name= "password" size= "20″type=" password "/>

2. login JavaScript File Login.js

JS Code

  1. /**
  2. * Set Form validation rules
  3. */
  4. function Regformvalidator () {
  5. $.formvalidator.initconfig ({formid: "LoginForm"});
  6. $ ("#loginName"). Formvalidator ({
  7. OnShow: "Please enter user name",
  8. onfocus: "User name at least 2 characters, up to 4 words"
  9. }). inputvalidator ({
  10. Min:1,
  11. OnError: "The user name you entered is illegal, please confirm"
  12. });
  13. $ ("#password"). Formvalidator ({
  14. OnShow: "Please enter your password"
  15. }). inputvalidator ({
  16. Min:6,
  17. OnError: "Password is more than 6, please confirm"
  18. });
  19. }
  20. $ (function () {
  21. Registration Form Validation Plug-in
  22. Regformvalidator ();
  23. $ (' #submit '). Click (function () {
  24. Verify that the user name and password you entered are correct
  25. var valid = JQuery.formValidator.pageIsValid (' 1′);
  26. if (valid) {
  27. $ (this). attr (' value ', ' Logging in ... '). attr (' disabled ', true);
  28. } else {
  29. Return
  30. }
  31. Send Request
  32. $.ajax ({
  33. URL: ' Login.do ',
  34. Data: {loginname:$ (' #loginName '). Val (), Password: $ (' #password '). Val ()},
  35. Success:function (Result) {
  36. Determines whether a login succeeds based on result return information
  37. if (Result &amp;&amp; result = = ' success ') {
  38. window.location.href = ' index.jsp ';
  39. } else {
  40. Alert (' Login failed, user name or password is wrong, please try again! ’);
  41. }
  42. }
  43. });
  44. });
  45. });

This triggers an AJAX request when the "Login" button is clicked:

    1. Verifying form Integrity
    2. Sends an AJAX request to the background, and the value is sent to the background via the Data key in JSON format
    3. If the result returned by the background is success, the login is successful, the page jumps to the homepage index.jsp

Third, the backstage work way

The background is more complicated than the foreground operation, which involves database, coding or some business logic

1. Get Request Parameters

There are two ways of doing this:

    • By means of Request.getparameter ("key")
    • Get through the Json-lib Toolkit

We're going to explain how to get the parameters by Json-lib.

First, let's write a public method that can return a Net.sf.json.JSONObject object with the following code:

Java code

  1. /**
  2. * Read request parameter conversion Jsonobject Object
  3. *
  4. * @param request HttpServletRequest Object
  5. * @return A JSON-formatted string object
  6. * @throws Exception
  7. */
  8. @SuppressWarnings ("Unchecked")
  9. Protected Jsonobject Readjson (HttpServletRequest request) throws Exception {
  10. Jsonobject jsonobject = new Jsonobject ();
  11. try {
  12. Map Parametermap = Request.getparametermap ();
  13. Get the key and value by looping through it and set it to Jsonobject
  14. Iterator paiter = Parametermap.keyset (). Iterator ();
  15. while (Paiter.hasnext ()) {
  16. String key = Paiter.next (). toString ();
  17. String[] values = (string[]) parametermap.get (key);
  18. Jsonobject.accumulate (Key, values[0]);
  19. }
  20. Log.debug ("Get json= from client" + jsonobject.tostring ());
  21. } catch (Exception e) {
  22. Log.error ("Error getting JSON data, error message: NT" + e.getmessage ());
  23. E.printstacktrace ();
  24. Throw e;
  25. }
  26. return jsonobject;
  27. }

By this method we can obtain a Jsonobject object, and then we can obtain the corresponding value by key;

2. Log in to handle action

Java code

  1. Public Actionforward Login (actionmapping mapping, Actionform actionform,
  2. HttpServletRequest request,httpservletresponse response) throws Exception {
  3. Jsonobject Jsonobject = Readjson (request);
  4. String name = jsonobject.getstring ("LoginName");
  5. String pass = jsonobject.getstring ("password");
  6. try {
  7. int loginflag = Usermanager.validlogin (name, pass);
  8. if (Loginflag = = usermanager.login_success) {
  9. User user = Usermanager.getuserbynameandpass (name, pass);
  10. Userutil.saveuser2session (user, request);
  11. Log.info ("User &lt;" + user.getusername ()
  12. + ", ip=" + request.getremoteaddr () + "&gt; login system");
  13. Print (response, resbonse_success);
  14. } else if (Loginflag = = Usermanager.login_fail) {
  15. Print (response, resbonse_error);
  16. }
  17. } catch (Exception e) {
  18. E.printstacktrace ();
  19. }
  20. return null;
  21. }

Explain:

In line 34 We get a Jsonobject object by the Readjson method we just prepared, then we get the username and password by key, then we verify the business logic, then we return the request result to the foreground.

We also need a small way to write results to the foreground, such as the above 44, 46 lines

Java code

    1. protected void print (HttpServletResponse response, String info) throws IOException {
    2. try {
    3. Response.getwriter (). print (info);
    4. } catch (IOException e) {
    5. E.printstacktrace ();
    6. Throw e;
    7. }
    8. }

/**

* Output Character stream

*

* @param reps

* Output Parameter Object

* @param str

* Content of the output

*/

public static void OutputStream (HttpServletResponse reps, String str) throws IOException

{

GetResponse (). setcharacterencoding ("Utf-8″");

GetResponse (). setContentType ("Text/html;charset=utf-8″");

Reps.getoutputstream (). Write (Str.tostring (). GetBytes ("Utf-8″)");

}

OutputStream (response, "{\" code\ ": \" -12\ ", \" msg\ ": \" The user is invalid, please login again! ") \”}”);

One thing to note here is that there is an episode in the output stream that I used when I was developing the tomcat5.5.26 version,

At that time, the wording was:

Java code

    1. Response.getoutputstream (). print (info);

Java code

    1. Later source open source after a netizen uses the TOMCAT6 version, said the system does not run normally, later he found out the reason, because obtains the output stream to have the problem,
    2. Change to Getwriter There is no problem, the collective also did not understand why this is ...

Java-based development will use struts,struts need to return a Actionmapping object, but in the AJAX request does not need to return a specific page, because there is no jump page action, the solution is simple, directly return null can be

After the output, jquery's Ajax success method receives the request result and then processes the business logic based on the result O (∩_∩) o~

JQuery Ajax Process Full parsing

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.