视图渲染
视图渲染
接上一节,获取到了ModelAndView对象,ModelAndView包含有view对象和Model对象,而视图渲染最为关键的就是这部分。
@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (logger.isTraceEnabled()) {
logger.trace("Rendering view with name '" + this.beanName + "' with model " + model +
" and static attributes " + this.staticAttributes);
}
Map<String, Object> mergedModel = createMergedOutputModel(model, request, response);
prepareResponse(request, response);
renderMergedOutputModel(mergedModel, getRequestToExpose(request), response);
}
protected abstract void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception;
在进行视图渲染时,会获取到上一节构造的view和model对象作为参数传递给renderMergedOutputModel,不同view的子类,做具体的渲染操作。如InternalResourceView就是进行redirect或者forword操作,这属于servlet的范畴。不做详细解释。
下载Excel视图的例子
在这使用继承AbstractXlsxView来实现,并实现抽象方法buildExcelDocument。
public class RecordSetExportView extends AbstractXlsxView {
private String title = UUID.randomUUID().toString();
public RecordSetExportView(){
}
public RecordSetExportView(String title){
this.title = title;
}
@Override
protected void buildExcelDocument(Map<String, Object> model,Workbook workbook,HttpServletRequest request,HttpServletResponse response) throws Exception {
RecordSet rs = (RecordSet) model.get("rs");
Font font1 = workbook.createFont();
font1.setFontName("黑体");
font1.setFontHeightInPoints((short) 16);//设置字体大小
font1.setBold(true);
Font font2 = workbook.createFont();
font2.setFontName("仿宋_GB2312");
font2.setFontHeightInPoints((short) 12);
CellStyle cellStyleTitle = workbook.createCellStyle();
cellStyleTitle.setFont(font1);
cellStyleTitle.setFillBackgroundColor((short) 13);
CellStyle cellStyleLabel = workbook.createCellStyle();
cellStyleLabel.setFont(font2);
if(rs!= null && !rs.getData().isEmpty()){
fileterColumnIfNeed(rs);
Sheet sheet = null ;
int rownum = 0;
if(!rs.getColumns().isEmpty()){
sheet = workbook.createSheet();
Row row = sheet.createRow(rownum++);
for(int i = 0;i < rs.getColumns().size();i++){
Cell cell = row.createCell(i);
cell.setCellType(CellType.STRING);
cell.setCellValue(rs.getColumns().get(i).get("desc"));
cell.setCellStyle(cellStyleTitle);
sheet.autoSizeColumn(i);
}
if(!rs.getData().isEmpty()){
for(Map<String,String> data:rs.getData()) {
Row row2 = sheet.createRow(rownum++);
for (int i = 0; i < rs.getColumns().size(); i++) {
String value = data.get(rs.getColumns().get(i).get("name"));
Cell cell = row2.createCell(i);
cell.setCellType(CellType.STRING);
cell.setCellValue(value);
cell.setCellStyle(cellStyleLabel);
}
}
}
}
}
}
private void fileterColumnIfNeed(RecordSet rs){
Iterator<Map<String,String>> iterator = rs.getColumns().iterator();
while(iterator.hasNext()){
Map<String,String> map = iterator.next();
if("1".equals(map.get("hidden"))){
iterator.remove();
}
}
}
}
没有智能的代码,源码面前了无秘密