I want SpringBoot to be able to send type="date" empty

Asked 1 years ago, Updated 1 years ago, 340 views

I'm creating an app with SpringBoot, and I want to be able to send it empty without entering a date.

However, if you send it empty, the type conversion from String type to Date type will be obvious, but an exception will occur and you will not be able to implement it as you wish.
Please let me know how to solve this problem.

<formth:method="post"th:action="@{/sample}"th:object="${sampleForm}">
    <input type="date" th:field="*{dateForm}">
    <button type="submit">Send</button>
</form>
@Controller
@RequestMapping("/sample")
public class SampleControl {
    @Autowired 
    private SampleService Service;
    
    @PostMapping()
    public String search(@ModelAttributeSampleFormsampleForm,Modelmodel){
        model.addAttribute("list", Service.searchForm(sampleForm)));
        return "sample";
    }
}
import java.sql.Date;

public class SampleForm {
    
    public DateForm;

    publicDateForm(){
        return dateForm;
    }
    public void setDateForm (DateForm) {
        This.dateForm=dateForm;
    }
}
@Service
@Transactional (rollbackFor=Exception.class)
public class SampleService {

    @Autowired
    SampleRepository repository;

    @PersistenceContext
    private EntityManager;

    publicList<SampleEntity>searchForm(SampleForm sampleForm){
        List<SampleEntity>list=repository.getDate(sampleForm.dateForm);
        return list;
    }
}

html spring spring-boot thymeleaf form

2022-12-23 21:08

1 Answers

If the transmission is empty, the transformation from String type to Date type is obvious, but an exception occurs

I don't know what exceptions are currently occurring, but if you send a non-empty value and it is accepted successfully, it may be considered in the conversion process implementation, so it is not a matter of course that the exception occurs.

Otherwise, if there is an exception to the non-empty value, that is, if the conversion process is not correct/implemented in the first place, you should take the following action:

  • @DateTimeFormat to indicate the date format
  • Using java.util.Date instead of
  • java.sql.Date

Specifically, implement SampleForm as follows:

import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;


public class SampleForm {

    @ DateTimeFormat (iso=DateTimeFormat.ISO.DATE)
    private DateForm;

    // getter and setter
}


2022-12-23 22:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.