spring - What is BeanNameViewResolver? -
i read documentation here, think spring documentation complex , hard understand, need little explanation beannameviewresolver.
can code example?
as explained in documentation,beannameviewresolver resolves views declared beans. of time need special-purpose views.
for example, need render excel spreadsheet. excel generation apache poi
<dependency> <groupid>org.apache.poi</groupid> <artifactid>poi</artifactid> <version>3.6</version> </dependency>
so, subclass abstractexcelview and implement custom logic render spreadsheet based on model values.
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 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; (map.entry<string, string> entry : revenuedata.entryset()) { //create row data hssfrow row = sheet.createrow(rownum++); row.createcell(0).setcellvalue(entry.getkey()); row.createcell(1).setcellvalue(entry.getvalue()); } }
}
and controller adds data
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"; } }
then declaring an beannameviewresolver makes available controllers: when controller returns string view name myexcelview, spreadsheet rendered.
<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>
Comments
Post a Comment