Spring MVC Common Client Parameter Reception Details

  • 2021-06-29 10:58:00
  • OfStack

In the MVC structure, the main functions of the controller components are to receive requests, process requests and generate responses. Receiving request parameters from clients is often the first thing the controller does.

Book Entity Class Book.java


public class Book {
  private Integer bookId;
  private String author;
  // generate Get , Set Method, omitted here 
}

1. Match request parameters directly with parameter names

Client interface (form):


<form action="/queryString" method="post">
  <input type="text" name="bookId">
  <input type="text" name="author">
  <input type="submit" value=" Submit ">
</form>

controller Layer:


@Controller
public class ParamPassDemo {
  @RequestMapping(value="/queryString")
  public String test1(Integer bookId, String author) {
    System.out.println("bookId="+bookId+", author="+author);
    // The address returned here is ( /WEB-INF/jsp/index.jsp ) 
    return "index";
  }
}

Note: There is only the value attribute in @RequestMapping, value can be omitted from not writing.

Client input: 123, Rose

Console output: bookId=123, author=Rose

2. Specify name for the request parameter through the @RequestParam annotation

Client interface (form):


<form action="/queryStringWithSpecName" method="post">
  <input type="text" name="bookId" value="321">
  <input type="text" name="author" value="Jack">
  <input type="submit" value=" Submit ">
</form>

If the field in the form matches the parameter name 1 in the method, you do not need @RequestParam, which is handled automatically.
controller Layer:


@Controller
public class ParamPassDemo {
  @RequestMapping("/queryStringWithSpecName")
  public String test2((value="bookId",required=false) Integer id, @RequestParam("author") String name) {
    System.out.println("bookId="+id+", author="+name);
    return "index";
  }
}

Note: There are two attributes in @RequestMapping here and value cannot be omitted.

@RequestParam passes parameters from the request address to the target method, which can be passed to the request method when the processing method is involved.
When the @RequestParam annotation is used, the parameter name int id may not match the request parameter after setting the request parameters name="bookId" passed by the client and the value value value="bookId" of @RequestParam to match.

Client input: 321, Jack

Console output: bookId=321, author=Jack

Client Interface (ajax):


<button onclick="clickMe()"> Click on me </button>
<script>
  function clickMe() {
      $.ajax({
      type : 'POST',
      url : "/queryStringWithSpecName",
      data : {
        "bookId" : 1,
        "author" : "Jack"
      },
    });
  }
</script>

controller Layer: (unchanged)

Client: data: {"author": "Jack"}

Console output: bookId=null, author=Jack (if bookId is of type int, the console throws an exception)

Client: data: {"bookId": 1}

Console output: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter'author'is not present

By setting optional parameters with required, required can be taken with no parameters when false and true must be taken with parameters (the default value is true).

When an optional parameter does not exist, Spring assigns it null by default (null), but since bookId is defined as the basic type int, assignment fails.Solution: Use int packaging class Integer.

3. Use domain objects to receive parameters

Client interface (form):


<form action="/queryStringWithDomainObj" method="post">
  <input type="text" name="bookId">
  <input type="text" name="author">
  <input type="submit" value=" Submit ">
</form>

controller Layer:


@Controller
public class ParamPassDemo {
  @RequestMapping("/queryStringWithDomainObj")
  public String test3(Book book) {
    System.out.println("bookId="+book.getBookId()+", author="+book.getAuthor());
    return "index";
  }
 }

Client input: 111, Bob

Console output: bookId=111, author=Bob

4. URL dynamic parameter transfer (path parameters)

Client interface (hyperlink):


<a href="/book/1" rel="external nofollow" >testPathVariable</a>

controller Layer:


@Controller
public class ParamPassDemo {
  //@PathVariable Can be used to map URL Placeholder in to parameter of target method 
  @RequestMapping("/book/{bookId}")
  public String test4(@PathVariable("bookId") Integer bookId) {
    System.out.println("bookId:" + bookId);
    return "index";
  }
 }

Console output: bookId:1

@PathVariable maps placeholders for URL binding

Placeholder parameters in URL can be bound to controller processing via @PathVariable: The {xxx} placeholder in URL can be bound to operation method input via @PathVariable ("xxx").

5. Use HttpServletRequest to get request parameters

Client interface (form):


<form action="/queryString" method="post">
  <input type="text" name="bookId">
  <input type="text" name="author">
  <input type="submit" value=" Submit ">
</form>
0

controller Layer:


<form action="/queryString" method="post">
  <input type="text" name="bookId">
  <input type="text" name="author">
  <input type="submit" value=" Submit ">
</form>
1

Client input: 123

Console Output: User id:123

6. Jump to another controller method

Client interface (url address bar): http://localhost:8080/test6 ?bookId=321

controller Layer:


<form action="/queryString" method="post">
  <input type="text" name="bookId">
  <input type="text" name="author">
  <input type="submit" value=" Submit ">
</form>
2

Console output: bookId=321 bookId:321


Related articles: