1. 程式人生 > >RequestBody只能用一次,angularjs用post提交json請求

RequestBody只能用一次,angularjs用post提交json請求

public JsonModel register(@RequestBody User user, @RequestBody String code, HttpSession session) {
		//驗證碼校驗
		if(session.getAttribute(CodeController.codeSessionKey)==null){
			return null;
		}
		String codeR = session.getAttribute(CodeController.codeSessionKey).toString().toUpperCase();
		if (code ==
null || codeR == null || !code.toUpperCase().equals(codeR)) { return new JsonModel(0, "驗證碼錯誤!", null, "/fore/user/login"); } if (user.getUsername() == null || "".equals(user.getUsername()) || user.getPassword() == null || "".equals(user.getPassword())) { return new JsonModel(0, "使用者名稱或者密碼為空!",
null, "/fore/user/login"); } //註冊 User newUser = us.register(user); //存session跳主頁 session.setAttribute(WebSecurityConfig.SESSION_KEY, newUser); //跳主頁 return new JsonModel(200, "註冊成功", null, WebConfig.Host); }

程式碼裡面@RequestBody用了兩次,會報錯:HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed,也就是解析第二個@RequestBody時流已經關閉了,原因是request的content-body是以流的形式進行讀取的,讀取完一次後,便無法再次讀取了。

解決方法: 1. 新建一個內部包裝類包裝User物件和String型別的code,例如:

class Param{
  public User user;
  public String code;  
}

但此時傳輸的json資料格式變為{user:{name:“test”},code:{“123”}}

2. 將接收引數定義為Map<String, Object>

3. get和post同時用,和ckeditor一樣,例如: 前端:

app.service("userService",function($http){
    this.reg=function(username,password,phone,code){
        var data = {'username':username,'password' : password,'phone':phone};
        return $http.post("/fore/user/register"+"?code="+code,data);
    }
});

後端:

@PostMapping("/fore/user/register")
	@ResponseBody
	public JsonModel register(@RequestBody User user,String code, HttpSession session) {
		...
	}

Tips: @RequestBody:用來接收web前端發來的json物件的,也就是說Content-Type是 application/json;charset=UTF-8的請求,而且請求是Post的,例如下面的angularjs前端程式碼:

app.service("userService",function($http){
    this.reg=function(username,password,phone,code){
        var data = {'username':username,'password' : password,'phone':phone,'code':code};//json物件
        return $http.post("/fore/user/register",data);
    }
});