| Home: www.vipan.com | Vipan Singla | e-mail: vipan@vipan.com |
|
GET /cgi-bin/runApp.pl?name=your+name&phone=1234567890 HTTP/1.0 Accept:*/* Connection: Keep-Alive Host: www.w3.org User-Agent: GenericThere is always a blank line at the end of "headers" information to tell the main web server that headers are finished. There is no request "body" to a GET request. Any query string will be attached to the url in the first line after appending a "?" after the url.
POST /cgi-bin/runApp.pl HTTP/1.0 Accept:*/* Connection: Keep-Alive Host: www.w3.org User-Agent: Generic name=your+name&phone=1234567890The part "name=..." is the request "body" e.g. from a form submission. ("Content-length:" header is not required to be present in "requests".
HTTP/1.1 200 OK
Date: Wed, 19 May 1999 18:20:56 GMT
Server: Apache/1.3.6
Last-Modified: Mon, 17 May 1999 15:46:21 GMT
ETag: "2da0dc-2870-374039cd"
Accept-Ranges:bytes
Content-Length: 10352
Connection: Keep-Alive
Keep-Alive: timeout=15
Content-Type: text/html; charset=iso-8859-1
<HTML><HEAD><TITLE>...</TITLE></HEAD>
<BODY>. . .</BODY>
</HTML>
Normally, you will only need to set the "content-type:" in your application's output. The main web server will automatically put in the other headers.
| CGI Environment Variable | Comments | Servlet Method |
|---|---|---|
| SERVER_NAME =www.yahoo.com | req.getServerName() | |
| SERVER_PORT =80 | request.getServerPort() | |
| REQUEST_METHOD =GET (or POST) | someReq.getMethod() | |
| SCRIPT_NAME =/servlet/myServlet | This includes either the servlet name or a path to the servlet, but does not include any extra path information (PATH_INFO) or a query string. | requ.getServletPath() |
| PATH_INFO =(none) | Servlets or scripts can be accessed by their virtual pathname such as /servlet, followed by extra information at the end of this path such as /myServlet. | req.getPathInfo() |
| PATH_TRANSLATED =(none) | "PATH-INFO" translated to actual computer path such as /home/you/myServlet. | req.getPathTranslated() |
| QUERY_STRING =name=value&name2=value2 | Anything after the first "?" in the request URI in "raw" as-sent format with no decoding. | req.getQueryString() |
| CONTENT_TYPE= | Only set if POST request. Specifies the type of data contained in the body of the request, if any. e.g. text/html. | req.getContentType() |
| CONTENT_LENGTH= | Only set it is a POST request. Specifies the total number of bytes contained in the body of the request. | req.getContentLength() |
/servlet after the computer name and port; then connect to a specific port number, say, 8080 and pass the "request body" to that port number (not the headers). The CGI environment variables are always available to any program who cares to retrieve them.
|
Enumeration keys = req.getParameterNames(); while (keys.hasMoreElements() ) { String key = (String)keys.nextElement(); //To retrieve a single value String value = req.getParameter(key); // If the same key has multiple values (check boxes) String[] valueArray = req.getParameterValues(); }Note: If the parameter data was sent in the request body, for example in a POST request, then don't use getInputStream() or getReader() described below. Instead use the getParameter...() methods.
//Also makes a new session if none exists HttpSession session = req.getSession(true);
String urlUptoQuestionMark = request.getRequestURI();
First line of HTTP request Returned Value -------------------------- -------------- POST /some/path.html HTTP/1.1 /some/path.html GET http://foo.bar/a.html HTTP/1.0 http://foo.bar/a.html HEAD /xyz?a=b HTTP/1.1 /xyzBUT PREFERRABLY, here is how you should reconstruct the URL the client used to make the request.
StringBuffer buff = HttpUtils.getRequestURL(req);
The returned URL string contains a protocol, server name, port number, and server path, but it does not include query string parameters. String myAppIsHere = request.getContextPath();e.g. "/HotelReservationSystem/mainServlet" has a context path of "/HotelReservationSystem". Empty string is returned for servlets placed in the default servlet directory.
ServletContext sct = getServletContext(); //No "request." in front!
URL gotten = getServletContext().getResource("/whatever/else")
String file = getServletContext().getRealPath("path string");
String serverInfo = getServletContext().getServerInfo();
Enumeration enum
= getServletContext().getInitParameterNames();
String initString = getServletContext().getInitParameter("parameter name");
//If the data is coming from a POST request int nBytes = request.getContentLength(); Hashtable keyValues = HttpUtils.parsePostData(nBytes, sis); //To parse and decode "raw" query string data as name-value pairs String query = req.getQueryString(); Hashtable keyValues = HttpUtils.parseQueryString(query );
public class SomeServlet extends HttpServlet { . . }
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{ . . . }
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{ . . . }
Enumeration keys= req.getParameterNames();
while (keys.hasMoreElements())
{
String key = (String)keys.nextElement();
String value = req.getParameter(key);
}
res.setContentType("text/html");
PrintWriter output = res.getWriter();
output.println(" . . ."); output.flush(); //Sometimes needed if buffering output output.close(); //Repeat calling doesn't hurt!
StringBuffer text = new StringBuffer(1024); text.append("some text . . . "); text.append("more text . . . "); //Finally send the output to the server output.println(text.toString() );
ServletOutputStream output = resp."getOutPutStream()"; output.print( . . . ) ;
res.setHeader("Pragma", "no-cache"); //HTTP/1.0 Proxy Servers
res.setHeader("Cache-Control", "no-cache"); //HTTP/1.1 Proxy Servers
res.setDateHeader("Expires", 0); // for Browsers
You may want to do this if your server data changes frequently.By default, the first time a user calls a servlet, the servlet container (java server) will automatically include a non-persistent cookie in its response which will tie the user to a single session in the java server. This cookie does not get stored in the cookie file on a user's computer. When the user closes his/her browser, that cookie gets destroyed. As long as the user has the same browser open (even if opening multiple windows), the browser will include that cookie (and other cookies) with every request to the main web server automatically. If the java server gets that request, it searches for and reads that cookie's value to get the session id. If the session id matches any session id stored in the memory of the java server, the java server will assign this request as belonging to that previously-opened session.
A session gets closed if:
invalidate() method to immediately close the active session.
If the user's browser is set to not accept cookies, the java server will automatically start appending session ID information to each link or anchor url contained in the servlet's response. So, you always have session tracking by default unless you take steps to disable it.
isNew(), getID(), getCreationTime(), getLastAccessedTime(), getMaxInactiveInterval(), setMaxInactiveInterval(), invalidate()
getRequestedSessionId(), isRequestedSessionIdValid(), isRequestedSessionIdFromCookie(), and isRequestedSessionIdFromURL().
Cookie takeThat
= new Cookie("name-this", "value is 4000 characters max");
takeThat.setMaxAge(2*60*60*24); //Persist for 2 days
response.addCookie(takeThat);
Cookie[] allCookiesSent = request.getCookies();
request.getAttributeNames(), request.getAttribute(), request.setAttribute(), request.removeAttribute() methods to store and retrieve this information.
getAttributeNames(), getAttribute("SomeName"), setAttribute("SomeName",someObject), removeAttribute("SomeName")
Integer someInteger = new Integer(1523);
session.setAttribute("trout",someInteger);
HttpSession session2 = request.getSession(true);
Integer someInt2 = (Integer)session2.getAttribute("trout");
int converted = someInt2.intValue();
ServletContext cntxt = getServletContext();
cntxt.getAttributeNames(), cntxt.getAttribute("SomeName"), cntxt.setAttribute("SomeName",someObject), cntxt.removeAttribute("SomeName").
getServletContext().setAttribute("Hitcount", countIntegerObject);
//Later (after, say, 49 days)
Integer hits
= (Integer)getServletContext().getAttribute("Hitcount");
Just configure the Java server so that, in the servlet's init parameters area, there is a name=value pair such as "pullFile=myInit.propy". Code your servlet's to call getInitParameter("pullFile") method, get the name of the file to read, and read in that file.
<%-- (Hidden comment here) --%>
out stream.
<%@ page
contentType="text/html;charset=ISO-8859-1"
import="com.abc.project1.*, java.util.*"
errorPage="oops/unhandled.jsp"
isErrorPage="false"
info="Later, call getServletInfo() method to return this text"
%>
<%@ page
contentType="text/html;charset=ISO-8859-1"
import="java.util.*"
isErrorPage="true"
info="This is the error page servlet"
%>
. . .
<b>The Exception = </b> <%= exception.toString() %>
Custom Exception Message - <%= exception.getMessage() %>
. . .
<%@ include file="some.html" %> - To include a file verbatim THE FIRST TIME a JSP file is called
<%!
String var1 = "My String";
int count = 0;
public void increaseCount()
{
count++;
. . .
}
void jspInit() { . . . }
void jspDestroy() { . . . }
%>
<%
String tempvar = request.getParameter("htmlFormNameAttribute");
out.println(tempvar); //This "out" is different from "System.out"
%>
<% for(int i=0;i<10;i++) { %>
<BR> Counter value is <%= i %>
Current price is <%= request.getParameter("item") + " = " + var1 %>
<% } %>
NO SEMI-COLON must be there at the end of your %= statement!<jsp:useBean ... /> (/>means no end tag required just as in XML.)package com.abc.project1; import . . .; //public class public class AnyThing { //Declare variables here String var1; //public constructor with no arguments public AnyThing() { . . . } //public setter methods which accept String arguments public void setThis(String whatever){var1 = whatever; . . . } //public getter methods which return String objects public String getThis(){ . . . return var1;} }
<jsp:useBean id="anyName" scope="application"
class="com.abc.project1.AnyThing" />
The current price is <%= anyName.getThis() %>
The new price is <%= anyName.setThis("23.00") %>
Here, "anyName" translates to:com.abc.project1.AnyThing anyName = new com.abc.project1.AnyThing();"<%-- Alternative syntax --%> The current price is <jsp:getProperty name="anyName" property="this" /> <jsp:setProperty name="anyName" property="this" value="23.00" /> The new price is <jsp:getProperty name="anyName" property="this" />
Note the case-change (Specifying "this" calls corresponding "getThis()" or "setThis( . . . )" ). Writing property="This" will not work!
<jsp:useBean
beanName="diskFileName"
scope="application"
type="com.abc.project1.AnyThing"
/>
<jsp:setProperty name="anyName" property="*" />
<jsp:setProperty name="anyName" property="user" param="username" />
Cannot use both "param" and "value" in a setProperty tag!
<jsp:forward page="path/another.jsp" />
<jsp:include page="path/another.jsp" flush="true" />
<jsp:param name="user" value="username" />
String mimeType = request.getContentType();
If it is text, it should be treated as a character stream. All other content types (or some time even text content type) should be read in as binary input.
int nBytes = request.getContentLength();
BufferedReader buff = request.getReader();
//Can call either getInputStream() or getReader(), not both ServletInputStream sis = request.getInputStream(); //Read the "binary" data line-by-line (upto each "newline" character) int readIn = sis.readLine( . . . ); //Returns number of bytes read //Or, Convert bytes into characters, useful if "text" data coming in InputStreamReader isrdr = new InputStreamReader(sis); BufferedReader buff = new BufferedReader(isrdr);It is generally used in servlet chaining where one servlet's response becomes another servlet's input.
public class SomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
//"path-to-access-2nd-servlet" can specify a .jsp file
RequestDispatcher rd
= getServletContext().getRequestDispatcher("pathToNextServlet");
//Do not open a writer stream
//Forward control to another file, never to return.
rd.forward(req, res);
//Or pass the request, include response here and get control back
//Can open writer stream and write before calling "include()"
rd.include(req, res);
}
}
InputStream in = req.getInputStream();
InputStreamReader rdr = new InputStreamReader(in);
BufferedReader buff = new BufferedReader(rdr);
//Read in the previous servlet's output as one line
String whatever = buff.readLine();
//Close the reader
buff.close();
res.setContentType("servlet-specific-mime-type");
//res.setContentType("text/plain"); //e.g. set to text/html
The "servlet container" will recognize that mime-type when it gets the mime-type as the first line of the response. It will then pass the response to the specified handling servlet.<FORM METHOD="post", ACTION="/servlet/whatever"> . . . </FORM>
public void actionPerformed(ActionEvent ae)
{
String fieldInput = someFormField.getText();
String encodedInput = URLEncoder.encode("myFieldName") + "=" +
URLEncoder.encode(fieldInput);
try {
//Establish a connection to the servlet
URL url = new URL("http:// . . . /servlet/someServlet");
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);
//Set content type as "application/x-www-form-urlencoded"
uc.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
//Send url-encoded data over as binary to servlet
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
dos.writeBytes(encodedInput);
dos.flush();
dos.close();
//Read in the servlet's response (here we expect it to be text)
InputStreamReader in = new InputStreamReader(uc.getInputStream());
String incoming = "";
// Read incoming character-by-character
int chr = in.read();
while (chr != -1) {
incoming += String.valueOf((char)chr );
chr = in.read(); //Read next character
}
in.close();
}
catch(MalformedURLException e) {}
catch(IOException e) {}
}
public class SomeCalledServlet extends HttpServlet
{
//Need to use doGet(), not doPost()
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
String requested = req.getParameter("myFieldName");
. . .
}
}
Normally, you will save user data as a "text" file (character data). If you have gone to the trouble of creating a complicated hashtable and populated it with user or application data, you might as well "serialize" it to a disk (or an object database). Presently, a Java object can be serialized as a binary file. In future, Java may allow serialization in XML format.
Use these procedures if you want to store a hashtable, request object, a session object or any "serializable" object to disk for later retrieval.
Use "FileOutputStream" and "FileInputStream". The stored binaries can only be read back in as Java types. You must know the order in which you stored the various types to be able to retrieve them correctly later.
Use a BufferedInputStream to buffer disk accesses (more efficient).
Java does not serialize "static" and "transient" fields.
//Storing objects and primitive types (serializing) FileOutputStream ostream = new FileOutputStream("persistent.store"); //Optionally, buffer data before writing to disk //BufferedOutputStream bos = new BufferedOutputStream(ostream); //ObjectOutputStream p = new ObjectOutputStream(bos); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeInt(12345); p.writeObject("Today"); p.writeObject(new Date()); p.flush(); ostream.close(); //Retrieving objects and primitive types (deserializing) //You must know the order and type of stored objects //for this to be of any use! FileInputStream istream = new FileInputStream("persistent.store"); //Optionally, buffer data while reading from disk //BufferedInputStream bis = new BufferedInputStream(ostream); //ObjectInputStream p = new ObjectInputStream(bis); ObjectInputStream p = new ObjectInputStream(istream); //Loads the correct class from current classpath to instantiate the object int i = p.readInt(); String today = (String)p.readObject(); Date date = (Date)p.readObject(); istream.close();
If all you want to do is save STRING "keys" with the associated STRING "values", use a properties file. It is a text file written in a special format by you or Java.
# AN EXAMPLE PROPERTIES FILE # First non-whitespace character as # or ! indicates a comment #Blank lines are ignored #All these lines put "Truth" key with "Beauty" value #in the "Properties" object (a hashtable) Truth = Beauty Truth:Beauty Truth :Beauty #com.abc.project1.whatever=whateverElse #Anything = really #Use \t,\n,\r,\\,\",\',\ (backslash and a space) #for special characters #In a key, put \= and \: to include a "=" and ":" I\tam\nof\ the\ opinion = Who\ \"cares\" # "\" at end of line means continue on to next line. e.g. # Key "fruits", # value "apple, banana, pear, cantaloupe, watermelon,kiwi, mango" fruits = apple, banana, pear, \ cantaloupe, watermelon, \ kiwi, mango # If there is no value, value is empty (zero length) string. e.g. # Key is "cheeses", value is "" cheeses # END OF EXAMPLE PROPERTIES FILE
For example, to read the information from the disk file in the main servlet's "init()" method:
public void init() throws ServletException
{
String propsFile = getInitParameter("pullFile");
//Check for zero-length strings too!
if (propsFile == null || propsFile.length() == 0)
{
throw new UnavailableException(this,
"Properties filename not set in servlet init parameters");
}
Properties props = new Properties();
try
{
//propsFile is string such as "C:\\whatevr.ext" (a text file)
InputStream incoming = new FileInputStream(propsFile);
props.load(incoming);
incoming.close();
}
catch (Exception e)
{
throw new UnavailableException(this,
"Can't read the properties file " + propsFile);
}
Enumeration propKeys = props.keys();
while (propKeys.hasMoreElements())
{
String key = (String) propKeys.nextElement();
// System.out.println(key + " = " + props.getProperty(key) );
//Finally store in servlet context
getServletContext().setAttribute(key, props.getProperty(key));
}
}
//Create an empty properties object (it must only store Strings!) Properties p = new Properties(); //MOST COMMON USAGE //Or, pass another properties object //(if property is not found in this object, //recursively looks in the embedded properties object) //Properties p2 = new Properties(fallBackProp); //Less common //Do not store any other object except Strings as key and value p.setProperty("myKey is this ", "And my value is this"); //Get a property as String (recursive search all embedded props), //null return if not found String value = p.getProperty("myKey is this "); //Value is the second argument string //if key is not found in any prop. object String value = p.getProperty("myKey is this ", "Not found, using this text as default"); //Get all key names available, //(even gets recursively embedded properties object's keys) Enumeration enum = p.propertyNames(); //Loop through all the keys to get values while (enum.hasMoreElements() ) { String nextKey = (String)enum.nextElement(); String value = p.getProperty(nextKey); System.out.println(nextKey + " = " + nextValue ); }
//Save the properties object to disk
FileOutputStream fos = new FileOutputStream("myProps.ext");
try {
//Does not close the output stream
p.store(fos, "MY PROPERTIES FILE FOR THIS PROJECT");
fos.close();
}catch (Exception e) { }
Almost always use a "BufferedWriter" to write in chunks (more efficient) instead of one character at a time to disk.
Use a "FileWriter" to write your own simple text to a "File" object which can be as simple as "C:\\whatever". A "FileWriter" is a subclass of a generic "OutputStreamWriter" which converts characters to system-dependent bytes just before writing. You will normally not need to use it directly.
//Get a text file writer (Can also pass a "File" object)
FileWriter fw = new FileWriter("myOutput.txt");
//For efficiency, first buffer output in "BufferedWriter"
BufferedWriter bw = new BufferedWriter(fw);
//Start writing any text you want
bw.write("This is " + 29 + " of May\n");
bw.close();
Use a "PrintWriter" to write anything (Java object or primitive type) as text (uses the thing's "toString()" method). The written text can't be read back in and converted to the original object type. For that, use binary ObjectOutputStream/ObjectInputStream. Of course, it can also write your own simple text too! Servlets use it a lot.
//To write a Java object or a primitive type to a "text" file
//Can also pass a "File" object
FileWriter fw = new FileWriter("myOutput.txt");
//For efficiency, first buffer output in "BufferedWriter"
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(pw);
//Shorthand form of above
//PrintWriter pw
// = new PrintWriter(
// new BufferedWriter(new FileWriter("myOutPut.txt")));
pw.println(yourJavaObject); //or pass a primitive Java type
//Write to an "OutputStream" instead of a text "Writer"
//write to terminal screen
//PrintWriter pw = new PrintWriter(System.out);
pw.println("kuwdghikchg");
//Can also write a String object
pw.write("This is " + 29 + " of May\n");
pw.close();
You can also display your text output on-screen before writing to a text file (for debugging). This same OutputStream acn also "stream" character data to remote applications such as an applet.
//Display output on system screen where program is running OutputStreamWriter osr = new OutputStreamWriter(System.out); Writer out = new BufferedWriter(new OutputStreamWriter(System.out)); //String encoding = osr.getEncoding(); //Just to check osr.write("3"); osr.write("\n"); osr.close(); //Instead of all of the above, you could just use: System.out.println("3");
Use a "BufferedReader" to read in chunks (more efficient) instead of one character at a time from disk.
Use a "FileReader" to read a text file from disk. Either pass the path as string ("C:\\whatever") or a "File" object. Note that it will read, but not deserialize a Java object written by "PrintWriter". To do that, see store and retrieve Java objects from a disk file
A "FileReader" is a subclass of "InputStreamReader" which converts system-dependent bytes to java characters after reading from disk. You will normally not need to use it directly.
//Read from a text file. Any file extension will work FileReader fr = new FileReader("someFile.txt"); //String encoding = fr.getEncoding(); //Not important //Reads one character at time (inefficient) //int i = fr.read(); //Read one "line" at a time until "newline" character which is read in too BufferedReader br = new BufferedReader(fr); String s = br.readLine(); //Tell the operating system that you are done with the disk file fr.close();
//Get keyboard input
InputStreamReader isr = new InputStreamReader(System.in);
//Generally, put in a while loop or use StreamTokenizer
//Reads "one" character, returns -1 if end of stream
int keyRead = isr.read();
isr.close();
Use a "StreamTokenizer" to parse characters as they are coming in through a reader. Typically, call nextToken() in a loop and parse successive tokens until TT_EOF is returned.
//Read words, quoted strings or numbers from keyboard //StreamTokenizer tzer // = new StreamTokenizer( new InputStreamReader(System.in) ); //Parse words, quoted strings or numbers from a text file StreamTokenizer tzer = new StreamTokenizer( new FileReader("someFile.txt") ); //int = one of "static" StreamTokenizer.TT_WORD/TT_NUMBER/TT_EOL/TT_EOF //or int = a single character or a quote character int typeRead = tzer.nextToken(); //Actually put this in a loop if (typeRead == StreamTokenizer.TT_NUMBER) { double numberRead = tzer.nval; } //Actually, also check for quote mark types read if (typeRead == StreamTokenizer.TT_WORD || ) { String wordRead = tzer.sval; } //No close() method
File setIt = new File("C:\\anyDir");
String dir = setIt.getPath();
File[] contents = dir.listFiles();
for (int i=0; i<=contents.length; i++)
{
String filename = contents[i].getName();
long size = contents[i].length();
boolean ren = contents[i].renameTo(new File("C:\\junk\\file"+i) );
boolean mds = contents[i].mkdirs();
boolean del = contents[i].delete();
boolean new = contents[i].createNewFile();
boolean ex = contents[i].exists();
URL fileUrl = contents[i].toURL(); // Converts to a file: URL
}
public synchronized void
doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
Enumeration e = req.getParameterNames();
Hashtable parms = new Hashtable(20);
String parmName;
String parmValue;
while (e.hasMoreElements() )
{
parmName = (String)e.nextElement();
parmValue = req.getParameter(parmName);
parms.put(parmName, parmValue);
}
. . .
}
public synchronized void
doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
Enumeration e = req.getParameterNames();
Hashtable parms = new Hashtable(20);
String parmName;
String parmValue;
while (e.hasMoreElements() )
{
parmName = (String)e.nextElement();
parmValue = req.getParameter(parmName);
parms.put(parmName, parmValue);
}
. . .
}
public String doThis(HashTable hash)". Then, through polymorphism, when the servlet actually calls that method, the extended class's method gets called.
Class t = Class.forName("com.abc.project1.Grapes");
//How-to instantiate a class, given its name as a string
//Your form has a hidden field with name="ClassName" and value="WorkHorse"
//Make sure "WorkHorse" extends "MotherClass"
//and customize "doThis()" method to WorkHorse's work
MotherClass mother;
try {
//Loads the WorkHorse class, if not loaded already
Class c = Class.forName(req.getParameter("ClassName") );
//Creates a new instance of the WorkHorse class
//You know that each child class extends MotherClass, so cast it to that
mother = (MotherClass)c.newInstance();
//Put this new object in the "session" so that any servlet can access it.
session.putValue("Mommy", mother);
} catch(ClassNotFoundException cnfe) { System.out.println(cnfe.toString());
} catch(InstantiationException ie) { . . .
} catch(IllegalAccessException iae) { . . .
}
public String doThis(HashTable hash)"). Then, upon further requests from the same user, you can retrieve the instantiated object from the session and call that known "doThis()" method on it.
//Returns an "Object", cast it to your type
MotherClass whatever = (MotherClass)session.getAttribute("Mommy");
URL url = new URL("http:// . . . /servlet/someServlet");
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
dos.writeBytes(encodedInput);
dos.flush();
dos.close();
OutputStream binout = response.getOutputStream(); // To write binary data binout.print( . . . ); //Then write binary data to binout
getClass() in a running program to find dynamically which exact class it belongs to. It is useful in applets, servlets or other dynamic content generation. some-name.getClass.getName() loops back to the name of the variable. Other useful methods of any object are getSuperclass(), getPackage(), getInterfaces().
Pull an image or other binary data from an internet path: (UNTESTED CODE)
//In a non-web Java Application
//InputStream binaryIn = getClass().getResourceAsStream("file-path-string");
//In a Web Java Application
//If the resource name starts with "/", it is unchanged; otherwise,
//the package name is prepended to the resource name after converting
//"." inpackage name to "/". (Different from the "getResource()" method
//which returns a URL.)
InputStream binaryIn
= getServletContext().getResourceAsStream("file-path-string");
//Buffer incoming stream for efficient reading
BufferedInputStream bis = new BufferedInputStream(binaryIn);
//Get a DataInputStream to read binary data
DataInputStream dis = new DataInputStream(dis);
//Store incoming bytes in a linked list as we don't know how many are coming
LinkedList byteList = new LinkedList();
try {
while(){
byte b = dis.readByte();
bytes.add(b);
}
} catch (EOFException){}
//Typecast returned object array to argument type
byte[] temp = new byte[100];
byte[] imgIn = byteList.toArray(temp);
//e.g., byte array is actually a .gif or a .jpg image
ImageIcon img = new ImageIcon(imgIn);
res.setHeader("Pragma", "no-cache"); //HTTP/1.0, for Proxy Servers
res.setHeader("Cache-Control", "no-cache"); //HTTP/1.1, for Proxy Servers
res.setDateHeader("Expires", 0); // for Browsers
//Create an image on a component (some-component.createImage()) int w = anyComponent.getSize().width; //Component width int h = anyComponent.getSize().height; //Component height //Buffer the whole image in memory BufferedImage bi = (BufferedImage)anyComponent.createImage(w, h);
Graphics2D g2 = bi.createGraphics(); //Now go crazy drawing in buffered image "bi" using graphics object "g2" //Your drawing will get stored in memory g2.draw( . . .); //Make up your image by hand g2.drawString( . . .); //Convert vector text to pixels g2.drawImage( . . .); //Get your image from some place else //If extending applet, use paint() public void paint(Graphics g) //If extending JApplet or any other "swing" component, use paintComponent() //public void paintComponent(Graphics g) { // Graphics2D g3 = (Graphics2D)g; //Just copies buffered image "bi" from memory to screen //when Java needs repainting //Actually a straight Graphics method (not Graphics2D) g.drawImage(bi, 0, 0, this); }
If you extend Swing components which have UI delegates (such as a JPanel), you should typically invoke "super.paintComponent()" within your paintComponent() method. The UI delegate will then clear the background before redrawing, so you won't have to.
| Technology | Speed (megabits/second) |
|---|---|
| ADSL | 1.5 to 6.1 (Asymmetric means megabits to user, only kilobits from user. So, don’t install a web server on your ADSL link!) |
| T1 | 1.544 |
| DS-3 | 45 |
| OC-3 | 155 |
| OC-12 | 622 |
| OC-24 | 1244 |
| Satellite (i.e. DirectPC) | Very asymmetric, telephone company return |
| Ethernet | EVERY Ethernet card has a unique ID number. So, wireless phones use this to access internet. |