springmvc 获取请求参数的几种方式

1、通过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";
    }

2、通过一个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";
    }

3、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。


4、用注解@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";
    }

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

示例: 使用@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;
    }
}

猜你喜欢

转载自blog.csdn.net/leo3070/article/details/81045846