jquery's Ajax and spring MVC docking considerations

Source: Internet
Author: User
Tags html form

Yesterday has been a tangled problem, the application scenario is this:

Here the login is to transmit data via jquery Ajax to the backend controller class corresponding map mapping receive. It was intended to return a view Modelandview after the background validation was successful. But never thought there was such a problem, that is, no matter how you return, the front desk is not jump page. Here is a very important question. First look at my front-end Ajax Send login request code:

<script type= "Text/javascript" >        $(function() {            $(' #submitLogin '). Click (function() {$.ajax ({type:"POST", URL:"/user/checklogin", DataType:"JSON", Data: $ ("#loginform"). Serialize (), Success:function(data,status) {alert ("Success" +data); }, Error:function() {alert (Failed);            }                });        });    }); </script>

Take a look at a deprecated background example: (The cause of the error)

@RequestMapping (value = "/checklogin", method =requestmethod.post) Public@ResponseBody modelandview userlogin (tuserloginvo tuserloginvo, HttpServletRequest request,httpservletresponse Response) {HttpSession session=request.getsession (); String Code= (String) session.getattribute ("code"); System.out.println ("---" +session.getattribute ("code")); Modelandview MV=NewModelandview (); if(Code.equals (Tuserloginvo.getcheckcode ())) {TUser TUser=Staffservice.finuser (Tuserloginvo.getusername (), Tuserloginvo.getpassword ()); if(tuser!=NULL) {Mv.setviewname ("Redirect:/pages/test.html"); System.out.println ("---"+tuser.getusername ()); returnMV; }} mv.setviewname ("Redirect:/pages/loginpage.html"); returnMV; }

The above directly return a view, but the foreground is not see jump, and directly executed the error method, the problem is that the background code has been executed AH.

Let's start by explaining what kind of role jquery Ajax code is playing!

Type: "Post", which represents the request via post.
URL: "/user/checklogin"@RequestMapping (value = "/checklogin", method = Requestmethod.post))
DataType: "JSON", this is very important, this is the direct surface I expected back to me. Returns a JSON-type of data, if not, the method that executes the error directly.
The following is an analysis of a property that is not normally set:
JSON.  Stringify(a); turn data A into JSON type, of course, not everything can be JSON type, I hope to remember!
Next
Data: $ ("#loginform"). Serialize (), which is a very quick way to take the values out of the form directly, taking the above example, the resulting format is this:

In this way, the background can also be directly used to receive the object, as to how it is assembled into objects, and the form of the name attribute, it is important to remember that the form, there is no background required data tags in the label must not be nested Name property. The value of the Name property must correspond to the value of the field in our PO Object!
For example, one of my PO classes:
    Private String username;     Private String password;     Private String Checkcode;

Those getter and setter methods I'm not going to put out.

It must correspond to the HTML form:

If there is inconsistency, background receive will report an unsupported error!

In order to cater to DataType: "JSON", this requirement, the background must precede the method return value with @ResponseBody:

 Public @ResponseBody  Object Userlogin () {* * * *}

The above is a point of attention, now come another!

Also mentioned before, JSON data type, back in the background JSON data type, although we added @responsebody, but this is to remember that this is the object, collection and other types can be converted to JSON type, but sometimes we need to return a string what to do, I'm sorry, @ Responsebody cannot help us to convert to JSON type, and will not error, only the foreground will only execute the error method, because we set the datatype: "JSON"

In general, this is set to JSON, so we have to return a string is best to find a way (of course datatype: "JSON" inside the JSON can also be changed to text, etc., but not necessary)

I am this solution, directly compare the return value of the code bar (self-assembled in a JSON-formatted string)

@RequestMapping (value = "/checklogin", method =requestmethod.post) Public@ResponseBody Object userlogin (tuserloginvo tuserloginvo, HttpServletRequest request,httpservletresponse Response) {HttpSession session=request.getsession (); String Code= (String) session.getattribute ("code"); System.out.println ("---" +session.getattribute ("code")); if(Code.equals (Tuserloginvo.getcheckcode ())) {TUser TUser=Staffservice.finuser (Tuserloginvo.getusername (), Tuserloginvo.getpassword ()); if(tuser!=NULL) {System.out.println ("---"+tuser.getusername ()); return"{\" loginok\ ": \" Loginok\ "}"; }        }        return"{\" loginerror\ ": \" Loginerror\ "}"; }

The problem is solved, the foreground executes the success Method!

Of course, the above method is not good, what to do, we need is JSON, but can not be transferred.

Can this one, give a general method:

 Packagecom.liyong.bos.utils;Importjava.io.Serializable;Importjava.util.List; Public classJsonresult<t, k>ImplementsSerializable {Private Booleanresult; PrivateString msg; PrivateList<t>dataList; PrivateK data; PrivateT Dataobje;  PublicK GetData () {returndata; }     Public voidsetData (K data) { This. data =data; }     PublicList<t>getdatalist () {returndataList; }     Public voidSetdatalist (list<t>dataList) {         This. dataList =dataList; }     PublicString getmsg () {returnmsg; }     Public voidsetmsg (String msg) { This. msg =msg; }     Public BooleanIsresult () {returnresult; }     Public voidSetresult (Booleanresult) {         This. result =result; }     PublicT Getdataobje () {returnDataobje; }     Public voidSetdataobje (T dataobje) { This. Dataobje =Dataobje; }}

Wrap the data we need into the Jsonresult object, and the return value is Jsonresult. See the code for specific features.

jquery's Ajax and spring MVC docking considerations

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.