Q:

Difference between @PathVariable and @ModelAttribute

I'm confused with @PathVariable and @ModelAttribute in SpringFramework. Can I know what are the differences between?

A:

1) @PathVariable

Annotation which indicates that a method parameter should be bound to a URI template variable

ex: You have one URL like this http:/myweb/transferfund/john/john123
@RequestMapping(value = "/transferfund/{user}/john123")
public String index(@PathVariable String user){
System.out.println("Logged User :"+user);
}

Base on above example,you can get the variable from URI using @PathVariable which in this case will print out john.
You also can fetch another part of URI like this;
@RequestMapping(value = "/transferfund/john/{userID}")
@RequestMapping(value = "/{transaction}/john/john123")

You even can do like this:
@RequestMapping(value = "/{transaction}")

which will catch any URl that doesnt have their own @RequestMapping
2) @ModelAttribute

Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view

ex: You have one form:
<form:form action="/addUser" modelAttribute="userInfo">
<form:input path="name" value="John Doe">
<form:input path="id" value="john123">
</form:form>

And in your @RequestMapping
 @RequestMapping(value = "/addUser")
        public String index(@ModelAttribute("userInfo") User userinfo){
        System.out.println("Registered User :"+userinfo.getUserName());
        }

Based on the example,the system will print out Registered User : John Doe
But you need this spring taglib to use @ModelAttribute :
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

Have fun.

