If it's only about generating CSV, the easiest thing is to do something like this:
class Factura {
public String toCSVRepresentation() {
StringBuilder builder = new StringBuilder();
builder
.add(getAttr1()).append(";")
.add(getAttr2()).append(";")
....
.add(getAttrN()).append(";");
return builder.toString();
}
And in your controller, after calling the service, you do this:
@RequestMapping(value= "/views/formulario", method = RequestMethod.POST, produces="text/csv")
public void obtieneDatos(@ModelAttribute("consultaForm") Factura fact, Model model, HttpServletResponse response) {
String id = fact.getId();
String cvePag=fact.getClavePago();
Date fecha = fact.getFechaInicial();
List<Factura> factList = obtieneInfoService.consultaDatos(id, cvePag, fecha);
response.addHeader("Content-Type", "application/csv");
response.addHeader("Content-Disposition", "attachment; filename=export.csv");
try {
PrintWriter out = response.getWriter();
out.write("nombreCol1;nombreCol2;...;nombreColN;");
out.write("\n");
//Versión para Java 8
//factList.forEach(result -> {
// out.write(result.toCSVRepresentation());
// out.write("\n");
//});
for(Factura result: factList) {
out.write(result.toCSVRepresentation());
out.write("\n");
}
out.flush();
out.close();
} catch (IOException ix) {
throw new RuntimeException("There was an error while retrieving CSV data", ix);
}
}
If you already had to import CSVs, then you could use a library like Jackson Dataformat (com.fasterxml.jackson.dataformat: jackson-dataformat-csv) and you could use it for both processes.