Spring MVC Ajax 400坏请求

当我触发Ajax请求时,我收到了“400:Bad Request”,这是一个“右上角”登录。 我不知道为什么。 在firebug中,我可以看到请求url是正确的,但它返回“400:Bad Request”。 我无法调试,因为似乎客户端没有成功发回任何东西回控制器。 我想在我的代码中使用ajax是一个错误。

控制器:

@Controller @RequestMapping("/login") public class AjaxLoginController { @Autowired SecurityContextRepository repository; @Autowired RememberMeServices rememberMeServices; @RequestMapping(method = RequestMethod.GET) public void login() { } @RequestMapping(method = RequestMethod.POST) @ResponseBody public String performLogin(@RequestParam("j_username") String username, @RequestParam("j_password") String password, HttpServletRequest request, HttpServletResponse response) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); try { Authentication authentication = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); repository.saveContext(SecurityContextHolder.getContext(), request, response); rememberMeServices.loginSuccess(request, response, authentication); return "{\"status\": true}"; } catch (BadCredentialsException e) { return "{\"status\": false, \"error\": \"Bad Credentials\"}"; } } 

JSP:

  function doLogin() { var url = "${login_url}"; var username = $("#j_username").val(); var password = $("#j_password").val(); $.ajax({ url : url, type : "POST", cache : false, async : true, contentType : "application/json; charset=UTF-8", data : JSON.stringify({ "j_username" : username, "j_password" : password }), datatype : "json", success : function(data) { alert("YES"); }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status + " : " + errorThrown); } }); } 

  

FireBug标题:

 Accept */* Accept-Encoding gzip, deflate Accept-Language zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3 Cache-Control no-cache Connection keep-alive Content-Length 42 Content-Type application/json; charset=UTF-8 Cookie JSESSIONID=AEBEB562DD68FF2023C03D54245B0C4A Host localhost:8099 Pragma no-cache Referer http://localhost:8099/springmvc/dishes/not_found User-Agent Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0 X-Requested-With XMLHttpRequest 

Firebug请求URL是正确的。

试试这个:

 @RequestMapping(method = RequestMethod.POST) @ResponseBody public String performLogin(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) { ... } 

尝试使用@ModelAttribute 。 这将是工作。