与多个@ModelAttribute相同的@RequestMapping

时间:2015-01-04 20:31:09

标签: spring modelattribute

我有一个页面,我将在同一个@RequestParameter上使用多个@ModelAttribute。有没有其他方法可以解决这个问题?而不是为每个表单制作另一个JSP?

正如您在我的控制器中看到的那样,“/ acct”采用@ModeAttribute“wish”。我想要的是对我的表格使用@RequestMapping“/ account”。

这是代码。

@Controller

public class UserController {

@Autowired
private UserService userService;

@Autowired
private BlogService blogService;

@Autowired
private WishlistService wishlistService;

@ModelAttribute("blog")
public Blog constructItem(){
    return new Blog();
}

@ModelAttribute("wish")
public Wishlist constructWish(){
    return new Wishlist();
}

@RequestMapping("/account")
public String account(Model model, Principal principal){
    String name = principal.getName();
    model.addAttribute("user", userService.findOneWithBlogs(name));
    return "account";
}

@RequestMapping(value="/account", method=RequestMethod.POST)
public String doAddBlog(Model model, @Valid @ModelAttribute("blog") Blog blog, Principal principal, BindingResult result){

    if(result.hasErrors()){
        return account(model, principal);
    }
    String name = principal.getName();
    blogService.save(blog, name);
    return "redirect:/account.html";
}

@RequestMapping("/blog/remove/{id}")
public String removeBlog(@PathVariable int id){
    Blog blog = blogService.findOne(id);
    blogService.delete(blog);
    return "redirect:/account.html";
}

@RequestMapping("/acct")
public String acct(Model model, Principal principal){
    String name = principal.getName();
    model.addAttribute("user", userService.findOneWithWish(name));
    return "account";
}

@RequestMapping(value={"/acct"}, method=RequestMethod.POST)
public String doAddWish(Model model, @ModelAttribute("wish") Wishlist wish, Principal principal, BindingResult result){
    if(result.hasErrors()){
        return acct(model, principal);
    }
    String name = principal.getName();
    wishlistService.save(wish, name);
    return "redirect:/account.html";
}

}

0 个答案:

没有答案