下面列出了javax.servlet.http.HttpServletResponse#getOutputStream() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void createResponse(byte[] buf) throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc
.getExternalContext().getResponse();
String filename = generateFileName();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachement; filename=\""
+ filename + "\"");
response.setContentLength(buf.length);
OutputStream out;
out = response.getOutputStream();
out.write(buf);
out.flush();
out.close();
fc.responseComplete();
}
@Override
public void doFilter(ServletRequest req, ServletResponse rsp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)rsp;
String contentEncoding = request.getHeader("content-encoding");
String acceptEncoding = request.getHeader("accept-encoding");
String contentType = request.getHeader("content-type");
if ((contentEncoding != null) &&
(contentEncoding.toLowerCase(Locale.ROOT).contains("gzip"))) {
request = new GZIPRequestWrapper(request);
}
if (((acceptEncoding != null) &&
(acceptEncoding.toLowerCase(Locale.ROOT).contains("gzip"))) ||
((contentType != null) && mimeTypes.contains(contentType))) {
response = new GZIPResponseWrapper(response);
}
chain.doFilter(request, response);
if (response instanceof GZIPResponseWrapper) {
OutputStream os = response.getOutputStream();
if (os instanceof GZIPResponseStream) {
((GZIPResponseStream)os).finish();
}
}
}
/**
* 图片压缩 --未测试
*/
@RequestMapping(value = "img-compress", produces = "application/json; charset=UTF-8", method = {RequestMethod.GET, RequestMethod.POST})
public void imgCompress(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
try {
byte[] reqByteAray = InputStreamUtils.toByteArray(file.getInputStream());
byte[] resByteAray = CompressImgUtils.compressImg2Byte(reqByteAray, 0, 0, true);
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
response.addHeader("Content-Length", "" + file.getSize());
OutputStream ous = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
ous.write(resByteAray);
ous.flush();
ous.close();
} catch (Exception e) {
log.error("获取图片验证码IO写入相应流失败:" + e.getMessage(), e);
}
}
@Override
protected void handleStatusOk(final HttpServletRequest req, final HttpServletResponse resp, String escapedPathInfo)
throws ClientResourceException {
TestResourceParameters parameters = getParametersFromPathInfo(escapedPathInfo);
if (null != parameters && !isNullOrEmpty(parameters.sessionId) && !isNullOrEmpty(parameters.testId)) {
try {
final String body = mapper
.writeValueAsString(new StartTestResponse(parameters.sessionId, parameters.testId).data);
try (final OutputStream os = resp.getOutputStream();
final OutputStreamWriter osw = new OutputStreamWriter(os)) {
osw.write(body);
osw.flush();
}
} catch (final IOException e) {
throw new ClientResourceException(SC_BAD_REQUEST);
}
}
}
public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException {
final GenericApplication application = getDomainObject(request, "applicationExternalId");
final String confirmationCode = (String) getFromRequest(request, "confirmationCode");
final GenericApplicationFile file = getDomainObject(request, "fileExternalId");
if (application != null
&& file != null
&& file.getGenericApplication() == application
&& ((confirmationCode != null && application.getConfirmationCode() != null && application.getConfirmationCode()
.equals(confirmationCode)) || application.getGenericApplicationPeriod().isCurrentUserAllowedToMange())) {
response.setContentType(file.getContentType());
response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\"");
response.setContentLength(file.getSize().intValue());
final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
dos.write(file.getContent());
dos.close();
} else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
response.getWriter().close();
}
return null;
}
public static BufferedWriter getWriter(HttpServletResponse httpResponse) throws IOException {
httpResponse.setContentType("text/html; charset=UTF-8");
if (X_FRAME_OPTIONS == null) {
// default value of X-Frame-Options is SAMEORIGIN
httpResponse.setHeader("X-Frame-Options", "SAMEORIGIN");
} else if (!"ALLOWALL".equals(X_FRAME_OPTIONS)) {
httpResponse.setHeader("X-Frame-Options", X_FRAME_OPTIONS);
}
try {
return new BufferedWriter(
new OutputStreamWriter(httpResponse.getOutputStream(), "UTF-8"));
} catch (final IllegalStateException e) {
// just in case, if httpResponse.getWriter() was already called (for an exception in PrometheusController for example)
return new BufferedWriter(httpResponse.getWriter());
}
}
/**
* Apply to servlet response.
* @param sresp Servlet response
* @throws IOException If fails
*/
public void applyTo(final HttpServletResponse sresp) throws IOException {
final Iterator<String> head = this.rsp.head().iterator();
final Matcher matcher = ResponseOf.HTTP_MATCHER.matcher(head.next());
if (matcher.matches()) {
sresp.setStatus(Integer.parseInt(matcher.group(1)));
while (head.hasNext()) {
ResponseOf.applyHeader(sresp, head.next());
}
try (
InputStream body = this.rsp.body();
OutputStream out = sresp.getOutputStream()
) {
final byte[] buff = new byte[ResponseOf.BUFSIZE];
// @checkstyle LineLengthCheck (1 line)
for (int read = body.read(buff); read >= 0; read = body.read(buff)) {
out.write(buff);
}
}
} else {
throw new IOException("Invalid response: response code not found");
}
}
@RequestMapping(value="/launchjob")
@ResponseBody
public void startJob(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
log.info("manual startJob");
try {
httpServletResponse.setContentType("text/plain; charset=utf-8");
ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
if(scheduleJobs.getJobStatus() == ScheduleJobs.JOB_STATUS_RUNNING) {
responseOutputStream.write("Job正在运行。。。".getBytes("utf-8"));
responseOutputStream.flush();
responseOutputStream.close();
} else {
log.info("scheduleJobs.cronJob() start by controller...");
scheduleJobs.cronJob();
}
} catch (Exception e) {
log.info("startJob exception e="+e.getMessage());
}
}
/**
* Sends an html document to the client explaining that they have used a
* poorly formed URL and then the help page...
*
* @param request The client's <code> request </code>
* @param response The client <code>response</code>
*/
public void badURL(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (Debug.isSet("showResponse")) {
log.debug("Sending Bad URL Page.");
}
// log.info("DODSServlet.badURL " + rs.getRequest().getRequestURI());
response.setContentType("text/html");
response.setHeader("XDODS-Server", getServerVersion());
response.setHeader("Content-Description", "dods-error");
// Commented because of a bug in the OPeNDAP C++ stuff...
// rs.getResponse().setHeader("Content-Encoding", "plain");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
printBadURLPage(pw);
printHelpPage(pw);
pw.flush();
response.setStatus(HttpServletResponse.SC_OK);
}
/**
* Exports tool results into excel.
*
* Had to move it from the tool as tool uses SessionMap
*/
@RequestMapping(path = "/exportExcel", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
Long toolContentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID);
List<ExcelSheet> sheets = scratchieService.exportExcel(toolContentId);
String fileName = "scratchie_export.xlsx";
fileName = FileUtil.encodeFilenameForDownload(request, fileName);
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// Code to generate file and write file contents to response
ServletOutputStream out = response.getOutputStream();
ExcelUtil.createExcel(out, sheets, null, false);
}
public void sendErrorResponse(int httpResponseCode, HttpServletResponse response) throws IOException {
response.setStatus(httpResponseCode);
response.setContentType("text/plain; charset=UTF-8");
response.setDateHeader("Expires", System.currentTimeMillis());
ServletOutputStream out = response.getOutputStream();
out.println(Constants.getMsg(httpResponseCode));
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws IOException
*/
protected void processRequest( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
AdminUser user = AdminUserService.getAdminUser( request );
// FIXME : use a jsp instead of a servlet to control the right in a standard way
if ( ( user != null ) && ( user.checkRight( StyleSheetJspBean.RIGHT_MANAGE_STYLESHEET ) ) )
{
String strStyleSheetId = request.getParameter( Parameters.STYLESHEET_ID );
if ( strStyleSheetId != null )
{
int nStyleSheetId = Integer.parseInt( strStyleSheetId );
StyleSheet stylesheet = StyleSheetHome.findByPrimaryKey( nStyleSheetId );
ServletContext context = getServletConfig( ).getServletContext( );
String strMimetype = context.getMimeType( stylesheet.getFile( ) );
response.setContentType( ( strMimetype != null ) ? strMimetype : "application/octet-stream" );
response.setHeader( "Content-Disposition", "attachement; filename=\"" + stylesheet.getFile( ) + "\"" );
OutputStream out = response.getOutputStream( );
out.write( stylesheet.getSource( ) );
out.flush( );
out.close( );
}
}
}
/**
* Writes out a <code>byte</code> to the ServletOuputStream.
*
* @param bytes the bytes to write to the <code>ServletOutputStream</code>.
*/
private void writeBytesToStream(byte[] bytes, HttpServletResponse response) {
response.setContentType(CONTENT_TYPE);
// Send image
try (ServletOutputStream sos = response.getOutputStream()) {
sos.write(bytes);
sos.flush();
}
catch (IOException e) {
// Do nothing
}
}
@RequestMapping(value = "/threadDump", method = RequestMethod.GET, produces = { "application/json" })
@ResponseBody
public void threadDump(HttpServletResponse response) {
response.setContentType("text/plain;charset=utf-8");
try (OutputStream outputStream = response.getOutputStream()) {
printThreadInfo(new PrintStream(outputStream, false, "UTF-8"), "Thread Dump");
} catch (IOException e) {
logger.error("exception when get stack trace", e);
}
}
/**
* Returns an OK response to the client
* @param resp the response object
* @param def the method definition
* @param response the result from the method
*/
public static void writeResponse(HttpServletResponse resp, WSDefinition def, double response) throws IOException {
resp.setStatus(HttpServletResponse.SC_OK);
DataOutputStream dos = new DataOutputStream(resp.getOutputStream());
dos.writeDouble(response);
dos.close();
}
@RequestMapping("/code.do")
public String getKaptchaImage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Set to expire far in the past.
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control",
"no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
// store the text in the session
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,
capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
return null;
}
public static void executeUpdate(String sql, ServletContext application, HttpServletRequest request, HttpServletResponse response) throws IOException{
response.setHeader("Content-Type", "text/html;charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
String connectionType = null;
Connection con = null;
PreparedStatement stmt = null;
TagUtil.printPageHead(out);
TagUtil.printPageNavbar(out);
TagUtil.printContentDiv(out);
try {
//Checking if connectionType is not, defaulting it to c3p0 if not set.
if(request.getParameter("connectionType") == null) {
connectionType = "c3p0";
} else {
connectionType = request.getParameter("connectionType");
}
con = ConnectionUtil.getConnection(application, connectionType);
out.println("<div class=\"panel-body\">");
out.println("<h1>SQL Query:</h1>");
out.println("<pre>");
out.println(sql);
out.println("</pre>");
logger.info(sql);
stmt = con.prepareStatement(sql);
logger.info("Created PreparedStatement: " + sql);
int result = stmt.executeUpdate();
logger.info("Executed: " + sql);
out.println("<h1>Altered Rows:</h1>");
out.print("<pre>" + result + "</pre>");
} catch(SQLException e) {
if(e.getMessage().equals("Attempted to execute a query with one or more bad parameters.")) {
int error = Integer.parseInt((String) application.getAttribute("defaultError"));
response.setStatus(error);
} else {
response.setStatus(500);
}
out.println("<div class=\"alert alert-danger\" role=\"alert\">");
out.println("<strong>SQLException:</strong> " + e.getMessage() + "<BR>");
if(logger.isDebugEnabled()) {
logger.debug(e.getMessage(), e);
} else {
logger.error(e);
}
while((e = e.getNextException()) != null) {
out.println(e.getMessage() + "<BR>");
}
} finally {
try {
if(stmt != null) {
logger.info("Closing PreparedStatement " + stmt);
stmt.close();
logger.info("Closed PreparedStatement " + stmt);
}
} catch (SQLException stmtCloseException) {
if(logger.isDebugEnabled()) {
logger.debug(stmtCloseException.getMessage(), stmtCloseException);
} else {
logger.error(stmtCloseException);
}
}
try {
if(con != null) {
logger.info("Closing Connection " + con);
con.close();
logger.info("Closed Connection " + con);
}
} catch (SQLException conCloseException) {
if(logger.isDebugEnabled()) {
logger.debug(conCloseException.getMessage(), conCloseException);
} else {
logger.error(conCloseException);
}
}
out.println("</DIV>");
TagUtil.printPageFooter(out);
out.close();
}
}
@Override
public void send(@Nullable final Request request, final Response response, final HttpServletResponse httpResponse)
throws ServletException, IOException
{
log.debug("Sending response: {}", response);
// add response headers
for (Map.Entry<String, String> header : response.getHeaders()) {
httpResponse.addHeader(header.getKey(), header.getValue());
}
// add status followed by payload if we have one
Status status = response.getStatus();
String statusMessage = status.getMessage();
try (Payload payload = response.getPayload()) {
if (status.isSuccessful() || payload != null) {
if (statusMessage == null) {
httpResponse.setStatus(status.getCode());
}
else {
httpResponse.setStatus(status.getCode(), statusMessage);
}
if (payload != null) {
log.trace("Attaching payload: {}", payload);
if (payload.getContentType() != null) {
httpResponse.setContentType(payload.getContentType());
}
if (payload.getSize() != Payload.UNKNOWN_SIZE) {
httpResponse.setContentLengthLong(payload.getSize());
}
if (request != null && !HttpMethods.HEAD.equals(request.getAction())) {
try (InputStream input = payload.openInputStream(); OutputStream output = httpResponse.getOutputStream()) {
payload.copy(input, output);
}
}
}
}
else {
httpResponse.sendError(status.getCode(), statusMessage);
}
}
}
@RequestMapping("/expsearch")
@Menu(type = "callcenter", subtype = "callcenter")
public void expall(ModelMap map , HttpServletResponse response , HttpServletRequest request ,final String username,final String channel ,final String servicetype,final String skill,final String agent,final String servicetimetype,final String begin,final String end , final String sbegin,final String send) throws IOException {
final String orgi = super.getOrgi(request);
Page<AgentService> page = agentServiceRes.findAll(new Specification<AgentService>(){
@Override
public Predicate toPredicate(Root<AgentService> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
if(!StringUtils.isBlank(username)) {
list.add(cb.equal(root.get("username").as(String.class), username)) ;
}
list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
if(!StringUtils.isBlank(channel)) {
list.add(cb.equal(root.get("channel").as(String.class), channel)) ;
}
if(!StringUtils.isBlank(agent)) {
list.add(cb.equal(root.get("agentno").as(String.class), agent)) ;
}
if(!StringUtils.isBlank(skill)) {
list.add(cb.equal(root.get("skill").as(String.class), skill)) ;
}
try {
if(!StringUtils.isBlank(begin) && begin.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
list.add(cb.greaterThanOrEqualTo(root.get("logindate").as(Date.class), UKTools.dateFormate.parse(begin))) ;
}
if(!StringUtils.isBlank(end) && end.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
list.add(cb.lessThanOrEqualTo(root.get("logindate").as(Date.class), UKTools.dateFormate.parse(end))) ;
}
if(!StringUtils.isBlank(sbegin) && sbegin.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
list.add(cb.greaterThanOrEqualTo(root.get("servicetime").as(Date.class), UKTools.dateFormate.parse(sbegin))) ;
}
if(!StringUtils.isBlank(send) && send.matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
list.add(cb.lessThanOrEqualTo(root.get("servicetime").as(Date.class), UKTools.dateFormate.parse(send))) ;
}
} catch (ParseException e) {
e.printStackTrace();
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}
},new PageRequest(super.getP(request),10000, Direction.DESC , "createtime")) ;
MetadataTable table = metadataRes.findByTablename("uk_agentservice");
List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
for (AgentService agentService : page.getContent()) {
values.add(UKTools.transBean2Map(agentService));
}
response.setHeader("content-disposition", "attachment;filename=UCKeFu-AgentService-History-"
+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xls");
ExcelExporterProcess excelProcess = new ExcelExporterProcess(values, table, response.getOutputStream());
excelProcess.process();
return;
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ReportingException if failed to handle report request
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws
ReportingException {
String component = request.getParameter("component");
String template = request.getParameter("template");
String type = request.getParameter("type");
String reportData = request.getParameter("reportDataSession");
String downloadFileName = null;
if (component == null || template == null || type == null || reportData == null) {
throw new ReportingException("required one or more parameters missing (component ,template , reportType, reportData)");
}
if (type.equals("pdf")) {
response.setContentType("application/pdf");
downloadFileName = template + ".pdf";
} else if (type.equals("excel")) {
response.setContentType("application/vnd.ms-excel");
downloadFileName = template + ".xls";
} else if (type.equals("html")) {
response.setContentType("text/html");
} else {
throw new ReportingException("requested report type can not be support");
}
if (downloadFileName != null) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
}
Object reportDataObject = request.getSession().getAttribute(reportData);
if (reportDataObject == null) {
throw new ReportingException("can't generate report , data unavailable in session ");
}
try {
String serverURL = CarbonUIUtil.getServerURL(request.getSession().getServletContext(), request.getSession());
ConfigurationContext configurationContext = (ConfigurationContext) request.getSession().getServletContext().
getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
String cookie = (String) request.getSession().getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
ReportResourceSupplierClient resourceSupplierClient = new ReportResourceSupplierClient(cookie,
serverURL, configurationContext);
String reportResource = resourceSupplierClient.getReportResources(component, template);
JRDataSource jrDataSource = new BeanCollectionReportData().getReportDataSource(reportDataObject);
JasperPrintProvider jasperPrintProvider = new JasperPrintProvider();
JasperPrint jasperPrint = jasperPrintProvider.createJasperPrint(jrDataSource ,reportResource, new ReportParamMap[0]);
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,jasperPrint);
ReportStream reportStream = new ReportStream();
ByteArrayOutputStream outputStream = reportStream.getReportStream(jasperPrint,type);
ServletOutputStream servletOutputStream = response.getOutputStream();
try{
outputStream.writeTo(servletOutputStream);
outputStream.flush();
}finally {
outputStream.close();
servletOutputStream.close();
}
} catch (Exception e) {
String msg = "Error occurred handling " + template + "report request from " + component;
log(msg);
throw new ReportingException(msg, e);
}
}