Configure ViewResolver with Spring4

1

Good morning everyone.

I am developing an application with Spring4 and Maven in Java.

And I want to add an option to export the data of a table to an excel sheet, using Apache POI.

The problem is that I do not recognize well the mapping in view of exporting the excel.

I have been following generally the steps indicated in the next link

Here I leave the following classes of my application, in case you can lend me a hand.

TaskController.java (view controller with the table I want to export

  

private Collection tasksExcel = null;

/**
 * This method will list all tasks by a user.
 */
@RequestMapping(value = { "/", "/tasklist" }, method = RequestMethod.GET)
public String listTasks(ModelMap model) {
    int id = getPrincipalUser().getId();
    Collection<Task> tasks = taskService.findAllTasksFromUser(id);
    double tasksDuration = taskService.getTasksDuration(tasks);
    double remainingHours = taskService.getRemainingHours(getPrincipalUser().getMaxHrsWeek(), tasks);

    tasksExcel = tasks;

    model.addAttribute("tasks", tasks);
    model.addAttribute("tasksDuration", tasksDuration);
    model.addAttribute("remainingHours", remainingHours);
    model.addAttribute("loggedinuser", getPrincipal());
    return "task/tasklist";
}
// Acción de exportar a excel
@RequestMapping(value = {"/exportexcel" }, method = RequestMethod.GET)
public ModelAndView exportExcel(ModelMap model) {

    return new ModelAndView("excelView", "tasks", tasksExcel);
}

tasklist.jsp (view that lists the tasks given by the controller, this is the part of the button to export to excel)

        <div class="well">
           <a href="<c:url value='/task/exportexcel' />" class="btn btn-success custom-width">Excel</a>
        </div>

ExcelBuilder.java (class that is responsible for formatting the excel sheet)

public class ExcelBuilder extends AbstractXlsView{

protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Nombre del archivo
    Date now = new Date();
    response.setHeader("Content-Disposition", "attachment; filename=\"tareas-"+now.toString()+".xls\"");

    @SuppressWarnings("unchecked")
    Collection<Task> tasks = (Collection<Task>) model.get("tasks");

    // Creamos hoja de excel
    Sheet sheet = workbook.createSheet("Tasks");

    // Creamos cabeceras de las columnas
    Row header = sheet.createRow(0);
    header.createCell(0).setCellValue("ID");
    header.createCell(1).setCellValue("Usuario");
    header.createCell(2).setCellValue("Tipo de tarea");
    header.createCell(3).setCellValue("Fecha");
    header.createCell(4).setCellValue("Duración");
    header.createCell(5).setCellValue("Última modificación");

    // Añadimos la información a las columnas
    int rowCount = 1;

    for (Task t : tasks){
        String date = new SimpleDateFormat("dd-MM-yyyy").format(t.getDate());
        String lastModification = new SimpleDateFormat("dd-MM-yyyy").format(t.getLastModification());

        Row taskRow = sheet.createRow(rowCount++);
        taskRow.createCell(0).setCellValue(t.getId());
        taskRow.createCell(1).setCellValue(t.getUser().getName());
        taskRow.createCell(2).setCellValue(t.getType());
        taskRow.createCell(3).setCellValue(date);
        taskRow.createCell(4).setCellValue(t.getDuration());
        taskRow.createCell(5).setCellValue(lastModification);
    }

}

AppConfig.java (this is where I declare the ViewResolver that the application uses)

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "incurridos")
public class AppConfig extends WebMvcConfigurerAdapter{

/**
 * Configure ViewResolvers to deliver preferred views.
 */
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {

    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");
    viewResolver.setOrder(1);
    registry.viewResolver(viewResolver);

    ResourceBundleViewResolver resolver = new ResourceBundleViewResolver();
    resolver.setBasename("views");
    resolver.setOrder(0);
    registry.viewResolver(resolver);
}

views.properties (here I indicate where is the class responsible for formatting the excel)

excelView.(class)=util.AbstractXlsView

Edit: I forgot to add the error that is shown to me when I click on the button to export to excel.

I hope I have been able to explain my situation well, anything that is not clear, I am at your disposal to clarify it.

Thank you very much in advance for the help!

    
asked by Pablo.x 15.11.2017 в 12:45
source

1 answer

1

I have a different solution that is easier for you:

My methods in the controller:

@RequestMapping(value = "/export")
public void exportExcel(HttpServletResponse response) throws IOException {
    logger.info("Exporting");           
    export(generateData(),response,"datos.xls");
}

// sólo la firma del método es relevante aquí, para darle algo de
// sentido al código a continuación
private ArrayList<MisDatos> generateData() {...}

public void export( ArrayList<MisDatos> data, HttpServletResponse response, String fileName)
        throws IOException {

    byte[] excelFileByte = getExcelFileAsBinary(data);

    // generando el fichero con lo que tengo en data, fuera del
    // alcance de la pregunta. Asumamos que se guarda en la variable
    // excelFileByte correctamente.

    response.setContentType("application/vnd.ms-excel");
    if (excelFileByte != null) {
        response.setHeader("Cache-Control", "max-age=30");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-disposition", "inline; filename=" + fileName);
        response.setContentLength(excelFileByte.length);
        ServletOutputStream out = response.getOutputStream();
        out.write(excelFileByte, 0, excelFileByte.length);
        out.flush();
        out.close();
    }
    return;
}
    
answered by 15.11.2017 / 15:23
source