我希望有一个控制器方法从JasperReports jrxml文件返回PDF,而不使用任何xml配置。
我想使用JasperReportsPdfView
。这有可能吗?我知道只能在这个博客中使用Java代码来完成它:
http://krams915.blogspot.com/2010/12/spring-3-mvc-jasper-integration_22.html
但我相信一定可以用更少的代码: - )
不幸的是,这里有一些不的示例代码。
@RequestMapping(value = "/test/pdfreport", method = RequestMethod.GET, produces = "application/pdf")
public JasperReportsPdfView getPdf() {
// does not work like this, unfortunately
final Person p = userService.getUserById("the id");
final JasperReportsPdfView view = new JasperReportsPdfView();
view.setReportDataKey("person");
view.addStaticAttribute("person", p); // ??
view.setUrl("report.jrxml");
return view;
}
感谢任何指针。
修改:这是我的工作解决方案:
@Autowired
private ApplicationContext appContext;
@RequestMapping(value = "/test/pdfreport", method = RequestMethod.GET, produces = "application/pdf")
public ModelAndView getPdf() {
final List<Map<String, Object>> users = userService.getUsers();
final JasperReportsPdfView view = new JasperReportsPdfView();
view.setReportDataKey("users");
view.setUrl("classpath:report.jrxml");
view.setApplicationContext(appContext);
final Map<String, Object> params = new HashMap<>();
params.put("users", users);
return new ModelAndView(view, params);
}
将spring-context-support
包添加到项目中非常重要。
答案 0 :(得分:7)
这对我有用:
@Autowired private ApplicationContext appContext;
@Autowired private DataSource dataSource;
@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public ModelAndView getPdf() {
JasperReportsPdfView view = new JasperReportsPdfView();
view.setJdbcDataSource(dataSource);
view.setUrl("classpath:report.jrxml");
Map<String, Object> params = new HashMap<>();
params.put("param1", "param1 value");
view.setApplicationContext(appContext);
return new ModelAndView(view, params);
}