Several ways for springmvc to get passed parameters

 

1. Basic parameter transfer method

As long as the name value entered in the form and the method parameter variable name are always on the line. It is best not to use basic data types for parameter types. If the parameters passed by the front end are null or empty strings, data conversion exceptions will occur, so it is best to use the wrapper class Integer. Of course, Pojo can also be used as the parameter type, as long as the parameter value corresponds to the attribute name one by one. for example:

Model object:
public class User {
    private String firstName;
    private String lastName;
// getter, setter omitted
}

Controller code:
@RequestMapping("/user")
public void test(User user) {
}

Form:
<form action="saysth.do" method="post">
<input name="firstName" value="张" type="text"/>
<input name="lastName" value="三" type="text"/>
......
</form>

 

2. Obtain directly with HttpServletRequest

@RequestMapping("/")
public String get(HttpServletRequest request, HttpServletResponse response) {
   System.out.println(request.getParameter("a"));
    return "helloWorld";
}

 

3. Bind request parameters with the annotation @RequestParam

@RequestMapping("/login")
   public String login(@RequestParam(value="age",required=false,defaultValue="24") String agenum){
       return "hello";
   }

 The value attribute matches the foreground parameter, and the required attribute specifies whether a value must be passed (the default is true). If it is true and the foreground does not pass this parameter, an exception will be thrown. defaultValue specifies the default value of this parameter (when this parameter exists, it means that the front desk does not need to pass a value, and required is false)

 

4. @PathVariable annotation gets the parameters in the path

@RequestMapping(value="user/{id}/{name}",method=RequestMethod.GET)
    public String printMessage1 (athPathVariable String id, @ PathVariable String name)
        System.out.println(id);
        System.out.println(name);
        return "users";
    }

 The name of the method parameter variable is the same as the name in the address {}, of course, it does not have to be applied to the get method

 

5.@RequestBody

Similar to @ResponseBody, it is to pass the body part of the http request as a String parameter, which is often used to accept the json string passed by the ajax request.

@ResponseBody
    @RequestMapping(value = "/detail", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public Port detail(@RequestBody String param) {
    	JSONObject object = JSONObject.fromObject(param);
    	String id = object.getString("id");
    	Port port = iPortService.getPortDetail(id);
        logger.debug("port Info : " + port);
        return port;
    }

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326125067&siteId=291194637