您的位置:首页 > 产品设计 > UI/UE

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

2017-02-10 16:56 429 查看
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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: