Issue
I want to search records for two dates from the database with spring JDBC. I used where startDate=?
and endDate=?
I need to correct the controller. I am getting exception as
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver resolveException
WARNING: Resolved [org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.sql.Date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.sql.Date': no matching editors or conversion strategy found]
**`viewemp?start=2021-08-30&end=2021-09-24`**
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Event> getEmployees(Date start, Date end){
return template.query("select * from Event where startDate=? and endDate=?",new RowMapper<Event>(){
public Event mapRow(ResultSet rs, int row) throws SQLException {
Event e=new Event();
e.setEventName(rs.getString(1));
e.setEventOrgName(rs.getString(2));
e.setEventFare(rs.getInt(3));
e.setStartDate(rs.getDate(4));
e.setEndDate(rs.getDate(5));
return e;
}
});
}
}
public class Event {
private String eventName;
private String eventOrgName;
private int eventFare;
private Date startDate;
private Date endDate;
}
@Controller
public class EmpController {
@Autowired
EmpDao dao;
@GetMapping("/viewemp")
public String viewemp(@RequestParam(value="start") @DateTimeFormat(pattern="dd/MM/yyyy") Date start,
@RequestParam(value="end") @DateTimeFormat(pattern="dd/MM/yyyy") Date end, Model m){
List<Event> list=dao.getEmployees(start,end);
m.addAttribute("list",list);
return "viewemp";
}
}
<h1>Add New Employee</h1>
<form method="get" action="viewemp">
<input type="date" id="start" name="start"/>
<input type="date" id="end" name="end"/>
<input type="submit" value="Filter" />
</form>
Solution
Check your XML. You may missed <mvc:annotation-driven /> to include. And controller change to
@RestController
public class EmpController {
@Autowired
EmpDao dao;
@PostMapping("/viewemp")
public String viewemp(@RequestParam(value="start") @DateTimeFormat(pattern="yyyy-MM-dd") Date start,
@RequestParam(value="end") @DateTimeFormat(pattern="yyyy-MM-dd") Date end, Model m){
List<Event> list=dao.getEmployees(start,end);
m.addAttribute("list",list);
return "viewemp";
}
}
Answered By - Sourav