SpringMVC and AJAX interactions

In the actual development, we often need to interact front and back, then the interaction between springmvc ajax here and record the details of the problems encountered in the actual development.

jsp page:

1 <fieldset id="login" style="width:600px; border:1px solid #000;border-left:none;border-right:none"> 
2 <legend style="">用户登录</legend> 
3 <p align="center">账号:<input type="text" name="username" /></p> 
4 <p align="center">密码:<input type="password" name="password" /></p> 
5 <p align="center"><input type="submit" id="submit1" value="登录" /></p> 
6 </fieldset>

ajax request as follows:

<Script type = "text / JavaScript"> 
$ (function () { 
$ ( "# Submit1" ) .click (function () { 
var JSON = {
 'username': $ ( ': INPUT [name = username]' ) .val (),
 'password': $ ( ': INPUT [name = password]' ) .val () 
}; 
// JSON string { "username": "ADMIN", "password": "123456"} 
var = the JSON.stringify PostData (json); // json json object into a string 
Alert (PostData); 
$ .ajax ({ 
type: 'the POST' , 
contentType: 'file application / json', // note type 
/ ** 
*(默认:true) By default, data passed in through the option data, if an object (if not technically a string),
* are process is converted into a query string to match the default content type "application/x-www-form-urlencoded"。
* If you want to send a DOM tree information or other information do not wish to convert, set to false. 
* / 
The processData: to false , 
URL: '<% =% path> / DataBind / requestbodybind' , 
dataType: 'JSON' , 
Data: PostData, 
Success: function (Data) { 
Alert ( 'username:' data.username + + '\ nPassword: '+ data.password); 
}, 
error: function () { 
Alert ( ' error ... ' ); 
} 
}); 
});     
});
 </ Script>

tip: We can see with contentType: 'application / json' initiated the request, data that we pass a json string instead of json objects, at the beginning I also think it is possible, not the result of direct transfer target error, wish to personally try.
SpringMVC desirable to provide the following method:

@RequestMapping(value="requestbodybind", method = {RequestMethod.POST})
@ResponseBody
public Account requestBodyBind(@RequestBody Account account){
System.out.println("requestbodybind:" + account);
return account;
}

That was contentType: 'application / json' initiated requests, we can not use it as way to receive value

@RequestMapping(value="json", method = {RequestMethod.POST})
@ResponseBody
public Account json(String username, String password){
Account account = new Account();
account.setUsername(username);
account.setPassword(password);
return account;
}

The answer is no, the exception will be thrown, 400 Bad Request
reason is: contentType: 'application / json' data transmission must be received back Modle, not a single property, and must be added @RequestBody comment.
If we replaced the default contentType contentType: 'application / x-www -form-urlencoded' it, front and how should I write?

ajax worded as follows:

$(function(){
$("#submit").click(function(){
$.ajax({
type: "POST",
/* contentType : 'application/x-www-form-urlencoded',*/
url: '<%=path%>/databind/json',
dataType: "json",
data: {username:$('#username').val(),
password:$('#password').val()},
success: function(data){
alert('username : '+data.username+'\npassword : '+data.password);
}
}); 
});
});

Here we must mention, though data appears to pass here is a json object, but the use of the application / x-www-form-urlencoded, can eventually be seen by firebug, in fact, the final pass past or username = admin & password = 123456, of course, you can directly pass the string in the past, but one thing to note, the real project or a particularly large number of fields, such splicing can be quite tedious, but we know there is a method for us to use, jQuery provides us with a $ ( "#login"). serialize () serialized form.

$(function(){
$("#submit").click(function(){
var params = $("#login").serialize();//序列化表单
alert(params);
$.ajax({
type: "POST",
url: '<%=path%>/databind/json',
dataType: "json",
data: params,
success: function(data){
alert('username : '+data.username+'\npassword : '+data.password);
}
}); 
});
});

Background receiving follows:

@RequestMapping(value="json", method = {RequestMethod.POST})
@ResponseBody
public Account json(String username,String password){
Account account = new Account();
account.setUsername(username);
account.setPassword(password);
return account;
}

To raise a question here that if I need to accept the field and more particularly it, do I also need a method to write a parameter of thing, such as a 20, still not exhausted.
The answer is of course

@RequestMapping(value="/json", method = {RequestMethod.POST})
@ResponseBody
public Account json(Account account){
System.out.println(account);
return account;
}

