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
- $.ajax ({
- Url:url,
- Data: {
- Id:chkvalue
- },
- Cache:false,
- DataType: "JSON",
- Success:function (Result) {
- alert (result);
- }
- );
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
- User name:
- <input id= "LoginName" name= "LoginName" size= "20″type=" text "/>
- Password:
- <input id= "password" name= "password" size= "20″type=" password "/>
2. login JavaScript File Login.js
JS Code
- /**
- * Set Form validation rules
- */
- function Regformvalidator () {
- $.formvalidator.initconfig ({formid: "LoginForm"});
- $ ("#loginName"). Formvalidator ({
- OnShow: "Please enter user name",
- onfocus: "User name at least 2 characters, up to 4 words"
- }). inputvalidator ({
- Min:1,
- OnError: "The user name you entered is illegal, please confirm"
- });
- $ ("#password"). Formvalidator ({
- OnShow: "Please enter your password"
- }). inputvalidator ({
- Min:6,
- OnError: "Password is more than 6, please confirm"
- });
- }
- $ (function () {
- Registration Form Validation Plug-in
- Regformvalidator ();
- $ (' #submit '). Click (function () {
- Verify that the user name and password you entered are correct
- var valid = JQuery.formValidator.pageIsValid (' 1′);
- if (valid) {
- $ (this). attr (' value ', ' Logging in ... '). attr (' disabled ', true);
- } else {
- Return
- }
- Send Request
- $.ajax ({
- URL: ' Login.do ',
- Data: {loginname:$ (' #loginName '). Val (), Password: $ (' #password '). Val ()},
- Success:function (Result) {
- Determines whether a login succeeds based on result return information
- if (Result && result = = ' success ') {
- window.location.href = ' index.jsp ';
- } else {
- Alert (' Login failed, user name or password is wrong, please try again! ’);
- }
- }
- });
- });
- });
This triggers an AJAX request when the "Login" button is clicked:
- Verifying form Integrity
- Sends an AJAX request to the background, and the value is sent to the background via the Data key in JSON format
- 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
- /**
- * Read request parameter conversion Jsonobject Object
- *
- * @param request HttpServletRequest Object
- * @return A JSON-formatted string object
- * @throws Exception
- */
- @SuppressWarnings ("Unchecked")
- Protected Jsonobject Readjson (HttpServletRequest request) throws Exception {
- Jsonobject jsonobject = new Jsonobject ();
- try {
- Map Parametermap = Request.getparametermap ();
- Get the key and value by looping through it and set it to Jsonobject
- Iterator paiter = Parametermap.keyset (). Iterator ();
- while (Paiter.hasnext ()) {
- String key = Paiter.next (). toString ();
- String[] values = (string[]) parametermap.get (key);
- Jsonobject.accumulate (Key, values[0]);
- }
- Log.debug ("Get json= from client" + jsonobject.tostring ());
- } catch (Exception e) {
- Log.error ("Error getting JSON data, error message: NT" + e.getmessage ());
- E.printstacktrace ();
- Throw e;
- }
- return jsonobject;
- }
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
- Public Actionforward Login (actionmapping mapping, Actionform actionform,
- HttpServletRequest request,httpservletresponse response) throws Exception {
- Jsonobject Jsonobject = Readjson (request);
- String name = jsonobject.getstring ("LoginName");
- String pass = jsonobject.getstring ("password");
- try {
- int loginflag = Usermanager.validlogin (name, pass);
- if (Loginflag = = usermanager.login_success) {
- User user = Usermanager.getuserbynameandpass (name, pass);
- Userutil.saveuser2session (user, request);
- Log.info ("User <" + user.getusername ()
- + ", ip=" + request.getremoteaddr () + "> login system");
- Print (response, resbonse_success);
- } else if (Loginflag = = Usermanager.login_fail) {
- Print (response, resbonse_error);
- }
- } catch (Exception e) {
- E.printstacktrace ();
- }
- return null;
- }
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
- protected void print (HttpServletResponse response, String info) throws IOException {
- try {
- Response.getwriter (). print (info);
- } catch (IOException e) {
- E.printstacktrace ();
- Throw e;
- }
- }
/**
* 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
- Response.getoutputstream (). print (info);
Java code
- 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,
- 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