向JSP添加新的输入表单并将新参数传递给Spring控制器

时间:2017-05-03 00:25:51

标签: java spring hibernate jsp spring-mvc

不久前我尝试用Spring,Hibernate在Maven中传递一个小教程,CRUD应用程序,所以这意味着我理解这一切并不像我希望的那样好:)当我尝试时真正的问题就开始了增加项目功能并添加按用户名搜索功能。只需添加输入表单,然后将参数传递给控制器​​,稍微更改一个查询,以便从数据库中检索用户列表。但是新的参数没有在模型中描述,我无法以简单的方式添加它。我总是遇到不同的错误,我想我尝试过这样的问题,例如"将参数从JSP传递给Spring Controller"。我的恶梦中已经有@RequesMapping @ModelAttribute @PathVariable注释)) 我不知道如何正确添加新的输入表单,并将值传递给控制器​​。我想让listUsers()方法从jsp中的搜索表单中获取传递的名称。请帮助!

我的代码没有变化:

型号:

word-count

控制器类:

    public class User {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "surname")
    private String surname;

    @Column(name = "age")
    private int age;

    @Column(name = "isAdmin")
    private boolean isAdmin;

    @Column(name = "createDate")
    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    private Date createDate;

    //and getters with setters.

和jsp-page:

    @Controller
    public class UserController {
        private UserService userService;

        @Autowired(required = true)
        @Qualifier(value = "userService")
        public void setUserService(UserService userService) {
            this.userService = userService;
        }

        @RequestMapping(value = "/users", method = RequestMethod.GET)
        public String listUsers(Model model){
            model.addAttribute("user", new User());
            model.addAttribute("listUsers", this.userService.listUsers());

            return "users";
        }

        @RequestMapping(value = "/users/add", method = RequestMethod.POST)
        public String addUser(@ModelAttribute("user") User user){
             if (user.getId() == 0) {
                 this.userService.addUser(user);
             }
             else {
                 this.userService.updateUser(user);
             }

             return "redirect: /users";
        }

        @RequestMapping("/remove/{id}")
        public String removeUser(@PathVariable("id") int id){
            this.userService.removeUser(id);

            return "redirect: /users";
        }

        @RequestMapping("/edit/{id}")
        public String editUser(@PathVariable("id") int id, Model model){
            model.addAttribute("user", this.userService.getUserById(id));
            model.addAttribute("listUsers", this.userService.listUsers());

            return "users";
        }

        @RequestMapping("/userdata/{id}")
        public String userData(@PathVariable("id") int id, Model model){
            model.addAttribute("user", this.userService.getUserById(id));

            return "userdata";
    }
}

0 个答案:

没有答案