什么是BeanNameViewResolver?

时间:2015-07-11 07:13:13

标签: spring spring-mvc

我阅读了文档here,但我认为Spring文档有时很复杂且难以理解,因此我需要对BeanNameViewResolver进行一些解释。

我可以获得代码示例吗?

1 个答案:

答案 0 :(得分:5)

如文档中所述,BeanNameViewResolver解析声明为bean的视图。大部分时间你都需要它用于一些特殊用途的视图。

例如,我们需要渲染Excel电子表格。 对于Excel生成,您将使用Apache POI

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.6</version>
   </dependency>

因此,您将AbstractExcelView子类化并实现自定义逻辑,以根据模型值呈现电子表格。

public class CustomExcelView extends AbstractExcelView { 

@Override
    protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");
        //create a wordsheet
        HSSFSheet sheet = workbook.createSheet("Revenue Report");


    HSSFRow header = sheet.createRow(0);
    header.createCell(0).setCellValue("Month");
    header.createCell(1).setCellValue("Revenue");

    int rowNum = 1;
    for (Map.Entry<String, String> entry : revenueData.entrySet()) {
        //create the row data
        HSSFRow row = sheet.createRow(rowNum++);
        row.createCell(0).setCellValue(entry.getKey());
        row.createCell(1).setCellValue(entry.getValue());
            }
}

}

并且控制器只是添加数据

package com.example;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;    
@Controller
@RequestMapping("/excelview")
public class ExcelController {

    public String getExcel(Model model){
        Map<String,String> revenueData = new HashMap<String,String>();
        revenueData.put("Jan-2010", "$100,000,000");
        revenueData.put("Feb-2010", "$110,000,000");
        revenueData.put("Mar-2010", "$130,000,000");
        revenueData.put("Apr-2010", "$140,000,000");
        revenueData.put("May-2010", "$200,000,000");
        model.addAttribute("revenueData",revenueData);

        return "myExcelView";
    }

}

然后声明BeanNameViewResolver使其可供控制器使用:当控制器返回视图名称为myExcelView的String时,将呈现您的电子表格。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.example" />

    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />

    <bean id="myExcelView" class="com.example.CustomExcelView" />

</beans>