Java Code Examples for javax.servlet.ServletResponse#getWriter()

The following examples show how to use javax.servlet.ServletResponse#getWriter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthorityFilter.java    From springboot-learn with MIT License 7 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    PrintWriter out = null;
    HttpServletResponse res = (HttpServletResponse) response;
    try {
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json");
        out = response.getWriter();
        out.println(JSONObject.toJSON(Result.error(MsgConstants.NOT_LOGIN)));
    } catch (Exception e) {
    } finally {
        if (null != out) {
            out.flush();
            out.close();
        }
    }
    return false;
}
 
Example 2
Source File: AjaxPermissionsAuthorizationFilter.java    From SpringBoot-Shiro-Vue with MIT License 7 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
	JSONObject jsonObject = new JSONObject();
	jsonObject.put("code", ErrorEnum.E_20011.getErrorCode());
	jsonObject.put("msg", ErrorEnum.E_20011.getErrorMsg());
	PrintWriter out = null;
	HttpServletResponse res = (HttpServletResponse) response;
	try {
		res.setCharacterEncoding("UTF-8");
		res.setContentType("application/json");
		out = response.getWriter();
		out.println(jsonObject);
	} catch (Exception e) {
	} finally {
		if (null != out) {
			out.flush();
			out.close();
		}
	}
	return false;
}
 
Example 3
Source File: CaptchaFormAuthenticationFilter.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
/**
 * 主要是处理登入失败的方法
 */
@Override
protected boolean onLoginFailure(AuthenticationToken token,
		AuthenticationException e, ServletRequest request,
		ServletResponse response) {
	setFailureAttribute(request, e);
	if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request)
			.getHeader("X-Requested-With"))) {// 不是ajax请求
		return true;
	}
	try {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.printf("{success:false,message:'%s'}",
				request.getAttribute(getFailureKeyAttribute()));
		out.flush();
		out.close();
	} catch (IOException e1) {
		log.fatal("异步跳转异常", e);
	}
	return false;
}
 
Example 4
Source File: MyUserFilter.java    From MyBlog with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write(JSON.toJSONString(MyResponse.createResponse(ResponseEnum.NON_LOGIN)));
    return false;
}
 
Example 5
Source File: RegServlet.java    From onlineTest with Apache License 2.0 5 votes vote down vote up
@Override
public void service(ServletRequest request, ServletResponse response)
		throws ServletException, IOException {
	    
	request.setCharacterEncoding("utf-8");
	response.setContentType("text/html;charset=utf-8");
	String loginname = request.getParameter("loginname");
	String password = request.getParameter("password");
	String email = request.getParameter("email");
	String phone = request.getParameter("phone");
	String sex = request.getParameter("sex");
	String birth = request.getParameter("birth");
	String uname = request.getParameter("uname");
	
	User user = new User(0, loginname, password, email, phone, sex, birth, uname, "0");
	UserDAO userDAO = new UserDAO();
	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE html>");
	out.println("<html>");
	out.println("	<head>");
	out.println("	</head>");
	out.println("	<body>");
	if(userDAO.add(user)){
		out.println("	恭喜,注册成功!<a href=\"/login.html\">进入登录页面</a>");
	}else{
		out.println("	抱歉,注册失败!<a href=\"/reg.html\">回到首页</a>");
	}
	out.println("	</body>");
	out.println("</html>");
	out.flush();
	out.close();
}
 
Example 6
Source File: LoginServlet.java    From onlineTest with Apache License 2.0 5 votes vote down vote up
@Override
public void service(ServletRequest request, ServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=utf-8");
	
	String loginname = request.getParameter("loginname");
	String password = request.getParameter("password");
	UserDAO userDAO = new UserDAO();
	User user = userDAO.login(loginname, password);
	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE html>");
	out.println("<html>");
	out.println("	<head>");
	out.println("	</head>");
	out.println("	<body>");
	if(user != null){			
		((HttpServletRequest)request).getSession().setAttribute("user", user);
		if("1".equals(user.getUlevel())){
			out.println("<div align=\"center\">欢迎 " + user.getUname() + ", 登录成功!<a href=\"/user/list.action\">点击进入管理员页面</a></div>");
		}else{
			out.println("<div align=\"center\">欢迎 " + user.getUname() + ", 登录成功!<a href=\"/test.action\">点击开始考试</a></div>");
		}
	}else{
		out.println("<div align=\"center\">登录失败,请重新登录<a href=\"/login.html\">登录</a></div>");
	}         
	out.println("	</body>");
	out.println("</html>");
	out.flush();
	out.close();
}
 
