HTTP Status 400 - Required string parameter "xx" is missing

I am trying to create a simple Spring MVC application.

Here is my HelloController

 package com.springapp.mvc; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printWelcome(ModelMap model,@RequestParam(value = "xx",required =true)String xx) { model.addAttribute("message", "Hello Mahdi"); return "hello"; } } 

and JSP :

 <html> <body> <h1>${message}</h1> <form action="/" method="GET"> <input type="text" name="xx"> <button type="submit">submit</button> </form> </body> </html> 

When you try to start the application, the following error appears:

 HTTP Status 400 - Required String parameter 'xx' is not present 

I'm new to Spring MVC , please help.

+4
source share
1 answer

In your use case, two actions are required:

  • View and edit <form>
  • Submit <form>

This should be mapped to two handler methods

 @RequestMapping(method = RequestMethod.GET) public String getForm() { model.addAttribute("message", "Hello Mahdi"); return "hello"; // assume hello.jsp } @RequestMapping(params={"submit"}, method = RequestMethod.GET) public String printWelcome(ModelMap model, @RequestParam(value = "xx",required=true) String xx) { /* Do something with submitted parameter and return some view name */ } 

When you want to access the form, you do a GET on / . When you submit the form, you can also do a GET before / , but you need something else to distinguish the request. Here I used params="submit" . So you need to change your input file to

 <input type="submit" name="submit">submit</button> 

or just put the parameter that you are already using ( params={"xx"} ).

+6
source

Source: https://habr.com/ru/post/1494558/


All Articles