1、直接把表單的參數寫在Controller相應的方法的形參中,適用於get方式提交,不適用於post方式提交。
/** * 1.直接把表單的參數寫在Controller相應的方法的形參中 * @param username * @param password * @return */ @RequestMapping("/addUser1") public String addUser1(String username,String password) { System.out.println("username is:"+username); System.out.println("password is:"+password); return "demo/index"; }
url形式:http://localhost/SSMDemo/demo/addUser1?username=lixiaoxi&password=111111 提交的參數需要和Controller方法中的入參名稱一致。
2、通過HttpServletRequest接收,post方式和get方式都可以。
/** * 2、通過HttpServletRequest接收 * @param request * @return */ @RequestMapping("/addUser2") public String addUser2(HttpServletRequest request) { String username=request.getParameter("username"); String password=request.getParameter("password"); System.out.println("username is:"+username); System.out.println("password is:"+password); return "demo/index"; }
3、通過一個bean來接收,post方式和get方式都可以。
(1)建立一個和表單中參數對應的bean
package demo.model; public class UserModel { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
(2)用這個bean來封裝接收的參數
/** * 3、通過一個bean來接收 * @param user * @return */ @RequestMapping("/addUser3") public String addUser3(UserModel user) { System.out.println("username is:"+user.getUsername()); System.out.println("password is:"+user.getPassword()); return "demo/index"; }
4、get請求通過@PathVariable獲取路徑中的參數
/** * 4、通過@PathVariable獲取路徑中的參數 * @param username * @param password * @return */ @RequestMapping(value="/addUser4/{username}/{password}",method=RequestMethod.GET) public String addUser4(@PathVariable String username,@PathVariable String password) { System.out.println("username is:"+username); System.out.println("password is:"+password); return "demo/index"; }
例如,訪問http://localhost/SSMDemo/demo/addUser4/lixiaoxi/111111 路徑時,則自動將URL中模板變量{username}和{password}綁定到通過@PathVariable注解的同名參數上,即入參后username=lixiaoxi、password=111111。
5、使用@ModelAttribute注解獲取POST請求的FORM表單數據
Jsp表單如下:
<form action ="<%=request.getContextPath()%>/demo/addUser5" method="post"> 用戶名: <input type="text" name="username"/><br/> 密 碼: <input type="password" name="password"/><br/> <input type="submit" value="提交"/> <input type="reset" value="重置"/> </form>
Java Controller如下:
/** * 5、使用@ModelAttribute注解獲取POST請求的FORM表單數據 * @param user * @return */ @RequestMapping(value="/addUser5",method=RequestMethod.POST) public String addUser5(@ModelAttribute("user") UserModel user) { System.out.println("username is:"+user.getUsername()); System.out.println("password is:"+user.getPassword()); return "demo/index"; }
6、用注解@RequestParam綁定請求參數到方法入參
當請求參數username不存在時會有異常發生,可以通過設置屬性required=false解決,例如: @RequestParam(value="username", required=false)
/** * 6、用注解@RequestParam綁定請求參數到方法入參 * @param username * @param password * @return */ @RequestMapping(value="/addUser6",method=RequestMethod.GET) public String addUser6(@RequestParam("username") String username,@RequestParam("password") String password) { System.out.println("username is:"+username); System.out.println("password is:"+password); return "demo/index"; }
7@RequestBody
以前,一直以為在SpringMVC環境中,@RequestBody接收的是一個Json對象,一直在調試代碼都沒有成功,后來發現,其實 @RequestBody接收的是一個Json對象的字符串,而不是一個Json對象。然而在ajax請求往往傳的都是Json對象,后來發現用 JSON.stringify(data)的方式就能將對象變成字符串。同時ajax請求的時候也要指定dataType: "json",contentType:"application/json" 這樣就可以輕易的將一個對象或者List傳到Java端,使用@RequestBody即可綁定對象或者List.
JavaScript 代碼:
script type="text/javascript"> $(document).ready(function(){ var saveDataAry=[]; var data1={"userName":"test","address":"gz"}; var data2={"userName":"ququ","address":"gr"}; saveDataAry.push(data1); saveDataAry.push(data2); $.ajax({ type:"POST", url:"user/saveUser", dataType:"json", contentType:"application/json", data:JSON.stringify(saveData), success:function(data){ } }); }); </script>
Java代碼
@RequestMapping(value = "saveUser", method = {RequestMethod.POST }}) public void saveUser(@RequestBody List<User> users) { userService.batchSave(users); }
8、: 使用@RequestBody來設置輸入 ,@ResponseBody設置輸出 (POST + JSON字符串形式)
JS請求:
//請求數據,登錄賬號 +密碼 var data = { userAccount: lock_username, userPasswd:hex_md5(lock_password).toUpperCase() } $.ajax({ url : ctx + "/unlock.do", type : "POST", data : JSON.stringify(data), //轉JSON字符串 dataType: 'json', contentType:'application/json;charset=UTF-8', //contentType很重要 success : function(result) { console.log(result); } });
Controller處理:
@RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json") @ResponseBody public Object unlock(@RequestBody User user) { JSONObject jsonObject = new JSONObject(); try{ Assert.notNull(user.getUserAccount(), "解鎖賬號為空"); Assert.notNull(user.getUserPasswd(), "解鎖密碼為空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER); Assert.notNull(currentLoginUser, "登錄用戶已過期,請重新登錄!"); Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解鎖賬號錯誤"); Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解鎖密碼錯誤"); jsonObject.put("message", "解鎖成功"); jsonObject.put("status", "success"); }catch(Exception ex){ jsonObject.put("message", ex.getMessage()); jsonObject.put("status", "error"); } return jsonObject; }
@Controller @ResponseBody public class HelloController { @RequestMapping(value = "/hello", method = RequestMethod.POST, consumes = "application/json") public String hello(@RequestBody String username) { System.out.println("接受參數name" + username); return username; } }