title: spring Java config for excel view resolver
body: <p>I have a spring java config based  web app with (jsp) view resolver.
    Now i want to show a excel sheet with some data when user clicks on excel icon in app.
    All over internet i only found xml based spring config for excel view with which i am not familiar with. 
    I decoded to some extent and came pretty close to get my task done. Below is what i got.</p>
  
  <p>I have similar controller and Homepage following the below link:</p>
  
  <p><a href="http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch17s06.html">http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch17s06.html</a></p>
  
  <p>Controlle Code:</p>
  
  <pre><code>@Controller
  public class ExcelController extends AbstractController {
  
  @Override
  @RequestMapping(value = "/Excel", method = RequestMethod.POST)
  protected ModelAndView handleRequestInternal(HttpServletRequest request,
          HttpServletResponse response) throws Exception {
      BufferedReader in = null;
       try {
              URL oracle = new URL("example.com");
              URLConnection yc =null;
                  yc = oracle.openConnection();
                    in = new BufferedReader(
                           new InputStreamReader(
                           yc.getInputStream()));
       }
       catch(Exception e){
           System.err.println(e);
       }
       Map map = new HashMap();
       map.put("input", in);
  
      return new ModelAndView("xl", map);
  }
  </code></pre>
  
  <p>}</p>
  
  <p>View Code:</p>
  
  <pre><code>public class ExcelReportView extends AbstractExcelView{
  
  @Override
  protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
          HSSFSheet sheet;
          HSSFRow row;
          HSSFCell cell;
       try {
              BufferedReader in = (BufferedReader) model.get("input");            
              sheet=workbook.createSheet("spring");
  
                       String inputLine;
                       int rowNum =0;
                          while ((inputLine = in.readLine()) != null) {
                               row = sheet.createRow(rowNum++);
                              String[] coloumns = inputLine.split("\t");
                              int cellNum =0;
                              for(String coloumn: coloumns){
                                      cell = row.createCell(cellNum++);
                                     cell.setCellValue(coloumn);
                              }
                              System.out.println(inputLine);
                  } 
                          in.close();  
                          System.out.println("Excel written successfully..");
  
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
  </code></pre>
  
  <p>}
  }</p>
  
  <p>view.properties</p>
  
  <pre><code> xl.class=package.ExcelReportView   
  </code></pre>
  
  <p>WebAppConfig.java</p>
  
  <pre><code>@Configuration
  @EnableWebMvc
  @ComponentScan(basePackages = "package")
  public class WebAppContextConfig extends WebMvcConfigurerAdapter {
  // Resolve logical view names to .jsp resources in /WEB-INF/views directory
  
  @Bean
  public InternalResourceViewResolver configureInternalResourceViewResolver() {
      InternalResourceViewResolver resolver = new InternalResourceViewResolver();
      resolver.setPrefix("/WEB-INF/jsp/");
      resolver.setSuffix(".jsp");
      return resolver;
  }
  
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/scripts/**").addResourceLocations(
              "/scripts/");
      registry.addResourceHandler("/css/**").addResourceLocations("/css/");
      registry.addResourceHandler("/img/**").addResourceLocations("/img/");
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Front end Code:</p>
  
  <pre><code> function AjaxCallForExcel(){
     $.ajax({
          type: 'POST',
          url: location.href + '/Excel',
          data: ({name:name })
          }); 
     }
  </code></pre>
  
  <p>Below is what i see in logs:</p>
  
  <pre><code> DispatcherServlet with name 'appServlet' processing POST request for [/App/Excel]
   Looking up handler method for path /App/Excel
   Returning handler method [protected org.springframework.web.servlet.ModelAndView package.ExcelController.handleRequestInternal(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.lang.Exception]
   Returning cached instance of singleton bean 'excelController'
   Invoking afterPropertiesSet() on bean with name 'xl'
   Rendering view [org.springframework.web.servlet.view.JstlView: name 'xl'; URL [**/WEB-INF/jsp/xl.jsp**]] in DispatcherServlet with name 'appServlet'
   Added model object 'org.springframework.validation.BindingResult.input' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'xl'
   Added model object 'input' of type [java.io.BufferedReader] to request in view with name 'xl'
   Forwarding to resource [/WEB-INF/jsp/xl.jsp] in InternalResourceView 'xl'
   Successfully completed request
  </code></pre>
  
  <p>I dont know how to avoid it from forwarding it to xl.jsp. I am sure view resolver is making it into jsp view. Can someone point how can i fix it.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I saw this xml equivalent config online. Not sure how to make it java config:</p>
  
  <pre><code>&lt;bean id="excelViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver"&gt;
    &lt;property name="order" value="1"/&gt;
    &lt;property name="location" value="/WEB-INF/views.xml"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>i tried converting it the below way:</p>
  
  <pre><code>@Bean
  public XmlViewResolver configureXmlViewResolver(){
      XmlViewResolver resolver = new XmlViewResolver();
      resolver.setOrder(1);
      resolver.setLocation(**WHAT SHOULD BE HERE**);
  }
  </code></pre>
  
  <p>I dont know what to put in location. I cant give string. i dont have views.xml as i am use java configs</p>
  
  <p><strong>Edit</strong>(Here is my code after making changes as you said)</p>
  
  <pre><code>public class ExcelReportView extends AbstractExcelView{
  BufferedReader in;
  ExcelReportView(BufferedReader in){
  this.in = in;
   }
  
  @Override
  protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
          HSSFSheet sheet;
          HSSFRow row;
          HSSFCell cell;
          response.setHeader("Content-Type", "application/octet-stream");
          response.setHeader("Content-Disposition", "attachment; filename=MyExcelSpreadsheet.xls");
  
       try {
              //BufferedReader in = (BufferedReader) model.get("input");          
              sheet=workbook.createSheet("spring");
  
                       String inputLine;
                       int rowNum =0;
                          while ((inputLine = in.readLine()) != null) {
                               row = sheet.createRow(rowNum++);
                              String[] coloumns = inputLine.split("\t");
                              int cellNum =0;
                              for(String coloumn: coloumns){
                                      cell = row.createCell(cellNum++);
                                     cell.setCellValue(coloumn);
                              }
                              System.out.println(inputLine);
                  } 
                          in.close();  
                          System.out.println("Excel written successfully..");
  
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
       OutputStream outStream = null;
  
          try {
              outStream = response.getOutputStream();
              workbook.write(outStream);
              outStream.flush();
          } finally {
              outStream.close();
          }    
      }
      }
  </code></pre>
  
  <p>Controller Code:</p>
  
  <pre><code>    @Controller
      public class ExcelController    {
  
  @RequestMapping(value = "/Excel", method = RequestMethod.POST)
  protected ModelAndView generateCSV(HttpServletRequest request,
          HttpServletResponse response) throws Exception {
      BufferedReader in = null;
       try {
              URL oracle = new URL("http://service.com");
              URLConnection yc =null;
                  yc = oracle.openConnection();
                    in = new BufferedReader(
                           new InputStreamReader(
                           yc.getInputStream()));
       }
       catch(Exception e){
           System.err.println(e);
       }
       ModelAndView mav = new ModelAndView();
       mav.setView(new ExcelReportView( in));
      return mav;
  }
      }
  </code></pre>
  
  <p>Log output:</p>
  
  <pre><code>    DispatcherServlet with name 'appServlet' processing POST request for [/App/Excel]
      Looking up handler method for path /App/Excel
      Returning handler method [protected org.springframework.web.servlet.ModelAndView com.package.ExcelController.generateCSV(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.lang.Exception]
      Returning cached instance of singleton bean 'excelController'
      Rendering view [com.package.controllers.ExcelReportView: unnamed] in DispatcherServlet with name 'appServlet'
      Created Excel Workbook from scratch
      Title Id required
      Excel written successfully..
      Successfully completed request
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Response Header:</p>
  
  <pre><code>HTTP/1.1 200 OK
  Server: Apache-Coyote/1.1
  Pragma: private
  Cache-Control: private, must-revalidate
  Content-Disposition: attachment; filename=MyExcelSpreadsheet.xls
  Content-Type: application/octet-stream;charset=ISO-8859-1
  Content-Language: en-US
  Transfer-Encoding: chunked
  Date: Tue, 12 Mar 2013 16:36:52 GMT
  </code></pre>