Tengo el siguiente método en el controller, el cual regresa un respuesta tipo json a la vista, para mostrar en un dialogo si hay o no datos en la bd de acuerdo a la informacion de los parámetros que le paso a mi servicio.
@RequestMapping(value="view/obtieneInfo")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public JsonResponse obtieneInfor(@ResponseBody Factura fact, HttpServletRequest request, HttpServletResponse respons) throws ControlException{
JsonResponse response = new JsonResponse();
response.setExito(0);
response.setDatos(null);
try{
List<Factura> factList = obtieneInfoService.consultaDatos(id, cvePag, fecha);
if(factList !=null && !factList.isEmpty){
response.setExito(1);
response.setDatos(factList);
}else{
log.info("Esta vacio");
}
}catch(ControlException e){
throw new ControlException("Error", e);
}
return response;
}
Este es mi código de la vista, el cual valida campos y cuando se llenan los campos y se da click en el boton, se le pasan esos parámetros al servicio, y manda un dialogo para informar si hay o no datos, y si los hay que descargue un archivo con esos datos
<script>
function consultar(){
var valido = true;
var valId = document.getElementaryById('idPago').value;
var valClavePago = document.getElementaryById('clavePago').value;
var valFecha = document.getElementaryById('fechaPago').value;
if(valId.trim() =="" && valClavePago.trim() == "" && valFecha.trim() == ""){
HelperDialogs.mostrar("Debes ingresar al menos un valor");
valido = false;
}
return valido;
}
function obtieneInf(){
if(consultar()){
if(!HelperForm.valido(consulta, validator)){
return;
}else{
var data = Helper.obtenerJsonForm(consulta);
var url="${pageContext.request.contextPath}/view/obtieneInfo";
$.ajax({
type:"POST",
contentType: "application/json",
url: url,
data: data,
dataType: 'json',
success: function(response){
if(response.exito==1){
HelperDialogo.mostrar("Si hay registros");
}else{
HelperDialogo.mostrar("No se encontraron registros");
}
},
error: function(response){
HelperDialogo.mostrarError(response);
}
});
}
}
}
</script>
<form:form id="consulta" modelAttribute="consultaForm">
<tr>
<td><label>ID/label></td>
<td><form: input type="text" id="idPago" path="id"/></td>
</tr>
<tr>
<td><label>CLAVE PAGO</label></td>
<td><form: input type="text" id="clavePago" path="clavePago"/></td>
</tr>
<tr>
<tr>
<td><label>FECHA PAGO</label></td>
<td><form: input type="text" id="fechaPago" path="fechaPago"/></td>
<input type="button" onclick="obtieneInf()"></input>
</tr>
</form:form>
Y lo hace de forma correcta, el problema se presenta al momento de agregarle el código para que realice la descarga de un archivo con la informacion que regresa la consulta, el código queda así:
@RequestMapping(value="view/obtieneInfo")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public JsonResponse obtieneInfor(@ResponseBody Factura fact, HttpServletRequest request, HttpServletResponse respons) throws ControlException{
JsonResponse response = new JsonResponse();
response.setExito(0);
response.setDatos(null);
try{
List<Factura> factList = obtieneInfoService.consultaDatos(id, cvePag, fecha);
if(factList !=null && !factList.isEmpty){
response.setExito(1);
response.setDatos(factList);
response.addHeader("Content-Type", "application/csv");
response.addHeader("Content-Disposition", "attachment; filename=archivo.csv");
PrintWriter out = response.getWriter();
out.write("columna1,columna2,columna3");
out.write("\n");
for(Factura factu: factList){
out.write(factu.toCSVRepresentation());
out.write("\n");
}
out.flush();
out.close();
}else{
log.info("Esta vacio");
}
}catch(ControlException e){
throw new ControlException("Error", e);
}
return response;
}
y manda ese error: servlet API cannot call getOutputStream() after getWriter()
a que se debe ese error?, que me hace falta? y es que ademas, si hago la descarga del archivo en este mismo método ,este va a contener todo el html de la pagina, y la informacion de la consulta
entonces mejor borre el código de la descarga del archivo en el metodo json, y agregue otro método igual al anterior, pero void, y así el archivo ya no contiene todo el html de la pagina, pero no recoge los datos de los input, los deja como null y pues no hace nada
Este es el nuevo método que agregue, pero no recoge los datos de los input, y me manda mensaje de que no hay datos, por que estan nullos, ademas pues estaría repitiendo código, como le puedo hacer?, o cual es la manera correcta de hacer la descarga del archivo?
@RequestMapping(value="view/obtieneArchivo")
public void obtieneArchivo(@ResponseBody Factura fact, HttpServletRequest request, HttpServletResponse response) throws ControlException{
try{
List<Factura> factList = obtieneInfoService.consultaDatos(id, cvePag, fecha);
if(factList !=null && !factList.isEmpty){
response.addHeader("Content-Type", "application/csv");
response.addHeader("Content-Disposition", "attachment; filename=archivo.csv");
PrintWriter out = response.getWriter();
out.write("columna1,columna2,columna3");
out.write("\n");
for(Factura factu: factList){
out.write(factu.toCSVRepresentation());
out.write("\n");
}
out.flush();
out.close();
}else{
log.info("Esta vacio");
}
}catch(ControlException e){
throw new ControlException("Error", e);
}
}
y agregue esta funcion a mi jsp
function descargaArchivo(){
var url="${pageContext.request.contextPath}/view/obtieneArchivo";
$.fileDownload(url)
.done(
function(){
Helper.muestraInf("Se descargo correctamente");
}
)
.fail(
function(){
Helper.muestraInf("Ocurrio un error en la descarga");
}
);
}
Ojala me puedan ayudar, apenas empiezo con esto y no entiendo muchas cosas, gracias