开发者

Multi Action with Form design streatgy

开发者 https://www.devze.com 2022-12-25 05:39 出处:网络
I want to have a controller that can handle multiple requests. Like a UserController handling all the addUser, deleteUser, updateUser and viewUser functionality. I know that MultiActionController can

I want to have a controller that can handle multiple requests. Like a UserController handling all the addUser, deleteUser, updateUser and viewUser functionality. I know that MultiActionController can be used to bundle multiple similar request into one controller. But the functionalities like addUser and updateUser involves user to enter data, w开发者_运维百科hich the controller need to process. Can a MultiActionController handle doSubmit kind of methods (similar to SimpleFormController). Is there any better way to handle this kind of scenario?

Thanks. Ravi


What version of Spring MVC are you using? If you are using 2.5 or higher, you should probably look into the Spring MVC annotations, which allow you to make any class be a controller with as many controller methods as you like (which can absolutely include some that handle POST requests -- "doSubmit" -- and some that handle GET requests).

Edited to add sample code:

(Note that in the samples I'm trying to use REST conventions, but that isn't required.)

within UserController.java (which need not inherit from any Spring class but should have @Controller at the top)

@RequestMapping(value = "/users/{userId}", method = RequestMethod.GET)
public String showUser(@PathVariable("userId") Long userId, ModelMap model) {       
    model.addAttribute("user", userRepository.getUser(userId));
    return "showUser";  //view name
}

    @RequestMapping(value = "/users/", method = RequestMethod.POST)
    public String createUser(@ModelAttribute("user") User user, BindingResult result, SessionStatus status) {

    new UserValidator().validate(user, result);
    if (result.hasErrors()) {
        return "userForm";
    }
    else {
        userRepository.saveUser(user);
        status.setComplete();
        return "redirect:/users/" + user.getId();`enter code here`
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消