Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Post Request

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.

like image 376
Akhil K Nambiar Avatar asked Dec 11 '13 09:12

Akhil K Nambiar


3 Answers

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>
like image 184
Jeevan Patil Avatar answered Oct 06 '22 00:10

Jeevan Patil


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.

like image 28
Tim B Avatar answered Oct 06 '22 00:10

Tim B


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

@RequestMapping(value="/property",method=RequestMethod.POST)
like image 35
Ingreatway Avatar answered Oct 05 '22 23:10

Ingreatway