我需要Java代码来从CSV格式下载数据库中的特定行。我正在使用Netbeans IDE和Structs。
我在动作类中使用了以下代码:
else if (mode.equalsIgnoreCase("download"))
{
if(null !=request.getParameter("batchid")){
batch_id=request.getParameter("batchid");
}
UploadVO uploadvo= new UploadVO();
filetype = uploadform.getFiletype();
filename = uploadform.getFilename();
try{
String sqls = "select ROW_NUMBER() over(order by id) as row,trx_batch_id,account_id,"
+ "(select name from [user] where id=tt.user_id) as Uploadedby,(SELECT CONVERT(VARCHAR(10),GETDATE(),101) ) as date_of_transaction,"
+ "amount,(select description from [_transaction_type] where type=tt.type) as type,note,reverse_transaction_id from"
+ " [transaction] tt "+ "where trx_batch_id= '" +batch_id+ "'" ;
Statement stmts = con.createStatement();
ResultSet rss = stmts.executeQuery(sqls);
while (rss.next()) {
byte[] ba;
Blob b = rss.getBlob("content");
ba = b.getBytes(1, (int) b.length());
uploadvo.setDocfile(ba);
}
}
catch(Exception e){
}
if (filetype.trim().equalsIgnoreCase("text/plain")) {
response.setContentType("text/plain");
} else if (filetype.trim().equalsIgnoreCase("application/ms-doc")) {
response.setContentType("application/ms-doc");
} else if (filetype.trim().equalsIgnoreCase("application/ms-excel")) {
response.setContentType("application/ms-excel");
} else if (filetype.trim().equalsIgnoreCase("pdf")) {
response.setContentType("application/pdf");
} else if (filetype.trim().equalsIgnoreCase("ppt")) {
response.setContentType("application/ppt");
} else if (filetype.trim().equalsIgnoreCase("application/vnd.ms-excel")) {
response.setContentType("application/vnd.ms-excel");
} else if (filetype.trim().equalsIgnoreCase("image/jpeg")) {
response.setContentType("image/jpeg");
} else {
response.setContentType("application/octet-stream");
}
String disHeader = "Attachment; Filename= " + filename + "";
System.out.println(disHeader);
response.setHeader("Content-Disposition", disHeader);
response.setHeader("cache-control", "no-cache");
ServletOutputStream outs = response.getOutputStream();
outs.write(uploadvo.getDocfile());
outs.flush();
outs.close();
return mapping.findForward("success");
}
但我得到一个空指针异常。
答案 0 :(得分:0)
您正在调用fileType.trim()
而不检查它是否为空。
你不要求的东西,但应该被提及。
Apache Commons有一个StringUtils类,非常适合检查字符串是否为空, 所以不要写
if (null !=request.getParameter("batchid"))
你会写
if (StringUtils.isNotEmpty(request.getParameter("batchid"))
因为你可能有兴趣知道它是否包含空格。
另外,你的
else if (mode.equalsIgnoreCase("download"))
表示您正在启用mode
(我不确定您是否已检查null
)。在struts 1.x中,您可以使用DispatchAction
来指定参数,例如mode,它将是被调用方法的名称,因此在您的示例中,您将实现一个方法
public ActionForward download(...) {
...
}
将在"download".equals(request.getParameter("mode")
时调用。
另请注意,编写"download".equals(request.getParameter("mode")
而不是request.getParameter("mode").equals("download")
可以使您免于潜在的空指针