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


Java ServletResponse.getWriter方法代碼示例

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


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

示例1: onPreHandle

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
@Override
public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    if (this.isAccessAllowed(request, response, mappedValue) && this.isLoginRequest(request, response)) {
        if (((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("{\"code\":200,\"info\":\"already logined\"}");
            out.flush();
            out.close();
        }else {
            WebUtils.issueRedirect(request,response,this.getSuccessUrl());
        }
        return false;
    }
    return super.onPreHandle(request, response, mappedValue);
}
 
開發者ID:liaojiacan,項目名稱:zkAdmin,代碼行數:18,代碼來源:LoginFilter.java

示例2: showStatus

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
/**
 * Show the status of the conf and the filter to the user.
 * 
 * @param request
 *            to get status info from
 * @param response
 *            response to show the status on.
 * @throws java.io.IOException
 *             if the output cannot be written
 */
private void showStatus(final HttpServletRequest request, final ServletResponse response) throws IOException {

    log.debug("showing status");

    if (allowConfSwapViaHttp) {
        String newConfPath = request.getParameter("conf");
        if (!StringUtils.isBlank(newConfPath)) {
            confPath = newConfPath;
            loadUrlRewriterLocal();
        }
    }

    Status status = new Status(confLastLoaded, this);
    status.displayStatusInContainer(request);

    response.setContentType("text/html; charset=UTF-8");
    response.setContentLength(status.getBuffer().length());

    final PrintWriter out = response.getWriter();
    out.write(status.getBuffer().toString());
    out.close();

}
 
開發者ID:luckyyeah,項目名稱:YiDu-Novel,代碼行數:34,代碼來源:UrlRewriteFilter.java

示例3: doFilter

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    out.print(getClass().getName());
    chain.doFilter(request, response);
}
 
開發者ID:liaokailin,項目名稱:tomcat7,代碼行數:8,代碼來源:TestStandardContext.java

示例4: service

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<!DOCTYPE html>\n"+
        "<html>\n"+
        "<head>\n"+
        "<meta charset='UTF-8'>\n"+
        "<title>Hello Servlet</title>\n"+
        "</head>\n"+
        "<body>\n"+
        "<h2>Hello Servlet!</h2>\n"+
        "Go <a href='"+
            request.getServletContext().getContextPath()+
        "'>Back</a>\n"+
        "</body>\n"+
        "</html>");
    pw.close();
}
 
開發者ID:biblelamp,項目名稱:JavaEE,代碼行數:20,代碼來源:HelloServlet.java

示例5: writeJson

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
/**
 * response 輸出JSON
 * @param response
 * @param resultMap
 * @throws IOException
 */
public static void writeJson(ServletResponse response, Map<String, Object> resultMap){
	PrintWriter out = null;
	try {
		response.setCharacterEncoding("UTF-8");
		out = response.getWriter();
		out.print(JSON.toJSONString(resultMap));
	} catch (Exception e) {
		logger.error("輸出JSON異常:", e);
	}finally{
		if(null != out){
			out.flush();
			out.close();
		}
	}
}
 
開發者ID:wjggwm,項目名稱:webside,代碼行數:22,代碼來源:ShiroUtils.java

