當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpServletResponse.setHeader方法代碼示例

本文整理匯總了Java中javax.servlet.http.HttpServletResponse.setHeader方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpServletResponse.setHeader方法的具體用法?Java HttpServletResponse.setHeader怎麽用?Java HttpServletResponse.setHeader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.servlet.http.HttpServletResponse的用法示例。


在下文中一共展示了HttpServletResponse.setHeader方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doGet

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String filename = request.getParameter("file");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);

    ViewerHtmlHandler handler = Utils.createViewerHtmlHandler();
    InputStream original = null;
    try {
        original = handler.getFile(filename).getStream();
    } catch (Exception x) {
        throw new RuntimeException(x);
    }

    Utils.writeToResponse(original, response);
}
 
開發者ID:groupdocs-viewer,項目名稱:GroupDocs.Viewer-for-Java-App,代碼行數:18,代碼來源:DownloadOriginalServlet.java

示例2: forwardToUrl

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void forwardToUrl(SectionInfo info, String link, int code)
{
	info.setRendered();
	try
	{
		HttpServletResponse response = info.getResponse();
		if( response == null )
		{
			throw new Error("info not bound to a request/response");
		}
		response.setStatus(code);
		response.setHeader("Location", link);
		response.flushBuffer();
	}
	catch( Exception e )
	{
		throw Throwables.propagate(e);
	}
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:21,代碼來源:SectionsControllerImpl.java

示例3: setCors

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
/**
 * Enables CORS (Cross-origin resource sharing) for the servlet;
 * 
 * @param response
 */
private void setCors(HttpServletResponse response) {
	response.setHeader("Access-Control-Allow-Origin", "*");
	response.setHeader("Access-Control-Max-Age", "3600");
	response.setHeader("Access-Control-Allow-Credentials", "true");
	response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization");
}
 
開發者ID:EixoX,項目名稱:jetfuel,代碼行數:12,代碼來源:UsecaseServlet.java

示例4: exportProjectBackupFile

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
public void exportProjectBackupFile(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	String path=req.getParameter("path");
	String projectPath=Utils.decodeURL(path);
	if(StringUtils.isEmpty(projectPath)){
		throw new RuleException("Export project not be null.");
	}
	SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");
	String projectName=projectPath.substring(1,projectPath.length());
	String filename=projectName+"-urule-repo-"+sd.format(new Date())+".bak";
	resp.setContentType("application/octet-stream");
	resp.setHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("utf-8"),"iso-8859-1") + "\"");
	resp.setHeader("content-type", "application/octet-stream");
	OutputStream outputStream=resp.getOutputStream();
	repositoryService.exportXml(projectPath,outputStream);
	outputStream.flush();
	outputStream.close();
}
 
開發者ID:youseries,項目名稱:urule,代碼行數:18,代碼來源:FrameServletHandler.java

示例5: downloadWorkflowDescription

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
private void downloadWorkflowDescription(HttpServletResponse response, String workflowName) throws ServletException {
 
    try {

        String xml = injector.getInstance(WfDefinitionService.class).fetchWfDefinition(workflowName);
        
        PrintWriter writer = response.getWriter();
        response.setContentType("application/force-download");
        response.setContentLength(xml.length());
        response.setHeader("Content-Transfer-Encoding", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + workflowName + ".oswf.xml\"");
    
        BufferedReader reader = new BufferedReader(new StringReader(xml)); 
        String line;
        while((line = reader.readLine()) != null) {
            writer.print(line);
            writer.print("\n");
        }
        
    } catch (Exception exception) {
        throw new ServletException(exception);
    }
    
}
 
開發者ID:will-gilbert,項目名稱:OSWf-OSWorkflow-fork,代碼行數:25,代碼來源:OSWfReSTServlet.java

示例6: writeJson

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
private void writeJson(HttpServletResponse response, Map<String, Object> sessionParams) throws ServletException {
	try {
		JSONObject json = new JSONObject();
		json.putAll(sessionParams);
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-cache");

		if (log.isTraceEnabled()) {
			log.trace("Responding with: " + json.toJSONString());
		}

		response.getWriter().write(json.toJSONString());
	} catch (IOException e) {
		throw new ServletException("Could not create json.", e);
	}
}
 
開發者ID:nortal,項目名稱:cas-modules,代碼行數:18,代碼來源:MobileIdController.java

