SpringMVC的Controller层获取表单数据

Controller获取表单数据有三种方法:

1. 传入Servlet的HttpServletRequest参数,并通过request.getParameter()获取请求数据。

    @RequestMapping(method = RequestMethod.GET) public String showUserMessage(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password"); return "index";
    }

2. 使用@RequestParam注解来进行添加表单字段的参数,但是如果表单字段很多,那么这种方法过于麻烦。

    @RequestMapping(method = RequestMethod.GET) public String showUserMessage(@RequestParam("username") String username, @RequestParam("password") String password) {
        System.out.println(username + "\n" + password); return "index";
    }

3. 使用@ModelAttribute添加自定义Java类型的入参(也可不使用注解)。

    @RequestMapping(method = RequestMethod.GET) public String showUserMessage(@ModelAttribute User user) {
        System.out.println(user.getUsername() + "\n" + user.getPassword()); return "index";
    }


综上,如果参数少可以使用第二种,参数超过四个则使用第三种。

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-21 17:59
点赞 评论 收藏
分享
07-07 12:25
门头沟学院 Java
程序员牛肉:你这个智邮公司做的就是那个乐山市税务系统的服务吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务