如何下载 excel 并在单击 JSP 上的链接时从 Spring 控制器返回一些错误消息



jsp 页面上有一个文本区域,一个按钮和一个div(显示错误消息(.

单击按钮时,根据文本区域中的文本,如果文本区域中的输入文本不正确,则在div中显示错误消息.如果一切正常,则下载excel.

当我在文本区域中输入不正确的文本时, 显示错误消息.
当我在文本区域中输入正确的文本时,我无法下载 excel,它直接显示 PK R P[Content_Types].xml S n 06 PU C { X % ]8 R q cfgfW d q ZCB| |*h
...
...
on 网页

索引.jsp
...
<textarea class="boxsizingBorder" id="activities"></textarea>
<button onclick="showresult()">download</button>
<div class="instruction"  id="process_result"></div>
...
<script type="text/javascript">
function showresult() {
document.getElementById("process_result").innerHTML = "process...";
document.getElementById("process_result").style.color = 'gray';
var activities = document.getElementById('activities').value;
var querycontent = JSON.stringify({
"activities" : activities
});

$
.ajax({
type : 'POST',
url : 'showresult', 
contentType : 'application/json;charset=utf-8',
data : querycontent,
dataType : 'html',
success : function(msg) {
document.getElementById("process_result").innerHTML = msg;
document.getElementById("process_result").style.color = 'red';
},
error : function() {
document.getElementById("process_result").innerHTML = "download failed!";
document.getElementById("process_result").style.color = 'red';
}
})
}
</script>

监视器控制器.java

@Controller
public class MonitorController {
@RequestMapping(value = "/showresult", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public @ResponseBody String showResult(@RequestBody QueryData querycontent, HttpServletRequest request,
HttpServletResponse response) throws FileNotFoundException, IOException, Exception {
DBConnection dbcon = new DBConnection();
String message = "";
String activities = querycontent.getactivities();
System.out.println("origin activities:n" + activities);
String pattern = "^[0-9\n]+$";
boolean isMatch = Pattern.matches(pattern, activities);
if (isMatch == false) {
message = "please input correct character!";
} else {
activities = activities.replaceAll("^[\n]+", "");
System.out.println("activities delete first newlines:n" + activities);
activities = activities.replaceAll("[\n]+$", "");
System.out.println("activities delete last newlines:n" + activities);
activities = activities.replaceAll("[\n]+", ",");
System.out.println("activities2:n" + activities);
ArrayList<String[]> MonitorList = dbcon.getImpAndClk(activities);
String[][] monitorArray = (String[][]) MonitorList.toArray(new String[0][0]);
if (monitorArray.length == 0) {
message = "no result";
} else {
String filename = "filename.xls";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file
/*
* CreationHelper helps us create instances of various things like DataFormat,
* Hyperlink, RichTextString etc, in a format (HSSF, XSSF) independent way
*/
CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
Sheet sheet = workbook.createSheet("Employee");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
String[] headerTitle = { "ID1", "ID2"};
// Create a Row
Row headerRow = sheet.createRow(0);
// Create header cells
for (int i = 0; i < headerTitle.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headerTitle[i]);
cell.setCellStyle(headerCellStyle);
}
workbook.write(response.getOutputStream()); // Write workbook to response.


// Closing the workbook
workbook.close();
}
}
return message;
}
}

>我已经解决了它.
在MonitorController中添加另一个requestmapping方法.java

@Controller
public class MonitorController {
private String activities = "";
private DBConnection dbcon = null;
private ArrayList<String[]> MonitorList = null;
private String[][] monitorArray = null;
@RequestMapping(value = "/showresult", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public @ResponseBody String showResult(@RequestBody QueryData querycontent, HttpServletRequest request,
HttpServletResponse response) throws FileNotFoundException, IOException, Exception {
dbcon = new DBConnection();
String message = "";
activities = querycontent.getactivities();
System.out.println("origin activities:n" + activities);
String pattern = "^[0-9\n]+$";
boolean isMatch = Pattern.matches(pattern, activities);
if (isMatch == false) {
message = "please input correct character!";
} else {
activities = activities.replaceAll("^[\n]+", "");
System.out.println("activities delete first newlines:n" + activities);
activities = activities.replaceAll("[\n]+$", "");
System.out.println("activities delete last newlines:n" + activities);
activities = activities.replaceAll("[\n]+", ",");
System.out.println("activities2:n" + activities);
MonitorList = dbcon.getImpAndClk(activities);
monitorArray = (String[][]) MonitorList.toArray(new String[0][0]);
if (monitorArray.length == 0) {
message = "no result";
} else {
}
}
return message;
}
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadLicenseFile(HttpServletResponse response) throws Exception {
System.out.println("activities in download controller:n" + activities);
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HHmm");
Date date = new Date(System.currentTimeMillis());
System.out.println(formatter.format(date));
String filename = "filename.xls";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file
/*
* CreationHelper helps us create instances of various things like DataFormat,
* Hyperlink, RichTextString etc, in a format (HSSF, XSSF) independent way
*/
CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
Sheet sheet = workbook.createSheet("SheetName");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLACK.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
String[] headerTitle = { "ID1", "ID2"};
// Create a Row
Row headerRow = sheet.createRow(0);
// Create header cells
for (int i = 0; i < headerTitle.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headerTitle[i]);
cell.setCellStyle(headerCellStyle);
}
workbook.write(response.getOutputStream()); // Write workbook to response.
// Closing the workbook
workbook.close();
}
}

索引.jsp

success : function(msg) {
document.getElementById("process_result").innerHTML = msg;
document.getElementById("process_result").style.color = 'red';
if (msg == "") {
window.location.href = '${pageContext.request.contextPath}/download';
}
},

最新更新