示例6: onTimeout

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
@Override
public void onTimeout(AsyncEvent event) throws IOException {
  // in this time, maybe:
  // 1.invocation in executor's queue
  // 2.already executing in executor
  // 3.already send response
  // to avoid concurrent, must lock request
  ServletRequest request = event.getSuppliedRequest();
  HttpServletRequestEx requestEx = (HttpServletRequestEx) request.getAttribute(RestConst.REST_REQUEST);

  synchronized (requestEx) {
    ServletResponse response = event.getAsyncContext().getResponse();
    if (!response.isCommitted()) {
      LOGGER.error("Rest request timeout, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI());
      // invocation in executor's queue
      response.setContentType(MediaType.APPLICATION_JSON);

      // we don't know if developers declared one statusCode in contract
      // so we use cse inner statusCode here
      ((HttpServletResponse) response).setStatus(ExceptionFactory.PRODUCER_INNER_STATUS_CODE);
      PrintWriter out = response.getWriter();
      out.write(TIMEOUT_MESSAGE);
      response.flushBuffer();
    }

    request.removeAttribute(RestConst.REST_REQUEST);
  }
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:29,代碼來源:RestAsyncListener.java

示例7: doBeforeProcessing

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
private void doBeforeProcessing(ServletRequest request, ServletResponse response)
		throws IOException, ServletException {
	try (PrintWriter out = response.getWriter()) {
		out.print("my--");
		out.flush();
	}
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Java-EE-Development-with-WildFly,代碼行數:8,代碼來源:MyBarFilter.java

示例8: doFilter

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	PrintWriter out = response.getWriter();
	ResponseCharacterWrapper wrappedResponse = new ResponseCharacterWrapper((HttpServletResponse) response);

	doBeforeProcessing(request, wrappedResponse);
	chain.doFilter(request, wrappedResponse);
	doAfterProcessing(request, wrappedResponse);

	out.write(wrappedResponse.toString());
	logger.info("filter name: " + filterConfig.getFilterName());
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Java-EE-Development-with-WildFly,代碼行數:14,代碼來源:MyBarFilter.java

示例9: doFilter

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	if (isWhiteReq(request.getRequestURI())) {
		chain.doFilter(request, response);
	} else {
		String token = request.getHeader("token");
		if (StringUtils.isNotBlank(token)) {
			try {
				Token tokenInfo = TokenUtil.getTokenInfo(token);
				if (tokenInfo != null) {
					Long now = System.currentTimeMillis();
					if (now - tokenInfo.getTime() < 1000 * 60 * 30) {
						String value = tokenInfo.getValue();
						TokenUtil.setTokenInfo(token, value);
						WebUtil.saveCurrentUser(request, value);
					}
				}
			} catch (Exception e) {
				logger.error("token檢查發生異常:", e);
			}
		}
		// 響應
		if (DataUtil.isEmpty(WebUtil.getCurrentUser(request))) {
			response.setContentType("text/html; charset=UTF-8");
			Map<String, Object> modelMap = InstanceUtil.newLinkedHashMap();
			modelMap.put("httpCode", HttpCode.UNAUTHORIZED.value());
			modelMap.put("msg", HttpCode.UNAUTHORIZED.msg());
			modelMap.put("timestamp", System.currentTimeMillis());
			PrintWriter out = response.getWriter();
			out.println(JSON.toJSONString(modelMap));
			out.flush();
			out.close();
		} else {
			chain.doFilter(request, response);
		}
	}
}
 
開發者ID:guokezheng,項目名稱:automat,代碼行數:39,代碼來源:TokenFilter.java

示例10: onAccessDenied

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    if (isLoginRequest(request, response)) {
        if (isLoginSubmission(request, response)) {
            if (log.isTraceEnabled()) {
                log.trace("Login submission detected.  Attempting to execute login.");
            }
            return executeLogin(request, response);
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Login page view.");
            }
            // allow them to see the login page ;)
            return true;
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Attempting to access a path which requires authentication.  Forwarding to the "
                    + "Authentication url [" + getLoginUrl() + "]");
        }
        if (!((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")) {
            saveRequestAndRedirectToLogin(request, response);
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("{\"code\":-203,\"info\":\"login\"}");
            out.flush();
            out.close();
        }
        return false;
    }
}
 
開發者ID:liaojiacan,項目名稱:zkAdmin,代碼行數:34,代碼來源:LoginFilter.java

示例11: onLoginFailure

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    if (!((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")) {
        setFailureAttribute(request, e);
        return true;
    }
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        String message = e.getClass().getSimpleName();
        if ("IncorrectCredentialsException".equals(message)
                || "UnknownAccountException".equals(message)
                ) {
            out.println("{\"code\":-100010,\"info\":\"賬號或密碼錯誤\"}");
        }else if("ExcessiveAttemptsException".equals(message)){
            out.println("{\"code\":-100020,\"info\":\"密碼錯誤次數超過限製,請10分鍾後重試!\"}");
        }else if("LockedAccountException".equals(message)){
            out.println("{\"code\":-100030,\"info\":\"賬號已停用!\"}");
        } else {
            out.println("{\"code\":-100500,\"info\":\"未知錯誤\"}");
        }
        out.flush();
        out.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return false;
}
 
開發者ID:liaojiacan,項目名稱:zkAdmin,代碼行數:31,代碼來源:LoginFilter.java

示例12: _getHtmlWriter

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
/**
 * @todo Generalize???
 */
private Writer _getHtmlWriter(FacesContext context) throws IOException
{
  ServletResponse response = (ServletResponse)
    context.getExternalContext().getResponse();
  response.setContentType(_HTML_MIME_TYPE);
  return response.getWriter();
}
 
開發者ID:apache,項目名稱:myfaces-trinidad,代碼行數:11,代碼來源:CoreRenderKit.java

示例13: handleError

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
/**
 * Handle a server-side error by reporting it back to the client.
 */
public static void handleError(ExternalContext ec, 
                               Throwable t) throws IOException
{
  String error = _getErrorString();
  _LOG.severe(error, t);

  ServletResponse response = (ServletResponse)ec.getResponse();
  PrintWriter writer = response.getWriter();
  XmlResponseWriter rw = new XmlResponseWriter(writer, "UTF-8");
  rw.startDocument();
  rw.startElement("partial-response", null);
  rw.startElement("error", null);
  rw.startElement("error-name", null);
  rw.writeText(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
  rw.endElement("error-name");

  String errorMessage = _getErrorMessage(error);

  // Default exception message contains the type of the exception.
  // Do not send this info to client in Production mode
  ApplicationFactory factory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
  Application application = factory.getApplication();
  if (application.getProjectStage() != ProjectStage.Production)
  {
    errorMessage = _getExceptionString(t) + errorMessage;
  }

  rw.startElement("error-message", null);
  rw.writeText(errorMessage, null);
  rw.endElement("error-message");

  rw.endElement("error");
  rw.endElement("partial-response");
  rw.endDocument();
  rw.close();
}
 
開發者ID:apache,項目名稱:myfaces-trinidad,代碼行數:40,代碼來源:XmlHttpConfigurator.java

示例14: getSender

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
@Override
public Sender getSender() {
    try {
        return new BlockingSenderImpl(exchange, getOutputStream());
    } catch (IllegalStateException e) {
        ServletResponse response = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletResponse();
        try {
            return new BlockingWriterSenderImpl(exchange, response.getWriter(), response.getCharacterEncoding());
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:14,代碼來源:ServletBlockingHttpExchange.java

示例15: process

import javax.servlet.ServletResponse; //導入方法依賴的package包/類
protected void process(ServletRequest req, ServletResponse resp, FilterChain filterChain, WebMethod webMethod) {
	try {
		ViewModel responseValue = (ViewModel) webMethod.invoke((HttpServletRequest) req,
				(HttpServletResponse) resp, filterChain);
		PrintWriter writer = resp.getWriter();
		String viewContent = templateMarkService.exec(responseValue.getViewName(), responseValue);
		writer.print(viewContent);
		writer.flush();
		return;
	} catch (Exception e) {
		ProcessLogger.error(CommonUtilities.getCurrentInvokerMethod(), e);
	}
}
 
開發者ID:daileyet,項目名稱:helpdesk,代碼行數:14,代碼來源:ViewModelMappingWebHandler.java


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