Example 7
Source File: IncludeTagFilter.java    From sling-org-apache-sling-dynamic-include with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException {
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    final String resourceType = slingRequest.getResource().getResourceType();

    final Configuration config = configurationWhiteboard.getConfiguration(slingRequest, resourceType);
    if (config == null) {
        chain.doFilter(request, response);
        return;
    }

    final IncludeGenerator generator = generatorWhiteboard.getGenerator(config.getIncludeTypeName());
    if (generator == null) {
        LOG.error("Invalid generator: " + config.getIncludeTypeName());
        chain.doFilter(request, response);
        return;
    }

    final PrintWriter writer = response.getWriter();
    final String url = getUrl(config, slingRequest);
    if (url == null) {
        chain.doFilter(request, response);
        return;
    }

    if (config.getAddComment()) {
        writer.append(String.format(COMMENT, StringEscapeUtils.escapeHtml4(url), resourceType));
    }

    // Only write the includes markup if the required, configurable request
    // header is present
    if (shouldWriteIncludes(config, slingRequest)) {
        String include = generator.getInclude(url);
        LOG.debug(include);
        writer.append(include);
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 8
Source File: XSSWebAppSRPWDelay.java    From spiracle with Apache License 2.0 5 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    try {
        Thread.sleep(10000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    ReadHTML.readHTML(out, req.getParameter("taintedtext"), req);
}
 
Example 9
Source File: ServletResponseMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Object resolveArgument(Class<?> paramType, ServletResponse response) throws IOException {
	if (OutputStream.class.isAssignableFrom(paramType)) {
		return response.getOutputStream();
	}
	else if (Writer.class.isAssignableFrom(paramType)) {
		return response.getWriter();
	}

	// Should never happen...
	throw new UnsupportedOperationException("Unknown parameter type: " + paramType);
}
 
Example 10
Source File: WebPBEConfigFilter.java    From jasypt with Apache License 2.0 5 votes vote down vote up
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    final WebPBEConfigRegistry registry = WebPBEConfigRegistry.getInstance();
    if (registry.isWebConfigurationDone()) {
        // If it is initialized, quickly continue filter chain
        chain.doFilter(request, response);
    } else {
        // Not initialized, a Forbidden page must be shown, chain broken
        PrintWriter printWriter = response.getWriter();
        printWriter.write(WebPBEConfigHtmlUtils.createNotInitializedHtml());
        printWriter.flush();
    }
    
}
 
Example 11
Source File: SystemLogoutFilter.java    From web-flash with MIT License 5 votes vote down vote up
private void writeResult(ServletResponse response){
    //响应Json结果
    PrintWriter out = null;
    try {
        out = response.getWriter();
        out.append(JsonUtil.toJson(Rets.success()));
    } catch (IOException e) {
        logger.error("返回Response信息出现IOException异常:" + e.getMessage());
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
 
Example 12
Source File: ServletBlockingHttpExchange.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public OutputStream getOutputStream() {
    ServletResponse response = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletResponse();
    try {
        try {
            return response.getOutputStream();
        } catch (IllegalStateException ex) {
            return new WriterOutputStream(exchange, response.getWriter(), response.getCharacterEncoding());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
Source File: Bug2928673.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (response instanceof HttpServletResponse) {
        final PrintWriter out = response.getWriter();
        final HttpServletResponse wrapper = (HttpServletResponse) response;
        chain.doFilter(request, wrapper);
        final String origData = wrapper.getContentType();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Hello");
        }
        if ("text/html".equals(wrapper.getContentType())) {
            final CharArrayWriter caw = new CharArrayWriter();
            final int bodyIndex = origData.indexOf("</body>");
            if (-1 != bodyIndex) {
                caw.write(origData.substring(0, bodyIndex - 1));
                caw.write("\n<p>My custom footer</p>");
                caw.write("\n</body></html>");
                response.setContentLength(caw.toString().length());
                out.write(caw.toString());
            } else {
                out.write(origData);
            }
        } else {
            out.write(origData);
        }
        out.close();
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 14
Source File: ServletResponseMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Object resolveArgument(Class<?> paramType, ServletResponse response) throws IOException {
	if (OutputStream.class.isAssignableFrom(paramType)) {
		return response.getOutputStream();
	}
	else if (Writer.class.isAssignableFrom(paramType)) {
		return response.getWriter();
	}

	// Should never happen...
	throw new UnsupportedOperationException("Unknown parameter type: " + paramType);
}
 
Example 15
Source File: ServletBlockingHttpExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example 16
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@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);
}
 
Example 17
Source File: PreviewFilter.java    From publick-sling-blog with Apache License 2.0 4 votes vote down vote up
/**
 * Handle blog posts that are not published. If the user is authenticated,
 * display a preview bar. If the user is anonymous, seve a 404.
 *
 * @param request The Sling HTTP Servlet Request.
 * @param response The Sling HTTP Servlet Response.
 * @param chain The Filter Chain to continue processin the response.
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    // Since this is a Sling Filter, the request and response objects are guaranteed
    // to be of types SlingHttpServletRequest and SlingHttpServletResponse.
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest)request;
    final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse)response;

    final Resource resource = slingRequest.getResource();
    final String method = slingRequest.getMethod();
    final String resourceType = resource.getResourceType();

    response.setCharacterEncoding(CharEncoding.UTF_8);

    if ("GET".equals(method) && PublickConstants.PAGE_TYPE_BLOG.equals(resourceType)) {

        if (!resource.getValueMap().get("visible", false)) {
            final boolean authorable = userService.isAuthorable(slingRequest.getResourceResolver().adaptTo(Session.class));

            /* If user is logged in and page isn't published, inject a preview bar. */
            if (authorable) {
                PrintWriter out = response.getWriter();
                CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse)response);

                try {
                  chain.doFilter(request, responseWrapper);
                } catch (Exception e) {
                  LOGGER.error("Could not continue chain", e);
                  chain.doFilter(request, response);
                }

                final String servletResponse = new String(responseWrapper.toString());
                final String previewHeader = getPreviewHeader(slingRequest, PREVIEW_HEADER_PATH);

                /* Insert component before body close tag. Append to end if body close tag doesn't exist. */
                if (servletResponse != null && servletResponse.contains(INSERTION_TAG)) {
                    String[] html = servletResponse.split(INSERTION_TAG);

                    out.write(html[0] + INSERTION_TAG + previewHeader + html[1]);
                } else {
                    out.write(servletResponse + previewHeader);
                }
            } else {
                /* If user is not logged in and page isn't published, forward to 404. */
                slingResponse.sendError(SlingHttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            chain.doFilter(request, slingResponse);
        }
    } else {
        chain.doFilter(request, slingResponse);
    }
}
 
Example 18
Source File: TutorialFilter.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException
{
  final String uri = ((HttpServletRequest) req).getRequestURI();
  if (uri.matches(".*/ProjectForge.*.html") == false) {
    chain.doFilter(req, resp);
    return;
  }
  final PrintWriter out = resp.getWriter();
  final CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) resp);
  chain.doFilter(req, wrapper);
  final CharArrayWriter caw = new CharArrayWriter();
  final String tutorialUrl = ((HttpServletResponse) resp).encodeURL(WicketUtils.getAbsoluteUrl("/wa/tutorial"));
  final String regexp = "(\\{actionLink\\|)([a-zA-Z0-9]*)\\|([a-zA-Z0-9_\\-]*)(\\})([^\\{]*)(\\{/actionLink\\})";
  final Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); // Compiles regular expression into Pattern.
  final Matcher m = p.matcher(wrapper.toString());
  final StringBuffer buf = new StringBuffer();
  // final String html = m.replaceAll(tutorialUrl + "/Hurzel");
  try {
    while (m.find() == true) {
      int i = 2;
      if (m.groupCount() != 6) {
        buf.append("{actionLink syntax error: " + m.groupCount() + ".}");
        continue;
      }
      // {actionLink|createUser|linda}create{/actionLink}
      m.appendReplacement(buf, "<a target=\"tutorial\" href=\"");
      buf.append(tutorialUrl);
      final String type = m.group(i++); // createUser
      if (type == null) {
        buf.append("\">create</a>");
        continue;
      }
      buf.append("?type=").append(type).append("&ref=");
      final String ref = m.group(i++);
      if (ref == null) {
        buf.append("\">create</a>");
        continue;
      }
      buf.append(ref).append("\"><img src=\"images/actionlink_add.png\" style=\"vertical-align:middle;border:none;\" />");
      i++; // }
      final String label = m.group(i++);
      if (label == null) {
        buf.append("\">create</a>");
        continue;
      }
      buf.append(label);
      buf.append("</a>");
    }
    m.appendTail(buf);
  } catch (final Exception ex) {
    log.error(ex.getMessage(), ex);
  }

  // html = html.replace("{actionLink}", tutorialUrl);
  // <link url="{actionLink}?type=createUser&amp;ref=linda" target="tutorial">create</link>
  caw.write(buf.toString());
  // caw.write(wrapper.toString().substring(0, wrapper.toString().indexOf("</body>") - 1));
  // caw.write("<p>\n<center>" + messages.getString("Visitor") + "<font color='red'>" + counter.getCounter() + "</font></center>");
  // caw.write("\n</body></html>");
  resp.setContentLength(caw.toString().length());
  out.write(caw.toString());
  out.close();
}
 
Example 19
Source File: Inter14.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void f(String s1, int i, ServletResponse resp) throws IOException {
	if(i != 0) {
	    PrintWriter writer = resp.getWriter();
        writer.println(s1);                    /* BAD */
	}		
}
 
Example 20
Source File: Inter4.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void f(ServletResponse resp) throws IOException {
    PrintWriter writer = resp.getWriter();
    writer.println(this.name);         /* BAD */        
}