Skip to content

Instantly share code, notes, and snippets.

@relax-more
Created December 19, 2012 06:44
Show Gist options
  • Save relax-more/4334888 to your computer and use it in GitHub Desktop.
Save relax-more/4334888 to your computer and use it in GitHub Desktop.
csv file export Parameterから検索条件を取得し、DBを検索、結果をcsvファイルとして出力する 【メモ】
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DownloadController {
private final static String CHARSET = "UTF-8";
private final static String CONTENT_DESCRIPTION = "Content-Disposition";
private final static String CONTENT_TYPE = "application/octet-stream";
private final static String CONTENT_DESCRIPTION_VALUE = "attachment; filename=mustbuy_serial_codes.%s.tsv";
final static Logger LOGGER = LoggerFactory.getLogger(DownloadController.class);
@Autowired
AnyDao anyDao;
/**
*
* @param request
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/download/mustbuySerials.mvc")
public void dounloadMustbuySerials(@ModelAttribute("AnyModel") final AnyModel condition,
HttpServletResponse response) throws UnsupportedEncodingException {
LOGGER.debug("request_condition:" + condition.toString());
//StringBuilder builder = new StringBuilder();
response.setCharacterEncoding(CHARSET);
response.setContentType(CONTENT_TYPE);
response.setHeader(CONTENT_DESCRIPTION, String.format(CONTENT_DESCRIPTION_VALUE, condition.getEventId()));
List<AnyModel> results = anyDao.select(condition);
ServletOutputStream output = null;
PrintWriter writer = null;
try {
output = response.getOutputStream();
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(output, CHARSET)));
for (AnyModel result : results) {
writer.println(result.getSerial());
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
if (writer != null) {
writer.flush();
writer.close();
}
/**
* ServletOutputStream等、Network関連のStreamはServletContainerがOpen、Closeの管理をすることが
* あるため、Container次第ではCloseしない方がよい場合がある
*
if (output != null) {
try {
output.close();
} catch (IOException e) {
// Nothing to do
}
}
**/
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment