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);
}
}