1. An overview of the

This article describes the common method parameter types and return types supported in Spring MVC using @RequestMapping.

Common method parameter types are: – 1 PathVariable – 2 RequestParam – 3 RequestBody – 4 HttpEntity – 5 CookieValue – 6 RequestHeader – 7 Automatically encapsulates the form request into the object -8 HttpServletRequest HttpServletResponse -9 RequestMapping Specifies the params headers parameter

Common return types are:

  • Returns the address of a page
  • 2 ResponseBody
  • 3 ResponseEntity
  • 4 ModelAndView

2. Prerequisites

Code project name: MVC

Test the PO class ModelAttributeVO

public class ModelAttributeVO { private String name; private String value; private Date date; // set/getCopy the code

VO

public class VO { private String name; private String value; private Date date; // set/getCopy the code

3. @requestMapping Specifies method parameter types supported

3.1. RequestParameterController

The following code in RequestParameterController class

@controller: indicates that this type of URL service is provided externally. @RequestMapping: This annotation applies not only to methods but also to classes. If applied to a class, this value is the prefix to the URL of all @RequestMapping methods in the class

@ Controller @ RequestMapping (value = "/ request") / / URL global public class RequestParameterController {... }Copy the code

3.2. JSP used

The following JSP pages are printed in the meta-INF resources web-INF page reqParameter directory: showinput.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Request Parameter</title>
</head>
<body>
    ${map}
</body>
</html>Copy the code

Formmodel.jsp tests the form form

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form name="myform" method="post" action="formModel"> <table> <tr> <td>First Name:</td> <td><input type="text" name="name" value="fisr name" /></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" name="value" value="lastName" /></td> </tr> <tr> <td colspan="2"> <input type="submit"  value="Save Changes" /> </td> </tr> </table> </form> </body> </html>Copy the code

Httpentityform.jsp tests the form form

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <form  name="myform" method="post"  action="httpEntity">
        <table>
            <tr>
                <td>First Name:</td>
                <td><input type="text" value="name" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" value="lastName" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Save Changes" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>Copy the code

3.3. @ PathVariable

Function: Can inject variable value in URL, can inject one or more

A single @pathvariable value code:

@RequestMapping(value="/path/{ownerId}")
public String pathVariable(@PathVariable String ownerId, Model model){
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("ownerId", ownerId);
    model.addAttribute("map", map);
    return "reqparameter/showInput";
}Copy the code

To access the URL: http://127.0.0.1:8080/request/path/1

Return result:

{ownerId=1}Copy the code

Multiple @pathVariable values can be used to inject variable values in urls, or to inject one or more codes:

    @RequestMapping(value="/path/{ownerId}/pet/{petId}")
    public String pathVariable2(@PathVariable String ownerId, @PathVariable String petId, Model model){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("ownerId", ownerId);
        map.put("petId", petId);
        model.addAttribute("map", map);
        return "reqparameter/showInput";
    }Copy the code

To access the URL: http://127.0.0.1:8080/request/path/1/pet/1234

Return result:

{petId=1234, ownerId=1}Copy the code

3.4. @ RequestParam

RequestParam (@requestParam, @requestParam, @requestParam)

@RequestMapping(value="/requestParam", method = RequestMethod.GET)
   public String requestParam(@RequestParam("ownerId") int ownerId, ModelMap model) {
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("ownerId", ownerId);

    model.addAttribute("map", map);
    return "reqparameter/showInput";
   }Copy the code

To access the URL: http://127.0.0.1:8080/request/requestParam? ownerId=223

Return result:

{ownerId=223}Copy the code

RequestParam (@requestParam, @requestParam, @requestParam)

