SpringMVC如何獲取表單數據(radio和checkbox)

SpringMVC獲取表單數據

1、實體類

package cn.hadron.bean;
import java.io.Serializable;
import java.util.Arrays;
/**
 * create table users(
     id int auto_increment primary key,
     username varchar(45),
     password varchar(45),
     age int default 0
   );
   insert into users(username,password,age) values('hadron','123',18);
 * @author chengyq
 *
 */
// 域對象,實現序列化接口
public class UserBean implements Serializable {
    private Integer id;
    private String username;
    private String password;
    private String birthday;
    private Integer age;
    //測試單選按鈕
    private String sex;
    //測試復選按鈕
    private String[] favorite;
    public UserBean() {}
    public UserBean(String username, String password,int age) {
        this.username = username;
        this.password = password;
        this.age=age;
    }
    public UserBean(String username, String birthday,String sex) {
        this.username = username;
        this.birthday = birthday;
        this.sex=sex;
    }
    public Integer getId() {
        return id;
    }
    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
    public Integer getAge() {
        return age;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String[] getFavorite() {
        return favorite;
    }
    public void setFavorite(String[] favorite) {
        this.favorite = favorite;
    }
    public String getBirthday() {
        return birthday;
    }
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "UserBean{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday='" + birthday + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", favorite=" + Arrays.toString(favorite) +
                '}';
    }
}

2、控制器

package cn.hadron.controller;
import cn.hadron.bean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping(value = "/f")
public class FormController {
    @RequestMapping(value="/getEditPage",method= RequestMethod.GET)
    public String getEditPage(Model model) {
        System.out.println("表單測試");
        UserBean user = new UserBean("jack","1997-7-1","女");
        // model中添加屬性user,值是user對象
        model.addAttribute("user",user);
        //返回Edit.jsp頁面
        return "edit";
    }
    @RequestMapping(value="/edit",method=RequestMethod.POST)
    public String edit(@ModelAttribute UserBean user,Model model) {
        System.out.println("獲取表單數據:");
        //@ModelAttribute註解指示瞭參數應該從模型(這裡所說的“模型”指 Model)中獲取
        model.addAttribute("username", user.getUsername());
        model.addAttribute("birthday", user.getBirthday());
        model.addAttribute("sex", user.getSex());
        model.addAttribute("favorite", user.getFavorite());
        System.out.println("user="+user);
        //返回userPage.jsp頁面
        return "userPage";
    }
    /**
     * 可以用@ModelAttribute註解的方法做一些初始化操作。
     * 當同一個controller中有多個方法被@ModelAttribute註解標記,
     * 所有被@ModelAttribute標記的方法均會被執行,按先後順序執行,然後再進入請求的方法
     * @return
     */
    @ModelAttribute("webList")
    public List<String> getWebList() {
        List<String> webList = new ArrayList<String>();
        webList.add("SpringMVC");
        webList.add("SpringBoot");
        webList.add("SpringCloud");
        return webList;
    }
}

3、頁面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>測試form標簽</title>
</head>
<body>
<h3>用戶信息編輯頁面</h3>
<form:form modelAttribute="user" method="post" action="/elastic/f/edit.do" >
    <table>
        <tr>
            <td>姓名:</td>
            <td><form:input path="username"/></td>
        </tr>
        <tr>
            <td>性別:</td>
            <td>
                <form:radiobutton path="sex" value="男" label="男" />
                <form:radiobutton path="sex" value="女" label="女" />
            </td>
        </tr>
        <tr>
            <td>生日:</td>
            <td><form:input path="birthday"/></td>
        </tr>
        <tr>
            <td>愛好:</td>
            <td><form:checkboxes items="${webList}" path="favorite" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="提交變更"/>
            </td>
        </tr>
    </table>
</form:form>
</body>
</html>

這裡寫圖片描述

<%--
  Created by IntelliJ IDEA.
  User: chengyq
  Date: 2018/9/3
  Time: 14:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>您提交的用戶信息</h2>
<table>
    <tr>
        <td>Username</td>
        <td>${username}</td>
    </tr>
    <tr>
        <td>Birthday</td>
        <td>${birthday}</td>
    </tr>
    <tr>
        <td>Sex</td>
        <td>${sex}</td>
    </tr>
    <tr>
        <td>favorite</td>
        <td>
            <%
                String[] favorite = (String[])request.getAttribute("favorite");
                for(String f: favorite) {
                    out.println(f);
                }
            %>
        </td>
    </tr>
</table>
</body>
</html>

這裡寫圖片描述

SpringMVC獲取表單參數

以下幾種方式隻有在已搭好的SpringMVC環境中,才能執行成功!

一、首先,寫一個登陸頁面和一個Bean類

登陸頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>yyx博客後臺登錄</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/user/login.do"
        method="post">
        <table>
            <tr>
                <td>用戶名:</td>
                <td><input type="text"  name="userName"></td>
            </tr>
            <tr>
                <td>密碼:</td>
                <td><input type="password"  name="userPwd"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="登陸"></td>
            </tr>
        </table>
    </form>
</body>
</html>

java實體類

package com.yyx.model;
 
public class User{
    private String userName;
    private String userPwd;
 
    public String getUserName() {
        return userName;
    }
 
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    public String getUserPwd() {
        return userPwd;
    }
 
    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
}

二、獲取表單數據的方法

1、直接把表單的參數寫在Controller相應的方法的形參中

註意:控制器中方法的形參String userName,String userPwd名稱必須和登陸頁面的name=”userName”,name=”userPwd”相同

package com.yyx.controller; 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; 
@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/login")
    public String loginByUser(String userName, String userPwd) {
        System.out.println("userName is:" + userName);
        System.out.println("userPwd is:" + userPwd);
        return "success";
    }
}

2.通過HttpServletRequest接收

控制器中

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

的參數名稱必須和登陸頁面的name=”userName”,name=”userPwd”相同

package com.yyx.controller; 
import javax.servlet.http.HttpServletRequest; 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/login")
    public String loginByUser(HttpServletRequest request) {
        String userName=request.getParameter("userName");
        String userPwd=request.getParameter("userPwd");
        System.out.println("userName is:" + userName);
        System.out.println("userPwd is:" + userPwd);
        return "success";
    }
}

3.通過一個bean來接收

登陸頁面的name=”userName”,name=”userPwd”必須和Bean類的屬性名稱相同

package com.yyx.controller; 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; 
import com.yyx.model.User;
 
@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/login")
    public String loginByUser(User user) {
        System.out.println("userName is:" + user.getUserName());
        System.out.println("userPwd is:" + user.getUserPwd());
        return "success";
    }
}

4.利用js中ajax請求通過json數據接收

在頁面中添加js代碼

<script type="text/javascript"
    src="${pageContext.request.contextPath}/static/jquery-3.1.1.min.js"></script>  
<script type="text/javascript">
    $(document).ready(function() {
        $("#button_submit").click(function() {
            var name = $("#userName").val();
            var pwd = $("#userPwd").val();
            var user = {
                userName : name,
                userPwd : pwd
            };//拼裝成json格式
            $.ajax({
                type : "POST",
                url : "${pageContext.request.contextPath}/user/login.do",
                data : user,
                success : function(data) {
                    alert("成功");
                },
                error : function(e) {
                    alert("出錯:" + e);
                }
            });
        });
    });
</script>

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

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: