【发布时间】:2017-03-21 20:01:54
【问题描述】:
我正在使用 Spring 和 javascript。使用 XhrHttpRequest 对象调用 @Controller。
我可以使用 Chrome Inspector 查看我的参数(JSON 字符串),但是当我调用 request.getParamter("id") 时返回 null。
Calling part with js
function ajax(url, data, callback, method){
//data is {"id":"system", "password" : "1234"}
var httpRequest;
var afterAction = function(){
if(!httpRequest) {
console.error('can not find httpRequest variable');
return;
}
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
var responseData = httpRequest.responseText;
//alert(JSON.stringify(responseData));
console.log('Result of API call >>>', responseData);
if(typeof callback == 'function') {
callback(JSON.parse(responseData));
}
} else {
alert('There was a problem with the request.');
}
}
}
//=========== LOGIC ============
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
if(!method) method = 'POST';
data = (!!data) ? JSON.stringify(data) : '';
httpRequest.onreadystatechange = afterAction;
httpRequest.open(method.toUpperCase(), url, true);
httpRequest.setRequestHeader("Content-type", "application/json; charset=utf-8");
//httpRequest.setRequestHeader("Content-length", data.length);
//httpRequest.setRequestHeader("Connection", "close");
httpRequest.send(data);
}
使用 Spring @Controller 接收零件
@Controller
@RequestMapping(value={"member"}, produces={"application/json"})
@ResponseStatus(value = HttpStatus.OK)
public class MemberController {
/**
* @param request
* @param resp
* @return
* @throws Exception
*/
@RequestMapping(value={"/login"})
public @ResponseBody String login(HttpServletRequest request, HttpServletResponse resp) throws Exception {
System.out.println("Login request");
String id = String.valueOf(request.getParameter("id")); //returns null
String password = String.valueOf(request.getParameter("password")); //returns null
Map<String, String> result = new HashMap<String, String>();
result.put("result", "S");
result.put("message", "login success");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(result);
}
}
我不知道为什么参数变为空。谢谢。
【问题讨论】:
-
JSON 正文不是请求参数。所以很明显
getParameter将返回null。您将需要解析正文而不是参数。 -
@M.Deinum 我的一位朋友建议使用
Converter,我将对其进行测试并添加到这篇文章中。感谢分享信息
标签: javascript spring model-view-controller xmlhttprequest httprequest