除了常见的jsp视图外,还有pdf,excel等。不管哪种视图,都会实现SpringMvc定义的视图接口View。这篇文章就讲讲怎么使用Pdf视图----AbstractPdfView。
AbstractPdfView属于非逻辑视图,不需要任何的视图解析器(ViewResolver)去定位。它是一个抽象类,有一个抽象方法需要我们去实现。
protected abstract void buildPdfdocument(Mapmodel, document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception;
我们首先创建一个Spring Boot工程,这里的orm使用Mybatis,数据源使用Druid,为了能够使用pdf,我们需要加pom.xml中相关的依赖,下面贴出完整的pom文件
org.springframework.boot spring-boot-starter-aoporg.springframework.boot spring-boot-starter-weborg.mybatis.spring.boot mybatis-spring-boot-starter1.3.2 mysql mysql-connector-javaruntime org.springframework.boot spring-boot-starter-tomcatprovided org.springframework.boot spring-boot-starter-testtest org.xhtmlrenderer core-rendererR8 com.itextpdf itextpdf5.5.12 com.alibaba druid1.1.6
继承了AbstractPdfView后,就得实现它的抽象方法,从而完成导出的逻辑,而每个控制器可能都有不同的导出逻辑,所以为了适应不同控制器的自定义导出,先定义一个导出接口。
import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.lowagie.text.document;import com.lowagie.text.pdf.PdfWriter;public interface PdfExportService {
public void make(Map model, document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response);
} 注意这里导的是com.lowagie.text包下的类。
有了这个接口后,各个控制器只需要实现这个接口,就能自定义导出pdf的逻辑。
接着就是继承AbstractPdfView,通过它调度PdfExportService 的make方法就可以让控制器去实现自定义的导出逻辑。
public class PdfView extends AbstractPdfView {
private PdfExportService pdfExportService = null;
public PdfView(PdfExportService pdfExportService) { this.pdfExportService = pdfExportService;
}
@Override
protected void buildPdfdocument(Map model, document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// 调用导出服务接口类
pdfExportService.make(model, document, writer, request, response);
}
} 这里可以看到,在创建自定义pdf视图时,需要自定义一个导出服务接口(PdfExportService ),通过实现这个接口,每个控制器都可以自定义其导出的逻辑。
完成了上面的工作,接下来就是正常的SSM结合。首先在Spring Boot的配置文件中进行配置
# 数据库配置jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8jdbc.username = root
jdbc.password = 1311664842# mybatis 配置文件的路径mybatis_config_file = /mybatis/mybatis-config.xml# 映射文件的路径mapper_path = /mapper@Configuration// 扫描dao层@MapperScan(value = "com.codeliu.dao")public class DataSourceConfig {
@Value(value = "${jdbc.driver}") private String jdbcDriver;
@Value(value = "${jdbc.url}") private String jdbcUrl;
@Value(value = "${jdbc.username}") private String jdbcUsername;
@Value(value = "${jdbc.password}") private String jdbcPassword;
@Bean(value = "dataSource") public DruidDataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(jdbcDriver);
dataSource.setUrl(jdbcUrl);
dataSource.setUsername(jdbcUsername);
dataSource.setPassword(jdbcPassword); return dataSource;
}
}@Configurationpublic class SqlSessionFactoryConfig { // mybatis配置文件的路径
@Value(value = "${mybatis_config_file}") private String mybatisConfigPath;
// mybatis映射文件的路径
@Value(value = "${mapper_path}") private String mapperPath;
// 实体包的路径
@Value(value = "${entity_package}") private String entityPath;
@Autowired
private DataSource dataSource;
@Bean(value = "sqlSessionFactory") public SqlSessionFactoryBean getSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
// mybatis配置文件的路径
sqlSessionFactory.setConfigLocation(new ClassPathResource(mybatisConfigPath));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath; // 指定映射文件的路径
sqlSessionFactory.setMapperLocations(resolver.getResources(packageSearchPath)); // 配置数据源
sqlSessionFactory.setDataSource(dataSource); // 配置实体包的扫描路径
sqlSessionFactory.setTypeAliasesPackage(entityPath); return sqlSessionFactory;
}
}注意加上了@Configuration注解,表示这是一个配置类。这样Spring Boot启动的时候,就会进行相关的初始化。
现在可以来进行controller的编写。
@Controller@RequestMapping("/man")public class ManController {
@Autowired
private ManService manService;
@GetMapping("/export/pdf") public ModelAndView exportPdf() {
List manList = manService.getManList(); // 定义pdf视图
View view = new PdfView(exportService());
ModelAndView mv = new ModelAndView(); // 设置视图
mv.setView(view); // 加入数据模型
mv.addObject("manList", manList); return mv;
}
@SuppressWarnings("unchecked") public PdfExportService exportService() { // 使用Lambda表达式
return(model, document, writer, request, response)-> { try { // A4纸张
document.setPageSize(PageSize.A4); // 标题
document.addTitle("用户信息"); // 换行
document.add(new Chunk("n")); // 表格,3列
PdfPTable table = new PdfPTable(3); // 单元格
PdfPCell cell = null; // 字体,定义为蓝色加粗
Font f8 = new Font();
f8.setColor(Color.BLUE);
f8.setStyle(Font.BOLD); // 标题
cell = new PdfPCell(new Paragraph("id", f8)); // 居中对齐
cell.setHorizontalAlignment(1); // 将单元格加入表格
table.addCell(cell);
// 标题
cell = new PdfPCell(new Paragraph("age", f8)); // 居中对齐
cell.setHorizontalAlignment(1); // 将单元格加入表格
table.addCell(cell);
// 标题
cell = new PdfPCell(new Paragraph("name", f8)); // 居中对齐
cell.setHorizontalAlignment(1); // 将单元格加入表格
table.addCell(cell);
// 获取数据模型中的manList
List manList = (List)model.get("manList"); for(Man man:manList) {
document.add(new Chunk("n"));
cell = new PdfPCell(new Paragraph(man.getId() + "")); // 居中对齐
cell.setHorizontalAlignment(1);
table.addCell(cell);
cell = new PdfPCell(new Paragraph(man.getAge() + "")); // 居中对齐
cell.setHorizontalAlignment(1);
table.addCell(cell);
cell = new PdfPCell(new Paragraph(man.getName())); // 居中对齐
cell.setHorizontalAlignment(1);
table.addCell(cell);
} // 文档中加入表格
document.add(table);
} catch(documentException e) {
e.printStackTrace();
}
};
}
} 可以看到我们先通过数据库查询出数据,然后放入模型和视图(ModelAndView)中,然后设置pdf视图(PdfView)。而定义PdfView时,使用Lambda表达式实现了导出服务接口,这样就可以很方便的让每一个控制器自定义样式和数据。导出pdf文件的逻辑在exportService方法中。
启动Spring Boot文件后,输入url,显示下面的结果
作者:Java攻城玩家
链接:https://www.jianshu.com/p/eab1eaef031c