示例7: doGet

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String idStr = request.getParameter("id");
	if (idStr != null) {
		Long id = Long.valueOf(idStr);
		LocationPicture picture = null;
		if (id >= 0) {
			picture = LocationPictureDAO.getInstance().get(id);
		} else {
			Map<Long, LocationPicture> temp = (Map<Long, LocationPicture>)request.getSession().getAttribute(TEMP_ROOM_PICTURES);
			if (temp != null)
				picture = temp.get(id);
		}
		if (picture != null) {
			response.setContentType(picture.getContentType());
			response.setHeader( "Content-Disposition", "attachment; filename=\"" + picture.getFileName() + "\"" );
			OutputStream out = response.getOutputStream(); 
			out.write(picture.getDataFile());
			out.flush();
		} else {
			new ServletException("Room picture of the given id does not exist.");
		}
	}
	new ServletException("No room picture id provided.");
}
 
開發者ID:Jenner4S,項目名稱:unitimes,代碼行數:25,代碼來源:RoomPictureServlet.java

示例8:

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@GET
@Path("/lsp")
@Produces(MediaType.APPLICATION_JSON)
public String 時間を指定してLSPを取得(
        @Context HttpHeaders header,
        @Context HttpServletResponse response,
        @QueryParam("time") String time,
        @QueryParam("version") String version
) throws RemoteException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    List<PasaranPOJO> pojos = LspPOJOUtil.getLsps(time, version);
    return json.format(pojos);
}
 
開發者ID:openNaEF,項目名稱:openNaEF,代碼行數:14,代碼來源:KeseranApi.java

示例9: doFilter

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	
	HttpServletResponse response = (HttpServletResponse) res;  
       response.setHeader("Access-Control-Allow-Origin", "*");  
       response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  
       response.setHeader("Access-Control-Max-Age", "3600");  
       response.setHeader("Access-Control-Allow-Headers", "x-requested-with");  
       chain.doFilter(req, res); 
	
}
 
開發者ID:shenan4321,項目名稱:BIMplatform,代碼行數:12,代碼來源:SimpleCORSFilter.java

示例10: displaySessionsListPage

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
/**
 * 
 * @param cn
 *            Name of the application for which the sessions will be listed
 * @param req
 * @param resp
 * @param smClient
 *            StringManager for the client's locale
 * @throws ServletException
 * @throws IOException
 */
protected void displaySessionsListPage(ContextName cn, HttpServletRequest req, HttpServletResponse resp,
		StringManager smClient) throws ServletException, IOException {
	List<Session> sessions = getSessionsForName(cn, smClient);
	String sortBy = req.getParameter("sort");
	String orderBy = null;
	if (null != sortBy && !"".equals(sortBy.trim())) {
		Comparator<Session> comparator = getComparator(sortBy);
		if (comparator != null) {
			orderBy = req.getParameter("order");
			if ("DESC".equalsIgnoreCase(orderBy)) {
				comparator = Collections.reverseOrder(comparator);
				orderBy = "ASC";
			} else {
				orderBy = "DESC";
			}
			try {
				Collections.sort(sessions, comparator);
			} catch (IllegalStateException ise) {
				// at least 1 of the sessions is invalidated
				req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated");
			}
		} else {
			log("WARNING: unknown sort order: " + sortBy);
		}
	}
	// keep sort order
	req.setAttribute("sort", sortBy);
	req.setAttribute("order", orderBy);
	req.setAttribute("activeSessions", sessions);
	// strong>NOTE</strong> - This header will be overridden
	// automatically if a <code>RequestDispatcher.forward()</code> call is
	// ultimately invoked.
	resp.setHeader("Pragma", "No-cache"); // HTTP 1.0
	resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP
																	// 1.1
	resp.setDateHeader("Expires", 0); // 0 means now
	getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp);
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:50,代碼來源:HTMLManagerServlet.java

示例11: write

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
/**
 * 輸出到客戶端
 * @param fileName 輸出文件名
 */
public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
    response.reset();
    response.setContentType("application/octet-stream; charset=utf-8");
    response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
    write(response.getOutputStream());
    return this;
}
 
開發者ID:sombie007,項目名稱:ExcelHandle,代碼行數:12,代碼來源:ExportExcel.java

