SpringMVC如何获取表单数据(radio和checkbox)

时间:2022-09-13 12:16:18

SpringMVC获取表单数据

1、实体类

  1. package cn.hadron.bean;
  2. import java.io.Serializable;
  3. import java.util.Arrays;
  4. /**
  5. * create table users(
  6. id int auto_increment primary key,
  7. username varchar(45),
  8. password varchar(45),
  9. age int default 0
  10. );
  11. insert into users(username,password,age) values('hadron','123',18);
  12. * @author chengyq
  13. *
  14. */
  15. // 域对象,实现序列化接口
  16. public class UserBean implements Serializable {
  17. private Integer id;
  18. private String username;
  19. private String password;
  20. private String birthday;
  21. private Integer age;
  22. //测试单选按钮
  23. private String sex;
  24. //测试复选按钮
  25. private String[] favorite;
  26. public UserBean() {}
  27. public UserBean(String username, String password,int age) {
  28. this.username = username;
  29. this.password = password;
  30. this.age=age;
  31. }
  32. public UserBean(String username, String birthday,String sex) {
  33. this.username = username;
  34. this.birthday = birthday;
  35. this.sex=sex;
  36. }
  37. public Integer getId() {
  38. return id;
  39. }
  40. public String getUsername() {
  41. return username;
  42. }
  43. public String getPassword() {
  44. return password;
  45. }
  46. public Integer getAge() {
  47. return age;
  48. }
  49. public void setId(Integer id) {
  50. this.id = id;
  51. }
  52. public void setUsername(String username) {
  53. this.username = username;
  54. }
  55. public void setPassword(String password) {
  56. this.password = password;
  57. }
  58. public void setAge(Integer age) {
  59. this.age = age;
  60. }
  61. public String getSex() {
  62. return sex;
  63. }
  64. public void setSex(String sex) {
  65. this.sex = sex;
  66. }
  67. public String[] getFavorite() {
  68. return favorite;
  69. }
  70. public void setFavorite(String[] favorite) {
  71. this.favorite = favorite;
  72. }
  73. public String getBirthday() {
  74. return birthday;
  75. }
  76. public void setBirthday(String birthday) {
  77. this.birthday = birthday;
  78. }
  79. @Override
  80. public String toString() {
  81. return "UserBean{" +
  82. "id=" + id +
  83. ", username='" + username + '\'' +
  84. ", password='" + password + '\'' +
  85. ", birthday='" + birthday + '\'' +
  86. ", age=" + age +
  87. ", sex='" + sex + '\'' +
  88. ", favorite=" + Arrays.toString(favorite) +
  89. '}';
  90. }
  91. }

2、控制器

  1. package cn.hadron.controller;
  2. import cn.hadron.bean.UserBean;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.ModelAttribute;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. @Controller
  11. @RequestMapping(value = "/f")
  12. public class FormController {
  13. @RequestMapping(value="/getEditPage",method= RequestMethod.GET)
  14. public String getEditPage(Model model) {
  15. System.out.println("表单测试");
  16. UserBean user = new UserBean("jack","1997-7-1","女");
  17. // model中添加属性user,值是user对象
  18. model.addAttribute("user",user);
  19. //返回Edit.jsp页面
  20. return "edit";
  21. }
  22. @RequestMapping(value="/edit",method=RequestMethod.POST)
  23. public String edit(@ModelAttribute UserBean user,Model model) {
  24. System.out.println("获取表单数据:");
  25. //@ModelAttribute注解指示了参数应该从模型(这里所说的“模型”指 Model)中获取
  26. model.addAttribute("username", user.getUsername());
  27. model.addAttribute("birthday", user.getBirthday());
  28. model.addAttribute("sex", user.getSex());
  29. model.addAttribute("favorite", user.getFavorite());
  30. System.out.println("user="+user);
  31. //返回userPage.jsp页面
  32. return "userPage";
  33. }
  34. /**
  35. * 可以用@ModelAttribute注解的方法做一些初始化操作。
  36. * 当同一个controller中有多个方法被@ModelAttribute注解标记,
  37. * 所有被@ModelAttribute标记的方法均会被执行,按先后顺序执行,然后再进入请求的方法
  38. * @return
  39. */
  40. @ModelAttribute("webList")
  41. public List<String> getWebList() {
  42. List<String> webList = new ArrayList<String>();
  43. webList.add("SpringMVC");
  44. webList.add("SpringBoot");
  45. webList.add("SpringCloud");
  46. return webList;
  47. }
  48. }

3、页面

  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <meta charset="UTF-8">
  7. <title>测试form标签</title>
  8. </head>
  9. <body>
  10. <h3>用户信息编辑页面</h3>
  11. <form:form modelAttribute="user" method="post" action="/elastic/f/edit.do" >
  12. <table>
  13. <tr>
  14. <td>姓名:</td>
  15. <td><form:input path="username"/></td>
  16. </tr>
  17. <tr>
  18. <td>性别:</td>
  19. <td>
  20. <form:radiobutton path="sex" value="男" label="男" />
  21. <form:radiobutton path="sex" value="女" label="女" />
  22. </td>
  23. </tr>
  24. <tr>
  25. <td>生日:</td>
  26. <td><form:input path="birthday"/></td>
  27. </tr>
  28. <tr>
  29. <td>爱好:</td>
  30. <td><form:checkboxes items="${webList}" path="favorite" /></td>
  31. </tr>
  32. <tr>
  33. <td colspan="2">
  34. <input type="submit" value="提交变更"/>
  35. </td>
  36. </tr>
  37. </table>
  38. </form:form>
  39. </body>
  40. </html>

