ireport实践之request获取参数名和参数值的两种方式

本文介绍了在Java中如何从HttpServletRequest对象中获取不确定参数名和参数值的方法。通过枚举和Map两种方式,详细展示了如何处理ireport报表业务中不确定数量和名称的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java HttpServletRequest可以通过确定的参数名获取参数值,但有的时候,后台并不知道前台传过来的参数名是什么,例如ireport报表业务,平台和业务分开开发,业务需要调用平台的功能,并向平台传不定数量及不定名字的参数,这种情况下平台可以通过枚举和map两种方式获取参数,代码如下:


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Map map = new HashMap();
String fileName = null;

/*方式1:通过枚举获取参数

                 *  Enumeration em = request.getParameterNames(); 
 while (em.hasMoreElements()) {  
 String paramName = (String) em.nextElement();    
 String paramValue = request.getParameter(paramName);  
  //形成键值对应的map  
 map.put(paramName, paramValue);  
 } 
*/

//方式2:通过map获取参数
Map<String, String[]> pathParas = request.getParameterMap();
   for (Map.Entry entry : pathParas.entrySet()) {
     if ((entry.getValue() != null) && (((String[])entry.getValue()).length > 0)) {
     map.put((String)entry.getKey(), ((String[])entry.getValue())[0]);
     }
   }

   fileName = (String) map.get("fileName");//报表文件名
map.remove("fileName");
 
//方式3:通过参数名来获取参数值:
//String fileName = request.getParameter("fileName");//报表文件参数
//File file = new File(getServletConfig().getServletContext().getRealPath("/jasper/touLiaoZ.jasper"));//获取touLiaoZ.jasper绝对路径
//String filePathString = file.getPath();
//String prdPlanId=request.getParameter("prdPlanId");//查询参数1
//String matId=request.getParameter("matId");//查询参数2
//Map<String, Object> map = new HashMap<>();
//map.put("prdPlanId", prdPlanId);
//map.put("matId", matId);
Connection con = Utils.getConection();
try {
//byte[] bytes = JasperRunManager.runReportToPdf(file.getPath(), map, con);
byte[] bytes = JasperRunManager.runReportToPdf("D:\\report\\"+fileName+".jasper", map, con);//文件路径多加一个\转义
response.setContentType("application/pdf");//charset=Identity-HPath

response.setContentLength(bytes.length);
ServletOutputStream sos = response.getOutputStream();
sos.write(bytes , 0 , bytes.length);
sos.flush();
sos.close();

} catch (JRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
Utils.closeCon(con);
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值