下面列出了javax.servlet.ServletOutputStream#println ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
final ServletOutputStream out = response.getOutputStream();
final Map<String, Object> bindings = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
try {
final Context context = (Context) new InitialContext().lookup("java:comp/");
addBindings("", bindings, context);
} catch (final NamingException e) {
throw new ServletException(e);
}
out.println("JNDI Context:");
for (final Map.Entry<String, Object> entry : bindings.entrySet()) {
if (entry.getValue() != null) {
out.println(" " + entry.getKey() + "=" + entry.getValue());
} else {
out.println(" " + entry.getKey());
}
}
}
/**
* this is the main method of the servlet that will service all get
* requests.
*
* @param request
* HttpServletRequest
* @param responce
* HttpServletResponce
**/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
res.setContentType("text/html");
// The following 2 lines are the difference between PingServlet and
// PingServletWriter
// the latter uses a PrintWriter for output versus a binary output
// stream.
ServletOutputStream out = res.getOutputStream();
// java.io.PrintWriter out = res.getWriter();
hitCount++;
out.println("<html><head><title>Ping Servlet</title></head>"
+ "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime
+ "<BR><BR></FONT> <B>Hit Count: " + hitCount + "</B></body></html>");
} catch (Exception e) {
Log.error(e, "PingServlet.doGet(...): general exception caught");
res.sendError(500, e.toString());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
ServletOutputStream out = response.getOutputStream();
Map<String, Object> bindings = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
try {
Context context = (Context) new InitialContext().lookup("java:comp/");
addBindings("", bindings, context);
} catch (NamingException e) {
throw new ServletException(e);
}
out.println("JNDI Context:");
for (Map.Entry<String, Object> entry : bindings.entrySet()) {
if (entry.getValue() != null) {
out.println(" " + entry.getKey() + "=" + entry.getValue());
} else {
out.println(" " + entry.getKey());
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
ServletOutputStream out = response.getOutputStream();
OUT = out;
try {
out.println("Pojo Webservice");
out.println(" helloPojo.hello(\"Bob\")=" + helloPojo.hello("Bob"));
out.println();
out.println(" helloPojo.hello(null)=" + helloPojo.hello(null));
out.println();
out.println("EJB Webservice");
out.println(" helloEjb.hello(\"Bob\")=" + helloEjb.hello("Bob"));
out.println();
out.println(" helloEjb.hello(null)=" + helloEjb.hello(null));
out.println();
} finally {
OUT = out;
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletOutputStream out = response.getOutputStream();
response.setContentType("text/plain");
Enumeration<String> e = request.getHeaders("Accept-Encoding");
while (e.hasMoreElements()) {
String name = e.nextElement();
out.println(name);
if (name.indexOf("gzip") != -1) {
out.println("gzip supported -- able to compress");
}
else {
out.println("gzip not supported");
}
}
out.println("Compression Filter Test Servlet");
out.println("Minimum content length for compression is 128 bytes");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.close();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletOutputStream out = response.getOutputStream();
response.setContentType("text/plain");
Enumeration<String> e = request.getHeaders("Accept-Encoding");
while (e.hasMoreElements()) {
String name = e.nextElement();
out.println(name);
if (name.indexOf("gzip") != -1) {
out.println("gzip supported -- able to compress");
}
else {
out.println("gzip not supported");
}
}
out.println("Compression Filter Test Servlet");
out.println("Minimum content length for compression is 128 bytes");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.close();
}
public void sendOKResponse(HttpServletResponse response, String data) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/plain; charset=UTF-8");
response.setDateHeader("Expires", System.currentTimeMillis());
if (null != data) {
ServletOutputStream out = response.getOutputStream();
out.println(data);
}
}
private void formular(ServletOutputStream out, HttpServletRequest requ,
HttpServletResponse resp, int sub) throws IOException {
out.print("<form method='post' action='");
out.print(requ.getRequestURI());
out.print("?action=");
out.print(ACT_INIT);
out.print("&sub=");
out.print(ACT_REPORT_1);
out.println("'>");
out.print("<input type='checkbox' name='preview' value='Y'");
if (requ.getParameter("preview") != null)
out.print(" checked ");
out.println(">preview<br>");
out.println("<input type=submit value='Report 1'>");
out.println("</form>");
if (sub != ACT_INIT) {
if (requ.getParameter("preview") != null) {
out.println("<script language='JavaScript'>");
out.print("w = window.open(\"");
out.print(requ.getRequestURI());
out.print("?action=");
out.print(sub);
out
.print("&preview=Y\", \"Printing\", \"width=800,height=450,scrollbars,menubar=yes,resizable=yes\");");
out.println("</script>");
} else {
out.print("<iframe src='");
out.print(requ.getRequestURI());
out.print("?action=");
out.print(sub);
out.println("' width='10' height='10' name='pdf_box'>");
}
}
out.println("</body>");
out.println("</html>");
}
@Test
public void testPropagateContentLength() throws IOException {
responseWrapper.setContentLength(10);
ServletOutputStream os = responseWrapper.getOutputStream();
verify(response).getOutputStream();
verify(requestWrapper, never()).propagateSession();
os.println();
verify(requestWrapper, never()).propagateSession();
os.println("1234567890");
verify(requestWrapper, atLeastOnce()).propagateSession();
}
/**
* Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an
* exception).
*
* @param resourceInfo
* The ResourceInfo object
* @param ostream
* The output stream to write to
* @param ranges
* Enumeration of the ranges the client wanted to retrieve
* @param contentType
* Content type of the resource
* @exception IOException
* if an input/output error occurs
*/
private void copy(ResourceInfo resourceInfo, ServletOutputStream ostream, Enumeration ranges, String contentType) throws IOException {
IOException exception = null;
while ((exception == null) && (ranges.hasMoreElements())) {
InputStream resourceInputStream = resourceInfo.getStream();
InputStream istream = // FIXME:ms: internationalization???????
new BufferedInputStream(resourceInputStream, input);
Range currentRange = (Range) ranges.nextElement();
// Writing MIME header.
ostream.println("--" + mimeSeparation);
if (contentType != null)
ostream.println("Content-Type: " + contentType);
ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/" + currentRange.length);
ostream.println();
// Printing content
exception = copyRange(istream, ostream, currentRange.start, currentRange.end);
try {
istream.close();
} catch (Throwable t) {
}
}
ostream.print("--" + mimeSeparation + "--");
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
private static void writeToResponse(Boolean allResults, Boolean showOutput, ServletOutputStream out, ResultSet rs) throws SQLException, IOException {
ResultSetMetaData metaData = rs.getMetaData();
out.println("<h1>Results:</h1>");
out.println("<TABLE CLASS=\"table table-bordered table-striped\">");
out.println("<TR>");
for(int i = 1; i <= metaData.getColumnCount(); i++) {
String colName = metaData.getColumnName(i);
out.print("<TH>" + colName + "</TH>");
}
out.println("</TR>");
//Matching sqlmap's testenv option to suppress output
if(showOutput) {
//Matching sqlmap's testenv partial output option.
if(allResults) {
while(rs.next()) {
writeRow(out, rs, metaData);
}
} else {
rs.next();
writeRow(out, rs, metaData);
}
}
out.println("</TABLE>");
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletOutputStream out = response.getOutputStream();
response.setContentType("text/plain");
Enumeration<String> e = request.getHeaders("Accept-Encoding");
while (e.hasMoreElements()) {
String name = e.nextElement();
out.println(name);
if (name.indexOf("gzip") != -1) {
out.println("gzip supported -- able to compress");
}
else {
out.println("gzip not supported");
}
}
out.println("Compression Filter Test Servlet");
out.println("Minimum content length for compression is 128 bytes");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.close();
}
public void sendOKResponse(HttpServletResponse response, String data) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/plain; charset=UTF-8");
response.setDateHeader("Expires", System.currentTimeMillis());
if (null != data) {
ServletOutputStream out = response.getOutputStream();
out.println(data);
}
}
public void sendOKResponse(HttpServletResponse response, String data) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/plain; charset=UTF-8");
response.setDateHeader("Expires", System.currentTimeMillis());
if (null != data) {
ServletOutputStream out = response.getOutputStream();
out.println(data);
}
}
/**
* this is the main method of the servlet that will service all get
* requests.
*
* @param request
* HttpServletRequest
* @param responce
* HttpServletResponce
**/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
res.setContentType("text/html");
String lengthParam = req.getParameter("contentLength");
Integer length;
if (lengthParam == null) {
length = 0;
} else {
length = Integer.parseInt(lengthParam);
}
ServletOutputStream out = res.getOutputStream();
// Add characters (a's) to the SOS to equal the requested length
// 167 is the smallest length possible.
int i = 0;
String buffer = "";
while (i + 167 < length) {
buffer = buffer + "a";
i++;
}
out.println("<html><head><title>Ping Servlet</title></head>"
+ "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet<BR></FONT><FONT size=\"+1\" color=\"#000066\">" + buffer
+ "</B></body></html>");
} catch (Exception e) {
Log.error(e, "PingServlet.doGet(...): general exception caught");
res.sendError(500, e.toString());
}
}
/**
* this is the main method of the servlet that will service all get
* requests.
*
* @param request
* HttpServletRequest
* @param responce
* HttpServletResponce
**/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
res.setContentType("text/html");
ServletOutputStream out = res.getOutputStream();
hitCount++;
// JSON generate
StringWriter sw = new StringWriter();
JsonGenerator generator = Json.createGenerator(sw);
generator.writeStartObject();
generator.write("initTime",initTime);
generator.write("hitCount", hitCount);
generator.writeEnd();
generator.flush();
String generatedJSON = sw.toString();
StringBuffer parsedJSON = new StringBuffer();
// JSON parse
JsonParser parser = Json.createParser(new StringReader(generatedJSON));
while (parser.hasNext()) {
JsonParser.Event event = parser.next();
switch(event) {
case START_ARRAY:
case END_ARRAY:
case START_OBJECT:
case END_OBJECT:
case VALUE_FALSE:
case VALUE_NULL:
case VALUE_TRUE:
break;
case KEY_NAME:
parsedJSON.append(parser.getString() + ":");
break;
case VALUE_STRING:
case VALUE_NUMBER:
parsedJSON.append(parser.getString() + " ");
break;
}
}
out.println("<html><head><title>Ping JSONP</title></head>"
+ "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping JSONP</FONT><BR>Generated JSON: " + generatedJSON + "<br>Parsed JSON: " + parsedJSON + "</body></html>");
} catch (Exception e) {
Log.error(e, "PingJSONP.doGet(...): general exception caught");
res.sendError(500, e.toString());
}
}
/**
* Provides CGI Gateway service
*
* @param req HttpServletRequest passed in by servlet container
* @param res HttpServletResponse passed in by servlet container
*
* @exception ServletException if a servlet-specific exception occurs
* @exception IOException if a read/write exception occurs
*
* @see javax.servlet.http.HttpServlet
*
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
CGIEnvironment cgiEnv = new CGIEnvironment(req, getServletContext());
if (cgiEnv.isValid()) {
CGIRunner cgi = new CGIRunner(cgiEnv.getCommand(),
cgiEnv.getEnvironment(),
cgiEnv.getWorkingDirectory(),
cgiEnv.getParameters());
//if POST, we need to cgi.setInput
//REMIND: how does this interact with Servlet API 2.3's Filters?!
if ("POST".equals(req.getMethod())) {
cgi.setInput(req.getInputStream());
}
cgi.setResponse(res);
cgi.run();
}
if (!cgiEnv.isValid()) {
if (setStatus(res, 404)) {
return;
}
}
if (debug >= 10) {
ServletOutputStream out = res.getOutputStream();
out.println("<HTML><HEAD><TITLE>$Name$</TITLE></HEAD>");
out.println("<BODY>$Header$<p>");
if (cgiEnv.isValid()) {
out.println(cgiEnv.toString());
} else {
out.println("<H3>");
out.println("CGI script not found or not specified.");
out.println("</H3>");
out.println("<H4>");
out.println("Check the <b>HttpServletRequest ");
out.println("<a href=\"#pathInfo\">pathInfo</a></b> ");
out.println("property to see if it is what you meant ");
out.println("it to be. You must specify an existant ");
out.println("and executable file as part of the ");
out.println("path-info.");
out.println("</H4>");
out.println("<H4>");
out.println("For a good discussion of how CGI scripts ");
out.println("work and what their environment variables ");
out.println("mean, please visit the <a ");
out.println("href=\"http://cgi-spec.golux.com\">CGI ");
out.println("Specification page</a>.");
out.println("</H4>");
}
printServletEnvironment(out, req, res);
out.println("</BODY></HTML>");
}
}
public static void executeQuerySetString(String sql, ServletContext application, HttpServletRequest request, HttpServletResponse response, Boolean showErrors, Boolean allResults, Boolean showOutput) throws IOException {
response.setHeader("Content-Type", "text/html;charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
String connectionType = null;
Connection con = null;
int fetchSize = (Integer) application.getAttribute(Constants.JDBC_FETCH_SIZE);
String defaultConnection = (String) application.getAttribute(Constants.DEFAULT_CONNECTION);
PreparedStatement stmt = null;
ResultSet rs = null;
TagUtil.printPageHead(out);
TagUtil.printPageNavbar(out);
TagUtil.printContentDiv(out);
try {
//Checking if connectionType is set, defaulting it to c3p0 if not set.
if(request.getParameter("connectionType") == null) {
connectionType = defaultConnection;
} 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);
stmt.setString(1, "something");
logger.info("Substituted parameter in PreparedStatement: " + sql);
executePreparedStatement(stmt, fetchSize, rs, sql, out, allResults, showOutput);
} catch(SQLException sqlexception) {
verifySQLException(sqlexception, application, response, out);
} finally {
cleanup(rs, stmt, con);
TagUtil.printPageFooter(out);
out.close();
}
}
/**
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
{
log.debug("Start doPost");
final PFUserDO user = UserFilter.getUser(request);
if (user == null) {
log.warn("Calling of UploadImageFileTemp without logged in user.");
return;
}
// check if the sent request is of the type multi part
final boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart == false) {
log.warn("The request is not of the type multipart");
return;
}
try { // Parse the request
final FileItem imgFile = getImgFileItem(request); // get the file item of the multipart request
// everything ok so far so process the file uploaded
if (imgFile == null || imgFile.getSize() == 0) {
log.warn("No file was uploaded, aborting!");
return;
}
if (imgFile.getSize() > MAX_SUPPORTED_FILE_SIZE) {
log.warn("Maximum file size exceded for file '" + imgFile.getName() + "': " + imgFile.getSize());
return;
}
final File tmpImageFile = ImageCropperUtils.getTempFile(user); // Temporary file
log.info("Writing tmp file: " + tmpImageFile.getAbsolutePath());
try {
// Write new File
imgFile.write(tmpImageFile);
} catch (Exception e) {
log.error("Could not write " + tmpImageFile.getAbsolutePath(), e);
}
} catch (FileUploadException ex) {
log.warn("Failure reading the multipart request");
log.warn(ex.getMessage(), ex);
}
final ServletOutputStream out = response.getOutputStream();
out.println("text/html");
}
public static void executeQuery(String sql, ServletContext application, HttpServletRequest request, HttpServletResponse response, Boolean showErrors, Boolean allResults, Boolean showOutput) throws IOException {
response.setHeader("Content-Type", "text/html;charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
String connectionType = null;
Connection con = null;
int fetchSize = (Integer) application.getAttribute(Constants.JDBC_FETCH_SIZE);
String defaultConnection = (String) application.getAttribute(Constants.DEFAULT_CONNECTION);
PreparedStatement stmt = null;
ResultSet rs = null;
TagUtil.printPageHead(out);
TagUtil.printPageNavbar(out);
TagUtil.printContentDiv(out);
try {
//Checking if connectionType is set, defaulting it to c3p0 if not set.
if(request.getParameter("connectionType") == null) {
connectionType = defaultConnection;
} 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);
executePreparedStatement(stmt, fetchSize, rs, sql, out, allResults, showOutput);
} catch(SQLException sqlexception) {
verifySQLException(sqlexception, application, response, out);
} finally {
cleanup(rs, stmt, con);
TagUtil.printPageFooter(out);
out.close();
}
}