Springmvc I think it's better than struts2. One of the reasons is that you can use annotations to parse JSON data quickly and easily. However, even so, there is a need to pay attention to the place.
1, the return place sets @responsebody, the request object parameter @requestbody, the individual parameter does not add @requestbody;
@RequestMapping (value= "/validation") String Validation (string username)throws exception{
username ; }
2, if you want to return an object, then return directly, spring will automatically convert to JSON data.
@RequestMapping (value= "/validation") User validation (String username)throws exception{
User U = New User (username); return u;}
3, if the transmission is a set of data, can be encapsulated with objects, using @requestbody will help us to convert the JSON to the corresponding object.
@RequestMapping (value= "/validation") public String validation (@RequestBody user user) Throws exception{
return "Index";}
Attention:
1, the situation of a single parameter
a), return a single variable SPRINGMVC will not help us to convert, will only return the original value.
b), single parameter do not use @requestbody, can use @requestparam.
error Condition: GET: 400 parameter illegal or post: appears Username=a,key and value are passed to the parameter
@RequestMapping (value= "/validation") public String validation (@RequestParamthrows exception{
return "index"; }
c), single parameter do not add ' contentType ' : ' Application/json '. contentType: ' Application/json ', this sentence is removed, this sentence is described in the request Package content format, you should use the default application/x-www-form-urlencoded to properly be parsed by the server.
error Condition: 400 error occurred using @requestparam, with @requestbody Key and value passed to the parameter
2, if it is @RequestBody the whole object, then you will add ' contentType ': ' Application/json '. If not added, there may be 406Not acceptable
$ (' #username '). blur (function () {var postdata = ' {"username": "' + $ (' #username '). Val () + '", "Password": "' + $ (' # Password '). val () + '} '; $.ajax ({ URL: "Validation", Type: "Post", cache:false,
ContentType: ' Application/json ', Data:postdata, DataType: ' JSON '
As mentioned above, as to the specific reasons for these situations, there is a time to study spring's source code at a breakpoint.
Springmvc of the @responsebody, @RequestBody use need to pay attention to the place