In addition, there must mention one thing, many people saw the model to bring it receives mass participation, it should not think should be added @RequestBody comment, springmvc will help you to model the correlation value package to go inside, I here to tell you, do not think so, not just to use this annotation, its purpose is to help you convert json-> model, xml-> model, you good form submission, with contentType: application / x- www-form-urlencoded, so why add this superfluous comment yet.
to sum up:

<script type="text/javascript">
$(function() {
$("#submit1").click(function() {
var json = {
'username':$(':input[name=username]').val(),
'password':$(':input[name=password]').val()
};
//json字符串 {"username":"admin","password":"123456"}
var postdata = JSON.stringify(json);//json对象转换json字符串
alert(postdata);
$.ajax({
type : 'POST',
contentType : 'application/json',
/**
*(默认:true) By default, data passed in through the option data, if an object (if not technically a string), 
* are transformed into a process the query string to match the default content type. "file application / X-WWW-form-urlencoded. " 
* If information to be transmitted DOM tree or other undesirable conversion information, set to false.
* / 
The processData: to false , 
URL: '<% =% path> / DataBind / requestbodybind' , 
dataType: 'JSON' , 
Data: PostData, 
Success: function (Data) { 
Alert ( 'username:' data.username + + '\ nPassword: '+ data.password); 
}, 
error: function () { 
Alert ( ' error ... ' ); 
} 
}); 
});     
});
 </ Script>

Above $ .ajax () in contentType: 'application / json', the data must be converted to the object and the background json method with Model parameters must accept, otherwise an error message 400, the parameters are accepted background:

@RequestMapping(value="requestbodybind", method = {RequestMethod.POST})
@ResponseBody
public Account requestBodyBind(@RequestBody Account account){
System.out.println("requestbodybind:" + account);
return account;
}

Default $ .ajax () in contentType: 'application / x-www -form-urlencoded' data format transmitted is "xx = yy & uu = ii " data Data not json object that is sent when the information to the server content encoding type.
Below $ .ajax () is not written contentType default type 'application / x-www-form -urlencoded', the parameter type data is transmitted as a single attribute.

function initArrivePerson(divId) {
var jqids = $("#jqid").val();//获得警情id
$.ajax({
type:"post", 
url:basePath + "kscj/findArrivePerson.do",
data:{"jqid":jqids},
dataType:"json",
async: false,
cache:false,
success : function(data) {
$("#"+divId).html("");
var arrivePerson="";
for (var i=0;i<data.length;i++) {
arrivePerson+="<span>";
arrivePerson+="<input type=\"checkbox\" name=\"cjrxm\" value=\'"+data[i].sjybh+"\'/><span>"+data[i].sjyxm+"</span>";
arrivePerson+="<input type=\"hidden\" name=\"cjdbh\" value=\'"+data[i].cjdbh+"\'/>";
arrivePerson+="</span>";
}
$("#"+divId).append(arrivePerson); 
}
});
}

The background is accepted parameters:

@RequestMapping(value = "/findArrivePerson", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public List<TItmpTcsDisposal> findArrivePerson(HttpServletRequest req, HttpServletResponse resp, String jqid){
List<TItmpTcsDisposal> arriveList = titmpGpsLocateinfoService.findNoRepeat(jqid);
return arriveList;
}

supplement:

When to use annotations @RequestParam, when not to use

We have already seen, to accept the basic parameters of a single type of value, respectively write down as long as the method, and does not need to be able to get the value of what annotations pass over, then why are @RequestParam this annotation it, and see to many places are using.
Actually this annotation, has its usefulness, is not useless, first as a basic parameter of type, if not using annotations, is passed from time pass, if it is null and does not complain, but when you use the @RequestParam notes, this parameter is then the time will pass, if not pass the error will, however, still may not necessarily be allowed to pass through the configuration, such as @RequestParam (value = "username", required = false), in addition, the annotation also If you do not pass the front desk can set values over, it will give a default value, such as @RequestParam (value = "username", defaultValue = "ruo").
I made notes of the summary is: If you pass a parameter is not necessary, do not use it, if it will pass, be sure to use it, if necessary transfer parameters can have default values, then, please add defaultValue the default value.

Original blog: https: //blog.csdn.net/u014079773/article/details/52984747

Guess you like

Origin www.cnblogs.com/Schrodinger6/p/11318814.html