我正在使用Spring和javascript。使用@Controller
对象调用XhrHttpRequest
。
我可以使用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);
}
}
我不知道为什么参数变为null。感谢。
答案 0 :(得分:0)
您需要按照以下步骤接受控制器中的Json
:
(1)定义UserLogin bean以保存Json
public class UserLogin {
private String id;
private String password;
//Add getters and setters
}
(2)更改您的控制器以接受Json&amp;收到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);
}
}
答案 1 :(得分:0)
这是杰克逊图书馆的替代方式。我喜欢@javaguy的方式,但使用Jackson库可以更灵活,所以添加这篇文章。
准备工作
WebMvcConfigurerAdapter
实现类或类似Eclipse Dynamic Web Project
Maven
和spring-webmvc
pom.xml
{/ 1}}。{/ 1>
我做了什么......
WebMvcConfigurerAdapter
configureMessageConverters
HttpServeletRequest request, HttpServletResponse resp
更改为@RequestBody Map<?, ?>
。(您可以更改通用值。这对进一步处理无关紧要)所以这是代码。
ServerConfig.java(我阻止其他选项来关注当前问题)
@Configuration
@EnableWebMvc
@ComponentScan(basePackages={ ... }
, excludeFilters=@ComponentScan.Filter(Configuration.class))
//Filter 걸 때 Configuration.class 를 수동으로 등록해줘야 되는데 나은 방법 찾아보기
public class ServerConfig extends WebMvcConfigurerAdapter {
...
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
};
和控制器(更改参数类型)
@Controller
@RequestMapping(value={"member"}, produces={"application/json"})
@ResponseStatus(value = HttpStatus.OK)
public class MemberApiController {
...
@RequestMapping(value={"/login"})
public @ResponseBody String login(@RequestBody Map<?, ?> jsonBody) throws JsonProcessingException {
System.out.println("Login request" + jsonBody.toString());
Map<String, String> result = new HashMap<String, String>();
String rs = "S";
String message = "SUCCESS";
System.out.println("ID >>> ", String.valueOf(jsonBody.get("id")));
System.out.println("PW >>> ", String.valueOf(jsonBody.get("password")));
result.put("result", rs);
result.put("result_msg", message);
mapper = new ObjectMapper();
return mapper.writeValueAsString(result);
}
};
但是,据我所知@RequestBody
没有HttpSession
,如果您尝试将数据存储到HttpSession
,则需要另一个参数HttpServletRequest
。
我希望这可以帮助那些与我有同样问题的人:D