示例12: exportExcelCourseGradebook

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
/**
    * Exports Course Gradebook into excel.
    */
   public ActionForward exportExcelCourseGradebook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {
Integer organisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID);
UserDTO user = getUser();
if (!getSecurityService().hasOrgRole(organisationID, user.getUserID(),
	new String[] { Role.GROUP_MANAGER, Role.GROUP_ADMIN }, "get course gradebook spreadsheet", false)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation");
    return null;
}

Organisation organisation = (Organisation) getUserService().findById(Organisation.class, organisationID);
if (GradebookMonitoringAction.log.isDebugEnabled()) {
    GradebookMonitoringAction.log.debug("Exporting to a spreadsheet course: " + organisationID);
}
LinkedHashMap<String, ExcelCell[][]> dataToExport = getGradebookService()
	.exportCourseGradebook(user.getUserID(), organisationID);

String fileName = organisation.getName().replaceAll(" ", "_") + ".xlsx";
fileName = FileUtil.encodeFilenameForDownload(request, fileName);

response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

// set cookie that will tell JS script that export has been finished
String downloadTokenValue = WebUtil.readStrParam(request, "downloadTokenValue");
Cookie fileDownloadTokenCookie = new Cookie("fileDownloadToken", downloadTokenValue);
fileDownloadTokenCookie.setPath("/");
response.addCookie(fileDownloadTokenCookie);

// Code to generate file and write file contents to response
ServletOutputStream out = response.getOutputStream();
ExcelUtil.createExcel(out, dataToExport, getGradebookService().getMessage("gradebook.export.dateheader"), true);

return null;
   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:39,代碼來源:GradebookMonitoringAction.java

示例13: checkIfModifiedSince

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
/**
 * Check if the if-modified-since condition is satisfied.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param resourceAttributes File object
 * @return boolean true if the resource meets the specified condition,
 * and false if the condition is not satisfied, in which case request
 * processing is stopped
 */
protected boolean checkIfModifiedSince(HttpServletRequest request,
        HttpServletResponse response,
        ResourceAttributes resourceAttributes) {
    try {
        long headerValue = request.getDateHeader("If-Modified-Since");
        long lastModified = resourceAttributes.getLastModified();
        if (headerValue != -1) {

            // If an If-None-Match header has been specified, if modified since
            // is ignored.
            if ((request.getHeader("If-None-Match") == null)
                && (lastModified < headerValue + 1000)) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setHeader("ETag", resourceAttributes.getETag());

                return false;
            }
        }
    } catch (IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;

}
 
開發者ID:liaokailin,項目名稱:tomcat7,代碼行數:37,代碼來源:DefaultServlet.java

示例14: putHeaders

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
public static void putHeaders(HttpServletResponse response, HttpContent content, long contentLength, boolean etag)
{   
    long lml=content.getResource().lastModified();
    if (lml>=0)
        response.setDateHeader(HttpHeader.LAST_MODIFIED.asString(),lml);

    if (contentLength==0)
        contentLength=content.getContentLengthValue();
    if (contentLength >=0)
    {
        if (contentLength<Integer.MAX_VALUE)
            response.setContentLength((int)contentLength);
        else
            response.setHeader(HttpHeader.CONTENT_LENGTH.asString(),Long.toString(contentLength));
    }

    String ct=content.getContentTypeValue();
    if (ct!=null && response.getContentType()==null)
        response.setContentType(ct);

    String ce=content.getContentEncodingValue();
    if (ce!=null)
        response.setHeader(HttpHeader.CONTENT_ENCODING.asString(),ce);
    
    if (etag)
    {
        String et=content.getETagValue();
        if (et!=null)
            response.setHeader(HttpHeader.ETAG.asString(),et);
    }
}
 
開發者ID:jmfgdev,項目名稱:gitplex-mit,代碼行數:32,代碼來源:Response.java

示例15: setExpiresHeader

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
/**
 * 設置客戶端緩存過期時間 的Header.
 */
public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
	// Http 1.0 header, set a fix expires date.
	response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + expiresSeconds * 1000);
	// Http 1.1 header, set a time after now.
	response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + expiresSeconds);
}
 
開發者ID:egojit8,項目名稱:easyweb,代碼行數:10,代碼來源:Servlets.java


注:本文中的javax.servlet.http.HttpServletResponse.setHeader方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。