6

I have something like

@RequestMapping("/property")
@ResponseBody
public String property(@RequestBody UserDto userDto ) {

    System.out.println(userDto.getUsername());
    System.out.println(userDto.getPassword());

    return "Hello";
}

in my controller.

But it gives me an error when I post with

<form method="post" action="http://localhost:8080/home/property">

    <input name="username"/>
    <input name="password"/>
    <input type="submit"/>
</form>

in my html. Where am I going wrong.

Akhil K Nambiar
  • 3,835
  • 13
  • 47
  • 85

5 Answers5

4

When you are posting a form, you should use @ModelAttribute annotation.

Change your code to :

@RequestMapping("/property")
@ResponseBody
public String property(@ModelAttribute("userDto") UserDto userDto ) {
    System.out.println(userDto.getUsername());
    System.out.println(userDto.getPassword());
    return "Hello";
}

And your HTML / JSP can be :

<form method="post" name="userDto" action="http://localhost:8080/home/property">
    <input name="username"/>
    <input name="password"/>
    <input type="submit"/>
</form>
Jeevan Patil
  • 6,029
  • 3
  • 33
  • 50
2

Request body is for when you are passing in something like a JSON or XML object (or raw data such as byte[]) to the HTTP POST. When you are POSTing form data then that is handled and parsed for you. The simplest way is to use the MVC form:form code with a command object, and then you will just receive a command object with all the entries from the form mapped to the object.

Tim B
  • 40,716
  • 16
  • 83
  • 128
1

Request mapping default method is GET. have to specify url method with RequestMapping.

@RequestMapping(value="/property",method=RequestMethod.POST)
Ingreatway
  • 145
  • 8
0

if you are getting http error 500? then try using

@RequestMapping(value = "/property", method = RequestMethod.POST )

If some other error please specify.

Mahendra
  • 323
  • 1
  • 7
-1

One way is what Jeevan suggested, or you can modify your spring to accept it like ,

UserDto userDto;
@RequestMapping("/property")
@ResponseBody
public String property(@RequestParam("username") userDto.username,  @RequestParam("password") userDto.password) {

    System.out.println(userDto.getUsername());
    System.out.println(userDto.getPassword());

    return "Hello";
}

ofcourse if you have exposed attributes in class, which is not an elegant practice.

Abhishek Anand
  • 1,940
  • 14
  • 27