Java/Servlets/Basics
Содержание
Bean Parser Servlet
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class BeanParserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
//set the MIME type of the response, "text/html"
response.setContentType("text/html");
//use a PrintWriter send text data to the client who has requested the servlet
java.io.PrintWriter out = response.getWriter();
//Begin assembling the HTML content
out.println("<html><head>");
out.println("<title>Stock Price Fetcher</title></head><body>");
out.println("<h2>Please submit a valid stock symbol</h2>");
//make sure method="post" so that the servlet service method
//calls doPost in the response to this form submit
out.println(
"<form method=\"post\" action =\"" + request.getContextPath() +
"/stockbean\" >");
out.println("<table border=\"0\"><tr><td valign=\"top\">");
out.println("Stock symbol: </td> <td valign=\"top\">");
out.println("<input type=\"text\" name=\"symbol\" size=\"10\">");
out.println("</td></tr><tr><td valign=\"top\">");
out.println("<input type=\"submit\" value=\"Submit Info\"></td></tr>");
out.println("</table></form>");
out.println("</body></html>");
} //end doGet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,java.io.IOException{
String symbol;//this will hold the stock symbol
float price = 0f;
symbol = request.getParameter("symbol");
boolean isValid = (symbol == null || symbol.length() < 1) ? false : true;
//set the MIME type of the response, "text/html"
response.setContentType("text/html");
//use a PrintWriter send text data to the client who has requested the servlet
java.io.PrintWriter out = response.getWriter();
//Begin assembling the HTML content
out.println("<html><head>");
out.println("<title>Latest stock value</title></head><body>");
if (! isValid){
out.println("<h2>Sorry, the stock symbol parameter was either empty or null</h2>");
} else {
out.println("<h2>Here is the latest value of "+ symbol +"</h2>");
StockPriceBean spbean = new StockPriceBean();
spbean.setSymbol(symbol);
price = spbean.getLatestPrice();
out.println( (price == 0 ? "The symbol is probably invalid." : ""+price) );
}
out.println("</body></html>");
out.close();
}// doPost
}//HttpServlet
Compression Response Stream servlets
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
* Implementation of <b>ServletOutputStream</b> that works with
* the CompressionServletResponseWrapper implementation.
*
* @author Amy Roh
* @author Dmitri Valdin
* @version $Revision: 1.3 $, $Date: 2004/03/18 16:40:33 $
*/
public class CompressionResponseStream
extends ServletOutputStream {
/**
* Construct a servlet output stream associated with the specified Response.
*
* @param response The associated response
*/
public CompressionResponseStream(HttpServletResponse response) throws IOException{
super();
closed = false;
this.response = response;
this.output = response.getOutputStream();
}
/**
* The threshold number which decides to compress or not.
* Users can configure in web.xml to set it to fit their needs.
*/
protected int compressionThreshold = 0;
/**
* Debug level
*/
private int debug = 0;
/**
* The buffer through which all of our output bytes are passed.
*/
protected byte[] buffer = null;
/**
* The number of data bytes currently in the buffer.
*/
protected int bufferCount = 0;
/**
* The underlying gzip output stream to which we should write data.
*/
protected GZIPOutputStream gzipstream = null;
/**
* Has this stream been closed?
*/
protected boolean closed = false;
/**
* The content length past which we will not write, or -1 if there is
* no defined content length.
*/
protected int length = -1;
/**
* The response with which this servlet output stream is associated.
*/
protected HttpServletResponse response = null;
/**
* The underlying servket output stream to which we should write data.
*/
protected ServletOutputStream output = null;
/**
* Set debug level
*/
public void setDebugLevel(int debug) {
this.debug = debug;
}
/**
* Set the compressionThreshold number and create buffer for this size
*/
protected void setBuffer(int threshold) {
compressionThreshold = threshold;
buffer = new byte[compressionThreshold];
if (debug > 1) {
System.out.println("buffer is set to "+compressionThreshold);
}
}
/**
* Close this output stream, causing any buffered data to be flushed and
* any further output data to throw an IOException.
*/
public void close() throws IOException {
if (debug > 1) {
System.out.println("close() @ CompressionResponseStream");
}
if (closed)
throw new IOException("This output stream has already been closed");
if (gzipstream != null) {
flushToGZip();
gzipstream.close();
gzipstream = null;
} else {
if (bufferCount > 0) {
if (debug > 2) {
System.out.print("output.write(");
System.out.write(buffer, 0, bufferCount);
System.out.println(")");
}
output.write(buffer, 0, bufferCount);
bufferCount = 0;
}
}
output.close();
closed = true;
}
/**
* Flush any buffered data for this output stream, which also causes the
* response to be committed.
*/
public void flush() throws IOException {
if (debug > 1) {
System.out.println("flush() @ CompressionResponseStream");
}
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
if (gzipstream != null) {
gzipstream.flush();
}
}
public void flushToGZip() throws IOException {
if (debug > 1) {
System.out.println("flushToGZip() @ CompressionResponseStream");
}
if (bufferCount > 0) {
if (debug > 1) {
System.out.println("flushing out to GZipStream, bufferCount = " + bufferCount);
}
writeToGZip(buffer, 0, bufferCount);
bufferCount = 0;
}
}
/**
* Write the specified byte to our output stream.
*
* @param b The byte to be written
*
* @exception IOException if an input/output error occurs
*/
public void write(int b) throws IOException {
if (debug > 1) {
System.out.println("write "+b+" in CompressionResponseStream ");
}
if (closed)
throw new IOException("Cannot write to a closed output stream");
if (bufferCount >= buffer.length) {
flushToGZip();
}
buffer[bufferCount++] = (byte) b;
}
/**
* Write <code>b.length</code> bytes from the specified byte array
* to our output stream.
*
* @param b The byte array to be written
*
* @exception IOException if an input/output error occurs
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/**
* Write <code>len</code> bytes from the specified byte array, starting
* at the specified offset, to our output stream.
*
* @param b The byte array containing the bytes to be written
* @param off Zero-relative starting offset of the bytes to be written
* @param len The number of bytes to be written
*
* @exception IOException if an input/output error occurs
*/
public void write(byte b[], int off, int len) throws IOException {
if (debug > 1) {
System.out.println("write, bufferCount = " + bufferCount + " len = " + len + " off = " + off);
}
if (debug > 2) {
System.out.print("write(");
System.out.write(b, off, len);
System.out.println(")");
}
if (closed)
throw new IOException("Cannot write to a closed output stream");
if (len == 0)
return;
// Can we write into buffer ?
if (len <= (buffer.length - bufferCount)) {
System.arraycopy(b, off, buffer, bufferCount, len);
bufferCount += len;
return;
}
// There is not enough space in buffer. Flush it ...
flushToGZip();
// ... and try again. Note, that bufferCount = 0 here !
if (len <= (buffer.length - bufferCount)) {
System.arraycopy(b, off, buffer, bufferCount, len);
bufferCount += len;
return;
}
// write direct to gzip
writeToGZip(b, off, len);
}
public void writeToGZip(byte b[], int off, int len) throws IOException {
if (debug > 1) {
System.out.println("writeToGZip, len = " + len);
}
if (debug > 2) {
System.out.print("writeToGZip(");
System.out.write(b, off, len);
System.out.println(")");
}
if (gzipstream == null) {
if (debug > 1) {
System.out.println("new GZIPOutputStream");
}
response.addHeader("Content-Encoding", "gzip");
gzipstream = new GZIPOutputStream(output);
}
gzipstream.write(b, off, len);
}
// -------------------------------------------------------- Package Methods
/**
* Has this response stream been closed?
*/
public boolean closed() {
return (this.closed);
}
}
Compression Servlet Response Wrapper
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* Implementation of <b>HttpServletResponseWrapper</b> that works with
* the CompressionServletResponseStream implementation..
*
* @author Amy Roh
* @author Dmitri Valdin
* @version $Revision: 1.3 $, $Date: 2004/03/18 16:40:33 $
*/
public class CompressionServletResponseWrapper extends HttpServletResponseWrapper {
// ----------------------------------------------------- Constructor
/**
* Calls the parent constructor which creates a ServletResponse adaptor
* wrapping the given response object.
*/
public CompressionServletResponseWrapper(HttpServletResponse response) {
super(response);
origResponse = response;
if (debug > 1) {
System.out.println("CompressionServletResponseWrapper constructor gets called");
}
}
// ----------------------------------------------------- Instance Variables
/**
* Original response
*/
protected HttpServletResponse origResponse = null;
/**
* Descriptive information about this Response implementation.
*/
protected static final String info = "CompressionServletResponseWrapper";
/**
* The ServletOutputStream that has been returned by
* <code>getOutputStream()</code>, if any.
*/
protected ServletOutputStream stream = null;
/**
* The PrintWriter that has been returned by
* <code>getWriter()</code>, if any.
*/
protected PrintWriter writer = null;
/**
* The threshold number to compress
*/
protected int threshold = 0;
/**
* Debug level
*/
private int debug = 0;
/**
* Content type
*/
protected String contentType = null;
// --------------------------------------------------------- Public Methods
/**
* Set content type
*/
public void setContentType(String contentType) {
if (debug > 1) {
System.out.println("setContentType to "+contentType);
}
this.contentType = contentType;
origResponse.setContentType(contentType);
}
/**
* Set threshold number
*/
public void setCompressionThreshold(int threshold) {
if (debug > 1) {
System.out.println("setCompressionThreshold to " + threshold);
}
this.threshold = threshold;
}
/**
* Set debug level
*/
public void setDebugLevel(int debug) {
this.debug = debug;
}
/**
* Create and return a ServletOutputStream to write the content
* associated with this Response.
*
* @exception IOException if an input/output error occurs
*/
public ServletOutputStream createOutputStream() throws IOException {
if (debug > 1) {
System.out.println("createOutputStream gets called");
}
CompressionResponseStream stream = new CompressionResponseStream(origResponse);
stream.setDebugLevel(debug);
stream.setBuffer(threshold);
return stream;
}
/**
* Finish a response.
*/
public void finishResponse() {
try {
if (writer != null) {
writer.close();
} else {
if (stream != null)
stream.close();
}
} catch (IOException e) {
}
}
// ------------------------------------------------ ServletResponse Methods
/**
* Flush the buffer and commit this response.
*
* @exception IOException if an input/output error occurs
*/
public void flushBuffer() throws IOException {
if (debug > 1) {
System.out.println("flush buffer @ CompressionServletResponseWrapper");
}
((CompressionResponseStream)stream).flush();
}
/**
* Return the servlet output stream associated with this Response.
*
* @exception IllegalStateException if <code>getWriter</code> has
* already been called for this response
* @exception IOException if an input/output error occurs
*/
public ServletOutputStream getOutputStream() throws IOException {
if (writer != null)
throw new IllegalStateException("getWriter() has already been called for this response");
if (stream == null)
stream = createOutputStream();
if (debug > 1) {
System.out.println("stream is set to "+stream+" in getOutputStream");
}
return (stream);
}
/**
* Return the writer associated with this Response.
*
* @exception IllegalStateException if <code>getOutputStream</code> has
* already been called for this response
* @exception IOException if an input/output error occurs
*/
public PrintWriter getWriter() throws IOException {
if (writer != null)
return (writer);
if (stream != null)
throw new IllegalStateException("getOutputStream() has already been called for this response");
stream = createOutputStream();
if (debug > 1) {
System.out.println("stream is set to "+stream+" in getWriter");
}
//String charset = getCharsetFromContentType(contentType);
String charEnc = origResponse.getCharacterEncoding();
if (debug > 1) {
System.out.println("character encoding is " + charEnc);
}
// HttpServletResponse.getCharacterEncoding() shouldn"t return null
// according the spec, so feel free to remove that "if"
if (charEnc != null) {
writer = new PrintWriter(new OutputStreamWriter(stream, charEnc));
} else {
writer = new PrintWriter(stream);
}
return (writer);
}
public void setContentLength(int length) {
}
/**
* Returns character from content type. This method was taken from tomcat.
* @author rajo
*/
private static String getCharsetFromContentType(String type) {
if (type == null) {
return null;
}
int semi = type.indexOf(";");
if (semi == -1) {
return null;
}
String afterSemi = type.substring(semi + 1);
int charsetLocation = afterSemi.indexOf("charset=");
if(charsetLocation == -1) {
return null;
} else {
String afterCharset = afterSemi.substring(charsetLocation + 8);
String encoding = afterCharset.trim();
return encoding;
}
}
}
/// the visibility of variables declared at class level and within methods.
class HW {
int j; // j is visible to both method1 and method 2
void method1() {
double x; // x is visible only to method1
}
void method2() {
double y; // y is visible only to method2
}
}
Post Handler
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
public class PostHandler extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
/* Use the ServletRequest.getParameter(String name), getParameterMap(), getParameterNames(), or getParameterValues() methods in the servlet"s doPost method*/
String name = request.getParameter("username");
String depart = request.getParameter("department");
String email = request.getParameter("email");
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Welcome</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Your Identity</h1>");
out.println("Your name is: " + ( (name == null || name.equals("")) ? "Unknown" : name));
out.println("<br><br>");
out.println("Your department is: " + ( (depart == null || depart.equals("")) ? "Unknown" : depart));
out.println("<br><br>");
out.println("Your email address is: " + ( (email == null || email.equals("")) ? "Unknown" : email));
out.println("<h2>Using ServletRequest.getParameterMap</h2>");
Map param_map = request.getParameterMap();
if (param_map == null)
throw new ServletException(
"getParameterMap returned null in: " + getClass().getName());
//iterate through the java.util.Map and display posted parameter values
//the keys of the Map.Entry objects ae type String; the values are type String[],
//or String array
Iterator iterator = param_map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry me = (Map.Entry)iterator.next();
out.println(me.getKey() + ": ");
String[] arr = (String[]) me.getValue();
for(int i=0;i<arr.length;i++){
out.println(arr[i]);
//print commas after multiple values,
//except for the last one
if (i > 0 && i != arr.length-1)
out.println(", ");}//end for
out.println("<br><br>");
}//end while
out.println("</body>");
out.println("</html>");
out.close();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
doPost(request,response);
}
}
Query Modifier
import javax.servlet.*;
import javax.servlet.http.*;
public class QueryModifier extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String requestUrl = request.getRequestURL().toString();
String querystr = request.getQueryString();
if (querystr != null) {
querystr = querystr
+ "&inspector-name=Jen&inspector-email=Jenniferq@yahoo.ru";
} else {
querystr = "inspector-name=Jen&inspector-email=Jenniferq@yahoo.ru";
}
RequestDispatcher dispatcher = request
.getRequestDispatcher("/viewPost.jsp?" + querystr);
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
doGet(request, response);
}
}
Servlet parameter
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowFile extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletOutputStream out = response.getOutputStream();
String fileName = request.getParameter("file");
out.println("<html>");
out.println("<head>");
out.println("<title>Welcome</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>The File</h2>");
out.println(fileName);
out.println("</body>");
out.println("</html>");
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}