    @RequestMapping(value="/requestParam2", method = RequestMethod.GET)
    public String requestParam2(@RequestParam Map<String,Object> map, ModelMap model) {
//      Map<String,Object> map = new HashMap<String,Object>();
//      map.put("ownerId", ownerId);

        model.addAttribute("map", map);
        return "reqparameter/showInput";
    }Copy the code

To access the URL: http://127.0.0.1:8080/request/requestParam2? ownerId=223&a=4&c=5

Return result:

{ownerId=223, a=4, c=5}Copy the code

@requestParam: required, defaultValue @requestParam: required, defaultValue

@RequestMapping("/requestParam3")
public String requestParam3(@RequestParam(value="inputStr", required=true, defaultValue="noInput") String inputStr,
                            ModelMap model) {
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("inputStr",inputStr );
    model.addAttribute("map",map);
    return "reqparameter/showInput";
}Copy the code

To access the URL: http://127.0.0.1:8080/request/requestParam3? InputStr =myInput If this URL has inputStr, the value is myInput

{inputStr=myInput}Copy the code

To access the URL: http://127.0.0.1:8080/request/requestParam3 the URL without inputStr value, its value as the default value, namely noInput return results:

{inputStr=noInput}Copy the code

3.5. @ RequestBody

Action: @requestBody: Gets the content of the request. Request content is JSON, because this project set request as JSON, so demo is: {” A “:1} code:

@RequestMapping(value = "/requestBody", method = RequestMethod.POST)
public String requestBody(@RequestBody String body, ModelMap model){
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("body",body );
    model.addAttribute("map",map);
    return "reqparameter/showInput";
}Copy the code

To access the URL: http://127.0.0.1:8080/request/requestBody content for {” a “: 1} this request for the POST, need to use the postman POST request return results such as:

{body={"a":1}}Copy the code

3.6. HttpEntity

HttpEntity, which can operate on the more primitive request method code:

@RequestMapping(value="/httpEntity", method = RequestMethod.GET) public String httpEntity(ModelMap model){ return "reqparameter/httpEntityForm"; } @RequestMapping("/httpEntity") public String httpEntity2(HttpEntity<byte[]> requestEntity, Header String acceptLanguage = requestEntity.getheaders ().getFirst(" accept-language "); Byte [] requestBody = requestentity.getBody (); byte[] requestBody = requestentity.getBody (); Map<String,Object> map = new HashMap<String,Object>(); map.put("acceptLanguage", acceptLanguage); // map.put("content", new String(requestBody)); model.addAttribute("map", map); return "reqparameter/showInput"; }Copy the code

To access the URL: http://127.0.0.1:8080/request/httpEntity

Result: Enter the above URL and enter the form form. After filling in the content, the new page will be displayed as follows

{acceptLanguage=zh-CN,zh; Q = 0.9, useful - TW; Q = 0.8}Copy the code

3.7. @ CookieValue

Get the value code in cookie:

@RequestMapping("/cookieValue")
public String cookieValue(@CookieValue("JSESSIONID") String cookie,ModelMap model) {
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("cookie", cookie);
    model.addAttribute("map", map);
    return "reqparameter/showInput";
}Copy the code

To access the URL: http://127.0.0.1:8080/request/cookieValue

Return result:

{cookie=38EDB55B71BB4CCA6EF1A2CDA7F1BCC0}Copy the code

3.8. @ RequestHeader

Select * from HTTP header; select * from HTTP header;

@RequestMapping("/requestHeader")
public String requestHeader (
        @RequestHeader ("User-Agent") String userAgent,
        @RequestHeader ("Host") String host,
        @RequestHeader ("Cache-Control") String cacheControl,
        ModelMap model) {
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("User-Agent", userAgent);
    map.put("Host", host);
    map.put("Cache-Control", cacheControl);

    model.addAttribute("map", map);
    return "reqparameter/showInput";
}Copy the code

Access the URL: http://127.0.0.1:8080/request/requestHeader the request to refresh demand refresh many times

Return result:

{cache-control =max-age=0, user-agent =Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36, Host=127.0.0.1:8080}Copy the code

Get all headers wrapped into a Map

Code:

    @RequestMapping("/requestHeaderMap")
    public String requestHeaderMap (@RequestHeader Map<String,String> map,
            ModelMap model) {       
        model.addAttribute("map", map);
        return "reqparameter/showInput";
    }Copy the code

To access the URL: http://127.0.0.1:8080/request/requestHeaderMap

Return result:

{host=127.0.0.1:8080, connection=keep-alive, user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36, upgrade-insecure-requests=1, accept=text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp image/apng, * / *; Q =0.8, accept-encoding=gzip, deflate, br, accept-language= zh-cn,zh; Q = 0.9, useful - TW; Q = 0.8, cookie = JSESSIONID = 38 edb55b71bb4cca6ef1a2cda7f1bcc0}Copy the code

3.9. Automatically encapsulate form requests into objects

Function: Code:

@RequestMapping(value="/formModel", method = RequestMethod.GET)
public String form(){
    return "reqparameter/formModel";
}

@RequestMapping("/formModel")
public String formPost(VO vo, ModelMap model){
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("name", vo.getName());
    map.put("value", vo.getValue());
    map.put("date", vo.getDate());

    model.addAttribute("map", map);
    return "reqparameter/showInput";
}Copy the code

Access URL: http://127.0.0.1:8080/request/formModel the URL into the form form, after we fill in the content, will be submitted to the formPost method, the automatically packaging value to the VO object, printing content is as follows

Return result:

{date=Sun Nov 12 22:11:22 CST 2017, name=fisr name, value=lastName}Copy the code

3.10 it + HttpServletResponse

What it does: Directly manipulate the original HttpServletRequest and HttpServletResponse code:

@RequestMapping("/httpServlet")
public void formPost(HttpServletRequest request, HttpServletResponse response) throws IOException{      
    String userAgent = request.getHeader("User-Agent");
    String host = request.getHeader("Host");
    String cacheControl = request.getHeader("Cache-Control");

    PrintWriter pw = response.getWriter();
    pw.println("User-Agent :"+ userAgent);
    pw.println("Host :" + host);
    pw.println("Cache-Control :" + cacheControl);

}Copy the code

To access the URL: http://127.0.0.1:8080/request/httpServlet

Return result:

User-Agent :Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36
Host :127.0.0.1:8080
Cache-Control :nullCopy the code

3.11. @requestMapping Configures params and headers

RequestMapping @requestMapping params filters requests through params (myParam=myValue)

@RequestMapping(value="/reqparameters/{ownerId}", method = RequestMethod.GET, params="myParam=myValue")
public String reqParameters(@PathVariable String ownerId, Model model){
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("ownerId", ownerId);
    model.addAttribute("map", map);
    return "reqparameter/showInput";
t";
    }Copy the code

To access the URL: http://127.0.0.1:8080/request/reqparameters/1? MyParam = myValue can access to this method, the process cannot access the methods but the following URL: http://127.0.0.1:8080/request/reqparameters/1

Note: Other conditions can also be: “myParam”, “! MyParam “, or “myParam = myValue”

The @requestMapping parameter is used to configure headers. If the request is filtered through headers, myParam must be entered in the request header and the value is myValue.

@RequestMapping(value="/reqparameters/{ownerId}", method = RequestMethod.GET, headers="myParam=myValue")
public String headerParameters(@PathVariable String ownerId, Model model){
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("ownerId", ownerId);
    model.addAttribute("map", map);
    return "reqparameter/showInput";
}Copy the code

Access URL: http://127.0.0.1:8080/reqparameters/1 if you use a POST request, please use the postman, and head in the request must take myParam, and value of myValue

4. @requestMapping Specifies the return type supported

4.1. ResponseParameterController

The following code is in this class

@Controller
@RequestMapping(value = "/response")
public class ResponseParameterController {
...
}Copy the code

4.2. Use JSP

META-INF resources web-INF page – resparameter

showInput.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Request Parameter</title>
</head>
<body>
    ${map}
</body>
</html>Copy the code

4.3. Return a page address

By default, a string is returned to indicate that a page is forwarded to. This is the pattern used in the previous demo

@RequestMapping(value="/path/{ownerId}")
public String pathVariable(@PathVariable String ownerId, Model model){
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("ownerId", ownerId);
    model.addAttribute("map", map);
    return "reqparameter/showInput";
}Copy the code

4.4. @ ResponseBody

This annotated method returns the string code:

@RequestMapping(value = "/responseBody", method = RequestMethod.GET)
@ResponseBody
public String responseBodyString() {
    return "Hello World";
}Copy the code

To access the URL: http://127.0.0.1:8080/response/responseBody

Return result:

"Hello World"Copy the code

@responseBody () {ResponseBody () {ResponseBody () {ResponseBody ();

@RequestMapping(value = "/responseBodyMode", method = RequestMethod.GET)
@ResponseBody
public VO responseBodyMode() {
    return new VO();
}Copy the code

To access the URL: http://127.0.0.1:8080/response/responseBodyMode

Return result:

{ "date":1510497345620, "name":"name", "value":"value" }Copy the code

4.5. ResponseEntity

Returns a ResponseEntity code:

@RequestMapping("/responseEntity")
public ResponseEntity<String> responseEntity(){
    // do something with request header and body
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("MyResponseHeader", "MyValue");
    return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}Copy the code

To access the URL: http://127.0.0.1:8080/response/responseEntity

Return result:

"Hello World"Copy the code

4.6. ModelAndView

Returns the ModelAndView code:

public ModelAndView modelAndView(){

    Map<String,Object> map = new HashMap<String,Object>();
    map.put("ownerId", "1");
    map.put("petId", "23");

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("resparameter/showInput");
    modelAndView.addObject("map", map);

    return modelAndView;
}Copy the code

To access the URL: http://127.0.0.1:8080/response/modelAndView

Return result:

{petId=23, ownerId=1}Copy the code

5. The code

Please use tag V0.4 as much as possible. Do not use master because the master is always changing. There is no guarantee that the code in this article will always be the same as the code on Github