将xml在线转换成html5,将ireport制作的.jrxml文件转成.html并输出到前端

springmvc中pom依赖:

net.sf.jasperreports

jasperreports

6.8.0

com.itextpdf

itextpdf

5.5.0

com.itextpdf

itext-pdfa

5.5.0

com.itextpdf

itext-asian

5.2.0

com.lowagie

itext

2.1.7

org.codehaus.groovy

groovy-all

2.5.6

pom

数据源的配置类

package top.mau5.configuration;

import com.alibaba.druid.pool.DruidDataSource;

import com.alibaba.druid.support.http.StatViewServlet;

import com.alibaba.druid.support.http.WebStatFilter;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.boot.web.servlet.FilterRegistrationBean;

import org.springframework.boot.web.servlet.ServletRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import java.util.HashMap;

import java.util.Map;

@Configuration

@EnableAutoConfiguration

public class DruidDBConfig {

private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);

@Value("${spring.datasource.url}")

private String dbUrl;

@Value("${spring.datasource.username}")

private String username;

@Value("${spring.datasource.password}")

private String password;

@Value("${spring.datasource.driverClassName}")

private String driverClassName;

// @Value("${spring.datasource.initialSize}")

// private int initialSize;

//

// @Value("${spring.datasource.minIdle}")

// private int minIdle;

//

// @Value("${spring.datasource.maxActive}")

// private int maxActive;

//

// @Value("${spring.datasource.maxWait}")

// private int maxWait;

//

// @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")

// private int timeBetweenEvictionRunsMillis;

//

// @Value("${spring.datasource.minEvictableIdleTimeMillis}")

// private int minEvictableIdleTimeMillis;

//

// @Value("${spring.datasource.validationQuery}")

// private String validationQuery;

//

// @Value("${spring.datasource.testWhileIdle}")

// private boolean testWhileIdle;

//

// @Value("${spring.datasource.testOnBorrow}")

// private boolean testOnBorrow;

//

// @Value("${spring.datasource.testOnReturn}")

// private boolean testOnReturn;

//

// @Value("${spring.datasource.poolPreparedStatements}")

// private boolean poolPreparedStatements;

//

// @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")

// private int maxPoolPreparedStatementPerConnectionSize;

//

// @Value("${spring.datasource.filters}")

// private String filters;

//

// @Value("{spring.datasource.connectionProperties}")

// private String connectionProperties;

@Bean //声明其为Bean实例

@Primary //在同样的DataSource中,首先使用被标注的DataSource

public DruidDataSource dataSource(){

DruidDataSource datasource = new DruidDataSource();

datasource.setUrl(this.dbUrl);

datasource.setUsername(username);

datasource.setPassword(password);

datasource.setDriverClassName(driverClassName);

// //configuration

// datasource.setInitialSize(initialSize);

// datasource.setMinIdle(minIdle);

// datasource.setMaxActive(maxActive);

// datasource.setMaxWait(maxWait);

// datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

// datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

// datasource.setValidationQuery(validationQuery);

// datasource.setTestWhileIdle(testWhileIdle);

// datasource.setTestOnBorrow(testOnBorrow);

// datasource.setTestOnReturn(testOnReturn);

// datasource.setPoolPreparedStatements(poolPreparedStatements);

// datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

// try {

// datasource.setFilters(filters);

// } catch (SQLException e) {

// logger.error("druid configuration initialization filter", e);

// }

// datasource.setConnectionProperties(connectionProperties);

return datasource;

}

@Bean

public ServletRegistrationBean druidServletRegistrationBean() {

ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();

servletRegistrationBean.setServlet(new StatViewServlet());

servletRegistrationBean.addUrlMappings("/druid/*");

return servletRegistrationBean;

}

/**

* 注册DruidFilter拦截

*

* @return

*/

@Bean

public FilterRegistrationBean duridFilterRegistrationBean() {

FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();

filterRegistrationBean.setFilter(new WebStatFilter());

Map initParams = new HashMap();

//设置忽略请求

initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");

filterRegistrationBean.setInitParameters(initParams);

filterRegistrationBean.addUrlPatterns("/*");

return filterRegistrationBean;

}

}

controller:

@RequestMapping(value = "report")

@RestController

