当前位置: 移动技术网 > IT编程>开发语言>Java > [Spring MVC] -简单表单提交实例

[Spring MVC] -简单表单提交实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

spring mvc自带的表单标签比较简单,很多时候需要借助el和jstl来完成。

下面是一个比较简单的表单提交页面功能: 

1、user model

package com.my.controller.bean;

import java.util.date;
import java.util.list;

import javax.validation.constraints.future;
import javax.validation.constraints.max;
import javax.validation.constraints.min;
import javax.validation.constraints.notnull;

import org.hibernate.validator.constraints.email;
import org.hibernate.validator.constraints.length;
import org.hibernate.validator.constraints.notempty;

public class user {
  
  private long id;
  
  @length(min=2, max=50, message="user name length range = 2-50")
  private string name;
  
  @future(message="时间不能小于今天")
  private date createtime;
  
  @notempty(message="customer不能为空")
  private list<customer> customers;
  
  @notnull(message="girl不能为空")
  private boolean girl;
  
  private string[] cbx;
  
  @notnull(message="age can not be null")
  @min(value=18, message="最小18岁")
  @max(value=100, message="最大100岁")
  private int age;
  
  @email(message="email格式不正确")
  private string email;
  
  public long getid() {
    return id;
  }
  public void setid(long id) {
    this.id = id;
  }
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public date getcreatetime() {
    return createtime;
  }
  public void setcreatetime(date createtime) {
    this.createtime = createtime;
  }
  public list<customer> getcustomers() {
    return customers;
  }
  public void setcustomers(list<customer> customers) {
    this.customers = customers;
  }
  public boolean isgirl() {
    return girl;
  }
  public void setgirl(boolean girl) {
    this.girl = girl;
  }
  public string[] getcbx() {
    return cbx;
  }
  public void setcbx(string[] cbx) {
    this.cbx = cbx;
  }
  public int getage() {
    return age;
  }
  public void setage(int age) {
    this.age = age;
  }
  public string getemail() {
    return email;
  }
  public void setemail(string email) {
    this.email = email;
  }

}

2、controller

package com.my.controller;

import java.util.arraylist;
import java.util.date;
import java.util.list;

import javax.validation.valid;

import org.springframework.stereotype.controller;
import org.springframework.validation.bindingresult;
import org.springframework.validation.fielderror;
import org.springframework.web.bind.annotation.modelattribute;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.servlet.modelandview;

import com.my.controller.bean.customer;
import com.my.controller.bean.user;

@controller
@requestmapping(value="/post")
public class testpostcontroller {
  
  private static list<user> users = new arraylist<user>();
  {
    //-----------------------------------------------
    // 设置entity
    // -----------------------------------------------
    users.add(new user());
    user user = users.get(0);
    user.setid(1);
    user.setname("robin");
    user.setcreatetime(new date());
    user.setgirl(true);
    user.setcbx(new string[] {"1", "2", "3"});
    user.setage(18);
    user.setemail("abcd@abc.com");
    
    user.setcustomers(new arraylist<customer>());
    customer customer1 = new customer();
    customer1.setid(1);
    customer1.setcompany("company - 1");
    customer1.setcreatetime(new date());
    customer1.setuser(user);
    user.getcustomers().add(customer1);
    
    customer customer2 = new customer();
    customer2.setid(1);
    customer2.setcompany("company - 2");
    customer2.setcreatetime(new date());
    customer2.setuser(user);
    user.getcustomers().add(customer2);
  }
  
  @requestmapping
  public modelandview index() {
    modelandview view = new modelandview("testpost/index");
    view.addobject("users", users);
    return view;
  }
  
  @requestmapping(value="/adduser", method=requestmethod.post)
  public modelandview adduser(@modelattribute @valid user user, bindingresult result) {
    modelandview view = new modelandview("redirect:/post");
    
    if(result.haserrors()) {
      list<fielderror> errors = result.getfielderrors();
      for(fielderror err : errors) {
        system.out.println("objectname:" + err.getobjectname() + "\tfieldname:" + err.getfield()
            + "\tfieldvalue:" + err.getrejectedvalue() + "\tmessage:" + err.getdefaultmessage());
      }
      view.addobject("users", users);
      return view;
    }
    
    user.setid(users.size() + 1);
    user.getcustomers().get(0).setid(1);
    user.getcustomers().get(0).setuser(user);
    users.add(user);
    view.addobject("users", users);
    return view;
  }
  
}

3、view

<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%>
<%@ page import="com.my.controller.bean.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="st" uri="http://www.springframework.org/tags" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>

<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>index</title>
</head>
<body>
  <fmt:setlocale value="zh_cn" />
  <form action="<st:url value="/post/adduser"></st:url>" method="post">
    <c:foreach items="${users}" var="user">
      user:${user.name}<br/>
      create time:<fmt:formatdate value="${user.createtime}"/><br/>
      is girl:
      <c:choose>
        <c:when test="${user.girl}">yes</c:when>
        <c:when test="${!user.girl}">no</c:when>
        <c:otherwise>n/a</c:otherwise>
      </c:choose>
      <br/>
      checkboxs:
      <c:foreach items="${user.cbx}" var="item">
        ${item},
      </c:foreach>
      <br/>
      age:${user.age}<br/>
      e-mail:${user.email}<br/>
      <hr/>
    
      <table style="width:100%;border:1px solid #ccc;">
        <thead>
          <tr style="text-align:left; background-color:#eee;">
            <th>company name</th>
            <th>user</th>
            <th>create time</th>
          </tr>
        </thead>
        <tbody>
          <c:foreach items="${user.customers}" var="item">
          <tr>
            <td>${item.company}</td>
            <td>${item.user.name}</td>
            <td><fmt:formatdate value="${item.createtime}" pattern="yyyy-mm-dd"/></td>
          </tr>
          </c:foreach>
        </tbody>
      </table>
      <hr/>
    </c:foreach>
    
    user name:
    <input type="text" name="name" id="name" /><br/>
    is girl:
    <input type="radio" name="girl" id="isgirl" value="true" checked="checked" /><label for="isgirl">yes</label>
    <input type="radio" name="girl" id="nogirl" value="false" /><label for="nogirl">no</label><br/>
    checkboxs:
    <input type="checkbox" name="cbx" id="cbx1" value="1" /><label for="cbx1">1</label>
    <input type="checkbox" name="cbx" id="cbx2" value="2" /><label for="cbx2">2</label>
    <input type="checkbox" name="cbx" id="cbx3" value="3" /><label for="cbx3">3</label>
    <br/>
    age:<input type="text" name="age" id="age" /><br/>
    e-mail:<input type="text" name="email" id="email" /><br/>
    create time:
    <input type="text" name="createtime" id="createtime" /><br/>
    company:
    <input type="text" name="customers[0].company" id="customers[0].company" /><br/>
    <input type="submit" value="add" />
    <sf:errors path="*"></sf:errors>
  </form>
  <hr/>
</body>
</html>

4、测试结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网