SpringMVC如何获取表单数据(radio和checkbox)

  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: chengyq
  4. Date: 2018/9/3
  5. Time: 14:27
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  9. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
  10. <html>
  11. <head>
  12. <title>Title</title>
  13. </head>
  14. <body>
  15. <h2>您提交的用户信息</h2>
  16. <table>
  17. <tr>
  18. <td>Username</td>
  19. <td>${username}</td>
  20. </tr>
  21. <tr>
  22. <td>Birthday</td>
  23. <td>${birthday}</td>
  24. </tr>
  25. <tr>
  26. <td>Sex</td>
  27. <td>${sex}</td>
  28. </tr>
  29. <tr>
  30. <td>favorite</td>
  31. <td>
  32. <%
  33. String[] favorite = (String[])request.getAttribute("favorite");
  34. for(String f: favorite) {
  35. out.println(f);
  36. }
  37. %>
  38. </td>
  39. </tr>
  40. </table>
  41. </body>
  42. </html>

SpringMVC如何获取表单数据(radio和checkbox)

SpringMVC获取表单参数

以下几种方式只有在已搭好的SpringMVC环境中,才能执行成功!

一、首先,写一个登陆页面和一个Bean类

登陆页面

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3.  
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>yyx博客后台登录</title>
  9. </head>
  10. <body>
  11. <form action="${pageContext.request.contextPath}/user/login.do"
  12. method="post">
  13. <table>
  14. <tr>
  15. <td>用户名:</td>
  16. <td><input type="text" name="userName"></td>
  17. </tr>
  18. <tr>
  19. <td>密码:</td>
  20. <td><input type="password" name="userPwd"></td>
  21. </tr>
  22. <tr>
  23. <td colspan="2"><input type="submit" value="登陆"></td>
  24. </tr>
  25. </table>
  26. </form>
  27. </body>
  28. </html>

java实体类

  1. package com.yyx.model;
  2.  
  3. public class User{
  4. private String userName;
  5. private String userPwd;
  6.  
  7. public String getUserName() {
  8. return userName;
  9. }
  10.  
  11. public void setUserName(String userName) {
  12. this.userName = userName;
  13. }
  14.  
  15. public String getUserPwd() {
  16. return userPwd;
  17. }
  18.  
  19. public void setUserPwd(String userPwd) {
  20. this.userPwd = userPwd;
  21. }
  22. }

二、获取表单数据的方法

1、直接把表单的参数写在Controller相应的方法的形参中

注意:控制器中方法的形参String userName,String userPwd名称必须和登陆页面的name="userName",name="userPwd"相同

  1. package com.yyx.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. @Controller
  5. @RequestMapping("/user")
  6. public class UserController {
  7. @RequestMapping("/login")
  8. public String loginByUser(String userName, String userPwd) {
  9. System.out.println("userName is:" + userName);
  10. System.out.println("userPwd is:" + userPwd);
  11. return "success";
  12. }
  13. }

2.通过HttpServletRequest接收

控制器中

  1. String userName=request.getParameter("userName");
  2. String userPwd=request.getParameter("userPwd");

的参数名称必须和登陆页面的name="userName",name="userPwd"相同

  1. package com.yyx.controller;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5.  
  6. @Controller
  7. @RequestMapping("/user")
  8. public class UserController {
  9. @RequestMapping("/login")
  10. public String loginByUser(HttpServletRequest request) {
  11. String userName=request.getParameter("userName");
  12. String userPwd=request.getParameter("userPwd");
  13. System.out.println("userName is:" + userName);
  14. System.out.println("userPwd is:" + userPwd);
  15. return "success";
  16. }
  17. }

3.通过一个bean来接收

登陆页面的name="userName",name="userPwd"必须和Bean类的属性名称相同

  1. package com.yyx.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import com.yyx.model.User;
  5.  
  6. @Controller
  7. @RequestMapping("/user")
  8. public class UserController {
  9. @RequestMapping("/login")
  10. public String loginByUser(User user) {
  11. System.out.println("userName is:" + user.getUserName());
  12. System.out.println("userPwd is:" + user.getUserPwd());
  13. return "success";
  14. }
  15. }

4.利用js中ajax请求通过json数据接收

在页面中添加js代码

  1. <script type="text/javascript"
  2. src="${pageContext.request.contextPath}/static/jquery-3.1.1.min.js"></script>
  3. <script type="text/javascript">
  4. $(document).ready(function() {
  5. $("#button_submit").click(function() {
  6. var name = $("#userName").val();
  7. var pwd = $("#userPwd").val();
  8. var user = {
  9. userName : name,
  10. userPwd : pwd
  11. };//拼装成json格式
  12. $.ajax({
  13. type : "POST",
  14. url : "${pageContext.request.contextPath}/user/login.do",
  15. data : user,
  16. success : function(data) {
  17. alert("成功");
  18. },
  19. error : function(e) {
  20. alert("出错:" + e);
  21. }
  22. });
  23. });
  24. });
  25. </script>

控制器中的代码和方法3中的相同。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/chengyuqiang/article/details/82348542