public class ReportController {

@Autowired

DruidDataSource druidDataSource;

@Autowired

ReportService reportService;

public static final String ROOT_PATH = "C:\\Users\\korin\\Desktop\\jaspertest\\";//本机文件保存地址

// public static final String ROOT_PATH = "C:\\jaspertest\\";//云服务器文件保存地址

@RequestMapping("uploadJrxml")

public Map fileUpload(MultipartFile file) throws IllegalStateException, IOException{

System.out.println(file.getOriginalFilename());

Filepath filepath = new Filepath();

filepath.setName(file.getOriginalFilename());

filepath.setPath(ROOT_PATH+filepath.getName());

file.transferTo(new File(filepath.getPath()));

reportService.insesrt(filepath);

Map map = new HashMap<>();

map.put("msg", "ok");

map.put("uuid", filepath.getRid());

return map;

}

@RequestMapping("showfilelist")

public List showfilelist() throws IllegalStateException, IOException{

return reportService.select(new Filepath());

}

/**

* 通过jrxml文件生成html,参数固定测试版

*

* 在这之前应该有个上传jrxml文件功能,上传到指定文件夹,存数据库(uuid,存储路径等)后返回uuid

*

* @param jrxml_path jrxml存放路径

* @param id 主键id

* @return

* @throws JRException

* @throws IOException

* @throws UnsupportedEncodingException

*/

@RequestMapping(value = "jrxml2html",produces = "text/html;charset=UTF-8")/* 返回格式为text/html */

public String jrxml2html(HttpServletRequest request,String jrxmlName,String id) throws JRException, UnsupportedEncodingException, IOException {

JasperReport jasper = JasperCompileManager.compileReport(new FileInputStream(new File("C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".jrxml")));

Map map = new HashMap<>();

map.put("P_YHTZID", id);

Connection conn = null;

String str = "";

try {

/* 生成html文件 */

conn = druidDataSource.getConnection();

JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);

JasperExportManager.exportReportToHtmlFile(jasperPrint,"C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");

/* 读取html文件 */

URL url = new URL("file:\\C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");

BufferedReader br = null;

br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

String res;

StringBuilder sb = new StringBuilder("");

while ((res = br.readLine()) != null) {

sb.append(res.trim());

}

str = sb.toString();

} catch (SQLException e) {

e.printStackTrace();

}finally {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

return str;

}

//参数可变

@RequestMapping(value = "jrxml2html_",produces = "text/html;charset=UTF-8")/* 返回格式为text/html */

public String jrxml2html_(HttpServletRequest request) throws JRException, UnsupportedEncodingException, IOException {

Map map = getParameterMap(request);

String jrxmlName = map.get("jrxmlName").toString();

//,String jrxmlName,String paramId

JasperReport jasper = JasperCompileManager.compileReport(new FileInputStream(new File("C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".jrxml")));

// map.put("P_YHTZID", id);

Connection conn = null;

String str = "";

try {

/* 生成html文件 */

conn = druidDataSource.getConnection();

JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);

JasperExportManager.exportReportToHtmlFile(jasperPrint,"C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");

/* 读取html文件 */

URL url = new URL("file:\\C:\\Users\\korin\\Desktop\\jaspertest\\"+jrxmlName+".html");

BufferedReader br = null;

br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

String res;

StringBuilder sb = new StringBuilder("");

while ((res = br.readLine()) != null) {

sb.append(res.trim());

}

str = sb.toString();

} catch (SQLException e) {

e.printStackTrace();

}finally {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

return str;

}

//优化后

/**

* @param request 参数中要带rid(在数据库filepath表中的rid)和相应的报表中所需的参数名和值(如P_YHTZID=...)

* @return

* @throws JRException

* @throws UnsupportedEncodingException

* @throws IOException

*/

@RequestMapping(value = "jrxml2html__",produces = "text/html;charset=UTF-8")/* 返回格式为text/html */

public String jrxml2html__(HttpServletRequest request) throws JRException, UnsupportedEncodingException, IOException {

Filepath filepath = new Filepath();

Map map = getParameterMap(request);

filepath.setRid(map.get("rid").toString());

String filePath = reportService.select(filepath).get(0).getPath();

InputStream is = new FileInputStream(new File(filePath));

JasperReport jasper = JasperCompileManager.compileReport(is);

Connection conn = null;

String str = "";

filePath = filePath.replaceAll(".jrxml", ".html");//html文件路径

try {

/* 生成html文件 */

File file = new File(filePath);

if(file.exists()) {

file.delete();//删除以前的html文件

}

conn = druidDataSource.getConnection();

JasperPrint jasperPrint = JasperFillManager.fillReport(jasper,map,conn);

JasperExportManager.exportReportToHtmlFile(jasperPrint,filePath);

/* 读取html文件 */

URL url = new URL("file:\\"+filePath);

BufferedReader br = null;

br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

String res;

StringBuilder sb = new StringBuilder("");

while ((res = br.readLine()) != null) {

sb.append(res.trim());

}

str = sb.toString();

} catch (SQLException e) {

e.printStackTrace();

}finally {

try {

is.close();//关流

conn.close();//关闭数据库连接

} catch (SQLException e) {

e.printStackTrace();

}

}

return str;

}

protected Map getParameterMap(HttpServletRequest request) {

return getParameterMap(request, false);

}

protected Map getParameterMap(HttpServletRequest request, boolean needNull) {

Map map = new HashMap();

Map parameterMap = request.getParameterMap();

for (String paramName : parameterMap.keySet()) {

String[] paramValues = parameterMap.get(paramName);

if (null != paramValues && paramValues.length > 1) {

map.put(paramName, paramValues);

} else if (null != paramValues) {

String paramValue = parameterMap.get(paramName)[0];

if (StringUtils.isNotEmpty(paramValue) || needNull) {

map.put(paramName, paramValue);

}

}

}

return map;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值