Juneyoung Oh Juneyoung Oh - 21 days ago 12
Javascript Question

HttpServletRequest can not get xhr request parameter

I am working with Spring and javascript. Calling

@Controller
with
XhrHttpRequest
Object.

I can see my parameter(JSON string) with Chrome Inspector, but when I call
request.getParamter("id")
returns 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);
}


receive part with 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);
}
}


I do not know why parameter becomes null. Thanks.

Answer

You need to follow the below steps to accept Json in your controller:

(1) Define UserLogin bean to hold the Json

public class UserLogin  {
    private String id;
    private String password;

    //Add getters and setters
}

(2) Change your controller to accept Json & receive the UserLogin bean

@Controller
@RequestMapping(value={"member"}, produces={"application/json"})
@ResponseStatus(value = HttpStatus.OK)
public class MemberController {

    @RequestMapping(value={"/login"}, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String login(UserLogin userLogin) throws Exception {
        System.out.println("Login request");
        String id = userLogin.getId();            
        String password = userLogin.getPassword();

        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);
    }
}