Learner
Learner

Reputation: 21393

Using pathvariable in spring mvc 3

I am learning Spring MVC from Spring in Action 3rd Edition and came across usage of path variables. I was not clear on how it works based on the example given in the book, please help me in understanding the concept here:

@RequestMapping(method=RequestMethod.POST)
public String addSpitterFromForm(@Valid Spitter spitter, BindingResult bindingResult) {
   if(bindingResult.hasErrors()){
       return"spitters/edit";
   }
   spitterService.saveSpitter(spitter);
   return "redirect:/spitters/" + spitter.getUsername();
}

As for the path that it’s redirecting to, it’ll take the form of /spitters/{username} where {username} represents the username of the Spitter that was just submitted. For example, if the user registered under the name habuma, then they’d be redirected to /spitters/habuma after the form submission.

In above statement, it says the request is redirected to /spitters/habuma where habuma is user name.

@RequestMapping(value="/{username}",method=RequestMethod.GET)
public String showSpitterProfile(@PathVariable String username, Model model){
    model.addAttribute(spitterService.getSpitter(username));
    return "spitters/view";
}

For example, if the request path is /username/habuma, then habuma will be passed in to showSpitterProfile() for the username.

and here it says the showSpitterProfile() method handles requests for /username/habuma which is contradicting with statement that is mentioned earlier.

It looks like the first statement itself is correct, but please tell me if the method showSpitterProfile handles both the URLs i.e /splitters/habuma and /username/habuma or /spitters/username/habuma?

Upvotes: 0

Views: 173

Answers (1)

Pavel Horal
Pavel Horal

Reputation: 18183

There is no /username path component if the @RequestMapping on the class level (not shown in your question) is only @RequestMapping("/spitter"). There is probably a typo in the book. Correct sentence would be:

For example, if the request path is /spitter/habuma, then habuma will be passed in to showSpitterProfile() for the username.

Upvotes: 1

Related Questions