在JAVA SSM框架中 如何使用SpringMvc 的数据验证,你看这篇就够了

<dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.1.5.Final</version>
    </dependency>
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>2.0.1.Final</version>
    </dependency>

 

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
        <property name="validationMessageSource" ref="messageSource"></property>
    </bean>

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>classpath:config</value>
            </list>
        </property>
        <property name="defaultEncoding" value="utf-8" />
        <property name="cacheSeconds" value="120" />
    </bean>

    <mvc:annotation-driven validator="validator"></mvc:annotation-driven>
package com.dzeco.bean;

import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.thymeleaf.util.Validate;
import sun.plugin2.message.Message;

import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @autohr Alex
 * @create 2020-09-24 14:36
 */
public class Employee {

    private Integer id;

    @Length(min=2,max = 5,message = "姓名{validator.length}在{min}到{max}之间")
    @NotEmpty(message="姓名不能为空")
    private String name;
    private Integer gender;
    @NotEmpty(message = "请填写地址")
    private String address;

    private Department dept;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date addTime;
    @NumberFormat(style = NumberFormat.Style.NUMBER,pattern = "##.##")
    private BigDecimal saraly;

    public Employee(Integer id, String name, Integer gender, String address,Department department,Date addTime,BigDecimal saraly) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.address = address;
        this.dept=department;
        this.addTime=addTime;
        this.saraly=saraly;
    }

    public Employee() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Department getDept() {
        return dept;
    }

    public void setDept(Department dept) {
        this.dept = dept;
    }

    public Date getAddTime() {
        return addTime;
    }

    public void setAddTime(Date addTime) {
        this.addTime = addTime;
    }

    public BigDecimal getSaraly() {
        return saraly;
    }

    public void setSaraly(BigDecimal saraly) {
        this.saraly = saraly;
    }
}

 

config.properties validator.length=字符数控制在

 

package com.dzeco.controller;

import com.dzeco.bean.Department;
import com.dzeco.bean.Employee;
import com.dzeco.bean.Student;
import com.dzeco.service.DepartmentService;
import com.dzeco.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @autohr Alex
 * @create 2020-09-24 15:06
 */
@Controller
public class EmployeeHandler {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartmentService departmentService;
    @RequestMapping("/index")
    public String index(Map<String,Object> map){
        map.put("employees",employeeService.getAll());
        return "index";
    }

    @RequestMapping(value = "/show/{id}",method = RequestMethod.GET)
    public String show(@PathVariable("id") Integer id, Model model){
        Employee emp=employeeService.getById(id);
        model.addAttribute("Employee",emp);
        return "show";
    }

    /**
     * 编辑
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
    public String edit(@PathVariable("id") Integer id,Model model){
        Employee emp=employeeService.getById(id);
        model.addAttribute("Employee",emp);
        model.addAttribute("department",departmentService.getAll());
        return "edit";
    }

    /**
     * 添加
     * @param model
     * @return
     */
    @RequestMapping(value = "/add/",method = RequestMethod.GET)
    public String add(Model model){
        model.addAttribute("department",departmentService.getAll());
        return "edit";
    }
    @PostMapping(value = "/add")
    public String save(@Validated Employee employee, BindingResult result, Model model){
        if(result.hasErrors()){
            Map<String, Object> map=new HashMap<String, Object>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError:fieldErrors) {

                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            Collection<Object> values = map.values();

            model.addAttribute("ab",map);
            model.addAttribute("department",departmentService.getAll());
            model.addAttribute("Employee",employee);
           return "edit";
        }else{
            Department dept=departmentService.getById(employee.getDept().getId());
            employee.setDept(dept);
            employeeService.save(employee);
       }

        return "redirect:/index";
    }

    @PostMapping(value = "/save")
    public String update(Employee employee){
        Department dept=departmentService.getById(employee.getDept().getId());
        employee.setDept(dept);
        employeeService.save(employee);
        return "redirect:/index";
    }

    @PostMapping("/con")
    @ResponseBody
    public String testconvert(@RequestParam("Student") Student student){
        System.out.println(student);
        return "ok";
    }
    @RequestMapping("/test")
    public String showtest(){
        return "test";
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值