- WindowUtilities.java Utility class that simplifies creating a window and setting the look and feel.
- ExitListener.java A WindowListener with support to close the window.
- JAppletExample.java A simple applet (JApplet) created in Swing. Illustrates setting the look and feel, adding components to the content pane, and changing the layout to FlowLayout (default is BorderLayout). See JAppletExample.html (requires the Java Plug-In or a Java 2 compliant browser, for example, Netscape 6.x).
- JFrameExample.java Demonstrates creating a simple Swing application using a JFrame. As with a JApplet, components must be added to the content pane, instead of the window directly.
- JLabels.java Illustrates creating labels in Swing. A nice feature of JLabels is that the label text can contain HTML markup. Uses image JHUAPL.gif
- JButtons.java Creates various buttons. In Swing, buttons can contain text only, an image only, or a combination of both an image and a label. Uses image cup.gif.
- JPanels.java A simple example that illustrates creating panels. In Swing, a JPanel can contain custom borders. Typically, utility methods in the BorderFactory class are used to create a border for the panel. Uses the following class:
o SixChoicePanel.java A JPanel that displays six radio buttons with labels. - JSliders.java Creates three common types of sliders: one without tick marks, one with tick marks, and one with both tick marks and labels.
- JColorChooserTest.java Demonstrates the use of a JColorChooser which presents a dialog with three different tabbed panes to allow the user to select a color preference. The dialog returns a Color object based on the user’s selection or null if the user entered Cancel.
- JInternalFrames.java Illustrates the ability to create a Multiple Document Interface (MDI) application by placing internal frames (JInternalFrame) in a desktop pane (JDesktopPane).
- JToolBarExample.java Small example showing the basic use of a JToolBar. Uses the following classes and images:
o ToolBarButton.java A simple button that contains an image and a label for use in a toolbar.
o BrowserToolBar.java A basic tool bar for holding multiple buttons.
o Images used in the toolbar buttons: Help.gif, Home.gif, Left.gif, Print.gif, Right.gif, RotCCUp.gif, TrafficRed.gif. - Browser.java Implementation of a simple browser in Swing. The user can specify a URL to load into the browser (JEditorPane). By attaching an HyperlinkListener, the editor pane is responsive to hyperlinks selected by the user. Uses the following class and image:
o JIconButton.java A simple button that the user can select to load the entered URL.
o home.gif Image used in the button. - JCheckBoxTest.java Simple example illustrating the use of check boxes.
- JRadioButtonTest.java Creates three radio buttons and illustrates handling ItemEvents in response to selecting a radio button.
- JOptionPaneExamples.java Creates various modal dialogs to show messages. Uses the follwoing classes:
o JLabeledTextField.java A simple JPanel that combines a JLabel and a JTextField.
o RadioButtonPanel.java Groups several radio buttons in a single row, with a label on the left.
o DisableListener.java A listener that toggles the enabled status of some other component.
Aug 25
Basic Swing Details
Aug 24
UrlRetriever.java Accepts an URL from the command line, parses the host, port, and URI components from the URL and then retrieves the document. Requires the following classes
UrlRetriever.java Accepts an URL from the command line, parses the host, port, and URI components from the URL and then retrieves the document. Requires the following classes: import java.util.*; /** This parses the input to get a host, port, and file, then * passes these three values to the UriRetriever class to * grab the URL from the Web. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class UrlRetriever { public static void main(String[] args) { checkUsage(args); StringTokenizer tok = new StringTokenizer(args[0]); String protocol = tok.nextToken(":"); checkProtocol(protocol); String host = tok.nextToken(":/"); String uri; int port = 80; try { uri = tok.nextToken(""); if (uri.charAt(0) == ':') { tok = new StringTokenizer(uri); port = Integer.parseInt(tok.nextToken(":/")); uri = tok.nextToken(""); } } catch(NoSuchElementException nsee) { uri = "/"; } UriRetriever uriClient = new UriRetriever(host, port, uri); uriClient.connect(); } /** Warn user if the URL was forgotten. */ private static void checkUsage(String[] args) { if (args.length != 1) { System.out.println("Usage: UrlRetriever "); System.exit(-1); } } /** Tell user that this can only handle HTTP. */ private static void checkProtocol(String protocol) { if (!protocol.equals("http")) { System.out.println("Don't understand protocol " + protocol); System.exit(-1); } } } UriRetriever.java Given a host, port, and URI, retrieves the document from the HTTP server. import java.net.*; import java.io.*; /** Retrieve a URL given the host, port, and file as three * separate command-line arguments. A later class * (UrlRetriever) supports a single URL instead. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class UriRetriever extends NetworkClient { private String uri; public static void main(String[] args) { UriRetriever uriClient = new UriRetriever(args[0], Integer.parseInt(args[1]), args[2]); uriClient.connect(); } public UriRetriever(String host, int port, String uri) { super(host, port); this.uri = uri; } /** Send one GET line, then read the results one line at a * time, printing each to standard output. */ // It is safe to use blocking IO (readLine), since // HTTP servers close connection when done, resulting // in a null value for readLine. protected void handleConnection(Socket uriSocket) throws IOException { PrintWriter out = SocketUtil.getWriter(uriSocket); BufferedReader in = SocketUtil.getReader(uriSocket); out.println("GET " + uri + " HTTP/1.0\r\n"); String line; while ((line = in.readLine()) != null) { System.out.println("> " + line); } } } NetworkClient.java import java.net.*; import java.io.*; /** A starting point for network clients. You'll need to * override handleConnection, but in many cases connect can * remain unchanged. It uses SocketUtil to simplify the * creation of the PrintWriter and BufferedReader. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class NetworkClient { protected String host; protected int port; /** Register host and port. The connection won't * actually be established until you call * connect. */ public NetworkClient(String host, int port) { this.host = host; this.port = port; } /** Establishes the connection, then passes the socket * to handleConnection. */ public void connect() { try { Socket client = new Socket(host, port); handleConnection(client); } catch(UnknownHostException uhe) { System.out.println("Unknown host: " + host); uhe.printStackTrace(); } catch(IOException ioe) { System.out.println("IOException: " + ioe); ioe.printStackTrace(); } } /** This is the method you will override when * making a network client for your task. * The default version sends a single line * ("Generic Network Client") to the server, * reads one line of response, prints it, then exits. */ protected void handleConnection(Socket client) throws IOException { PrintWriter out = SocketUtil.getWriter(client); BufferedReader in = SocketUtil.getReader(client); out.println("Generic Network Client"); System.out.println ("Generic Network Client:\n" + "Made connection to " + host + " and got '" + in.readLine() + "' in response"); client.close(); } /** The hostname of the server we're contacting. */ public String getHost() { return(host); } /** The port connection will be made on. */ public int getPort() { return(port); } } SocketUtil.java Provides utilities for wrapping a BufferedReader and PrintWriter around the Socket's input and output streams, respectively. import java.net.*; import java.io.*; /** A shorthand way to create BufferedReaders and * PrintWriters associated with a Socket. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class SocketUtil { /** Make a BufferedReader to get incoming data. */ public static BufferedReader getReader(Socket s) throws IOException { return(new BufferedReader( new InputStreamReader(s.getInputStream()))); } /** Make a PrintWriter to send outgoing data. * This PrintWriter will automatically flush stream * when println is called. */ public static PrintWriter getWriter(Socket s) throws IOException { // Second argument of true means autoflush. return(new PrintWriter(s.getOutputStream(), true)); } }
Aug 24
AddressVerifier.java Connects to an SMTP server and issues a expn request to display details about a mailbox on the server. Uses the following classes
import java.net.*; import java.io.*; /** Given an e-mail address of the form user@host, * connect to port 25 of the host and issue an * 'expn' request for the user. Print the results. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class AddressVerifier extends NetworkClient { private String username; public static void main(String[] args) { if (args.length != 1) { usage(); } MailAddress address = new MailAddress(args[0]); AddressVerifier verifier = new AddressVerifier(address.getUsername(), address.getHostname(), 25); verifier.connect(); } public AddressVerifier(String username, String hostname, int port) { super(hostname, port); this.username = username; } /** NetworkClient, the parent class, automatically establishes * the connection and then passes the Socket to * handleConnection. This method does all the real work * of talking to the mail server. */ // You can't use readLine, because it blocks. Blocking I/O // by readLine is only appropriate when you know how many // lines to read. Note that mail servers send a varying // number of lines when you first connect or send no line // closing the connection (as HTTP servers do), yielding // null for readLine. Also, we'll assume that 1000 bytes // is more than enough to handle any server welcome // message and the actual EXPN response. protected void handleConnection(Socket client) { try { PrintWriter out = SocketUtil.getWriter(client); InputStream in = client.getInputStream(); byte[] response = new byte[1000]; // Clear out mail server's welcome message. in.read(response); out.println("EXPN " + username); // Read the response to the EXPN command. int numBytes = in.read(response); // The 0 means to use normal ASCII encoding. System.out.write(response, 0, numBytes); out.println("QUIT"); client.close(); } catch(IOException ioe) { System.out.println("Couldn't make connection: " + ioe); } } /** If the wrong arguments, thn warn user. */ public static void usage() { System.out.println ("You must supply an email address " + "of the form 'username@hostname'."); System.exit(-1); } } MailAddress.java Separates the user and host components of an email address. import java.util.*; /** Takes a string of the form "user@host" and * separates it into the "user" and "host" parts. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class MailAddress { private String username, hostname; public MailAddress(String emailAddress) { StringTokenizer tokenizer = new StringTokenizer(emailAddress, "@"); this.username = getArg(tokenizer); this.hostname = getArg(tokenizer); } private static String getArg(StringTokenizer tok) { try { return(tok.nextToken()); } catch (NoSuchElementException nsee) { System.out.println("Illegal email address"); System.exit(-1); return(null); } } public String getUsername() { return(username); } public String getHostname() { return(hostname); } } NetworkClient.java Starting point for a network client to communicate with a remote computer. import java.net.*; import java.io.*; /** A starting point for network clients. You'll need to * override handleConnection, but in many cases connect can * remain unchanged. It uses SocketUtil to simplify the * creation of the PrintWriter and BufferedReader. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class NetworkClient { protected String host; protected int port; /** Register host and port. The connection won't * actually be established until you call * connect. */ public NetworkClient(String host, int port) { this.host = host; this.port = port; } /** Establishes the connection, then passes the socket * to handleConnection. */ public void connect() { try { Socket client = new Socket(host, port); handleConnection(client); } catch(UnknownHostException uhe) { System.out.println("Unknown host: " + host); uhe.printStackTrace(); } catch(IOException ioe) { System.out.println("IOException: " + ioe); ioe.printStackTrace(); } } /** This is the method you will override when * making a network client for your task. * The default version sends a single line * ("Generic Network Client") to the server, * reads one line of response, prints it, then exits. */ protected void handleConnection(Socket client) throws IOException { PrintWriter out = SocketUtil.getWriter(client); BufferedReader in = SocketUtil.getReader(client); out.println("Generic Network Client"); System.out.println ("Generic Network Client:\n" + "Made connection to " + host + " and got '" + in.readLine() + "' in response"); client.close(); } /** The hostname of the server we're contacting. */ public String getHost() { return(host); } /** The port connection will be made on. */ public int getPort() { return(port); } } SocketUtil.java Provides utilities for wrapping a BufferedReader and PrintWriter around the Socket's input and output streams, respectively. import java.net.*; import java.io.*; /** A shorthand way to create BufferedReaders and * PrintWriters associated with a Socket. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class SocketUtil { /** Make a BufferedReader to get incoming data. */ public static BufferedReader getReader(Socket s) throws IOException { return(new BufferedReader( new InputStreamReader(s.getInputStream()))); } /** Make a PrintWriter to send outgoing data. * This PrintWriter will automatically flush stream * when println is called. */ public static PrintWriter getWriter(Socket s) throws IOException { // Second argument of true means autoflush. return(new PrintWriter(s.getOutputStream(), true)); } }
Aug 23
Buggy Counter Applet.java Demonstrates that data shared by multiple threads is candidate for a potential race condition
import java.applet.Applet; import java.awt.*; /** Emulates the Counter and Counter2 classes, but this time * from an applet that invokes multiple versions of its own run * method. This version is likely to work correctly * except when an important customer is visiting. public class BuggyCounterApplet extends Applet implements Runnable{ private int totalNum = 0; private int loopLimit = 5; // Start method of applet, not the start method of the thread. // The applet start method is called by the browser after init is // called. public void start() { Thread t; for(int i=0; i<3; i++) { t = new Thread(this); t.start(); } } private void pause(double seconds) { try { Thread.sleep(Math.round(1000.0*seconds)); } catch(InterruptedException ie) {} } public void run() { int currentNum = totalNum; System.out.println("Setting currentNum to " + currentNum); totalNum = totalNum + 1; for(int i=0; i
Aug 23
SplitTest.java Illustrates parsing a string with a String.split
SplitTest.java Illustrates parsing a string with a String.split /** Prints the tokens resulting from treating the first * command-line argument as the string to be tokenized * and the second as the delimiter set. Uses * String.split instead of StringTokenizer. */ public class SplitTest { public static void main(String[] args) { if (args.length == 2) { String input = args[0], delimiters = args[1]; String[] tokens = args[0].split(delimiters); for(int i=0; i<tokens.length; i++)="" {="" string="" token="tokens[i];" if="" (token.length()="" !="0)" system.out.println(token);="" }="" else="" system.out.println="" ("usage:="" java="" splittest="" delimeters");="" <="" pre="">
Aug 22
TokTest.java Illustrates parsing a string with a StringTokenizer.
TokTest.java Illustrates parsing a string with a StringTokenizer. import java.util.StringTokenizer; /** Prints the tokens resulting from treating the first * command-line argument as the string to be tokenized * and the second as the delimiter set. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class TokTest { public static void main(String[] args) { if (args.length == 2) { String input = args[0], delimiters = args[1]; StringTokenizer tok = new StringTokenizer(input, delimiters); while (tok.hasMoreTokens()) { System.out.println(tok.nextToken()); } } else { System.out.println ("Usage: java TokTest string delimeters"); } } }
Aug 21
কীবোর্ড থেকে একটি কী হারিয়ে গেলে বা নষ্ট হয়ে গেলে কি করবেন?
আপনার ল্যাপটপের একটি বা একাধিক কী হারিয়ে গেছে বা নষ্ট হয়ে গেছে এবং আপনি জানেন না এখন কি করবেন? ভয় পাবার কিছু নেই, সম্ভবত আপনি কীবোর্ডটি ঠিক করতে পারবেন এবং নতুন একটি কীবোর্ড ক্রয় করার কোন প্রয়োজন হবে না। সকল কীবোর্ড এর জন্য অনন্য সমাধান নেই, কারণ সকল কীবোর্ড এক নয়। এখানে সাধারণ ক্ষেত্রে কি করতে হবে তা দেওয়া হলো।
অবস্থা ০১
কী কেপ (key cap) এবং কী ধারক (key retainer) খুলে গেছে এবং আপনি জানেন না কীভাবে আপনি এদেরকে সঠিক অবস্থানে ফেরত দেবেন।
সতর্কতার সাথে অন্য আরেককি কী এর কেপ খুলে ফেলুন যাতে retainer কীবোর্ড থেকে খুলে না যায়।
কী retainer টি ভাল করে দেখুন, এটি কীবোর্ড এর সাথে চারটি ভিন্ন বিন্দু দ্বারা যুক্ত আছে।
সংযোগ খুলে যাওয়া retainer টি একইভাবে সেট করে কীবোর্ড এ স্থাপন করুন।
কী কেপটি retainer এর উপর বসান এবং হালকা চাপ দিয়ে বসিয়ে দিন।
অবস্থা ০২
কীবোর্ড থেকে কী খুলে গেলে এবং আপনি তা হারিয়ে ফেলেছেন। এক্ষেত্রে আপনি একটি একক কী ইন্টারনেট থেকে ক্রয় করতে পারেন। নতুন একটি পাবার পরে, উপরোক্ত পদ্ধতিতে এটিকে সস্থানে স্থাপন করুন।
স্পেসবার কী স্থাপন করা
স্পেসবার কী এর সাথে একটি ধাতুর তৈরি ধারক সংযুক্ত থাকে (কিছু কীবোর্ড মডেল এর ক্ষেত্রে)। ধারকটিকে ফ্লাট (সমতল) মাথা বিশিষ্ট স্ক্রুড্রাইভার দিয়ে কীবোর্ড থেকে খুলে ফেলুন।
ছবিতে দেখানো পদ্ধতিতে ধারকটিকে স্থাপন করুন। আপনার ছোট আংটার সাহায্যে ধারকটিকে কীবোর্ড এর সাথে স্থাপন করতে হতে পারে।
স্পেসবার কীটিকে সস্থানে নিয়ে যান এবং যতক্ষন পর্যন্ত না ঠিকভাবে লেগে যায় ততক্ষন আঙ্গুল দিয়ে হালকাভাবে চাপ দিন।
ভেঙ্গে যাওয়া কীবোর্ড কী এর জন্য এখনে আরেকটি কৌশল দেখানো হলো
নিচের চিত্রটিতে আপনি দেখতে পারছেন যে আপনার U কী টি নেই। কী কেপ, ধারক এমনটি সিলিকন ঝিল্লিও নেই। এখানে দেখানো হলো কীভাবে নতুন কী ক্রয় না করেও কিভাবে এটিকে সাময়িকভাবে ঠিক করবেন।
আমি নিজে U কী ছাড়া কীবোর্ড ব্যবহার করতে পারবো না, কিন্তু ডান অল্ট কী বা রাইট ক্লিক কী ছাড়াও চলতে পারবো। নিচের গাইড এ আমি দেখাবো কিভাবে আমি ব্যবহার করি না এমন একটি কী খুলে ফেলে U কী এর স্থলে স্থাপন করবো।
সতর্কতার সাথে আঙ্গুলের সাহায্যে কী কেপ টি খুলে ফেলুন।
ধারকটি খুলে ফেলুন। ধারকটি দুটি অংশ দ্বারা একে অপরের সাথে যুক্ত থাকে। যদি একটি অংশ অপর অংশে থেকে খুলে যায় তাহলে এদেরকে পুনরায় সংযুক্ত করুন।
সিলিকন ঝিল্লিটি আঠা দিয়ে কীবোর্ড এর সাথে লাগানো থাকে। খুবই সতর্কতার সাথে একটি ধারালো ছুরি দিয়ে ধীরে ধীরে ঝিল্লিটিকে কীবোর্ড থেকে আলগা করুন।
সিলিকন ঝিল্লিটি আলগা হয়ে যাবে।
এখন ঝিল্লিটির নিচের প্রান্তে যতটুকু প্রয়োজন ঠিক ততটুকু সুপারগ্লু লাগান।
সতর্কতার সাথে ঝিল্লিটিকে U এর কেন্দ্রে স্থাপন করুন। গ্লু শুকানো পর্যন্ত অপেক্ষা করুন।
ধারকটিকে স্থাপন করুন।
কী কেপটিকে ধারকের উপরে স্থাপন করুন। হালকাভাবে চাপ দিয়ে ধারকের সাথে স্থাপন করুন।
এখন আপনি U কী আবার ব্যবহার করতে পারবেন।
কেন কী সংযুক্ত করা যায় না।
কী টিকে উল্টো করুন এবং ক্লিপটিকে ভালভাবে দেখুন। সম্ভাবনা আছে, এটির একটি ক্লিপ নষ্ট হয়ে যাবার কারণে ধারকের সাথে এটি আটকাচ্ছে না। যদি এটি কারণ হয়ে থাকে তাহলে আপনাকে নতুন একটি কী ক্রয় করতে হবে।
পরবর্তী ছবিতে আপনি দেখেতে পাচ্ছেন যে, একটি ক্লিপ নেই, এটি ভেঙ্গে গেছে। এই কী টি ধারক এর সাথে সংযুক্ত করা যাবে না। যদি এটি কারণ হয়ে থাকে তাহলে আপনাকে নতুন একটি কী ক্রয় করতে হবে।
সম্ভবত, আপনার কী টি ভাল আছে, কিন্তু ধারকটি ভেঙ্গে গেছে। পরবর্তী ছবিতে আপনি দেখতে পাচ্ছেন যে, ধারক এর সাথে টিপটি নেই। বাম টিপ টি আছে কিন্তু ডান টিপ টি নেই। যদি এটি কারণ হয়ে থাকে তাহলে আপনাকে নতুন একটি কী ক্রয় করতে হবে।
এখানে আরো একটি ছবি আছে। এই ছবিতে ধারকটির দুটি অংশ একে অপরের সাথে সংযুক্ত করা যাচ্ছে না। এটির কারণ হচ্ছে এদের একটি ভেঙ্গে গেছে।বাম টিপ টি আছে কিন্তু ডান টিপ টি নেই। যদি এটি কারণ হয়ে থাকে তাহলে আপনাকে নতুন একটি কী ক্রয় করতে হবে।
Aug 21
NetworkClientTest.java Makes a simple connection to the host and port specified on the command line. Uses the following classes
NetworkClientTest.java Makes a simple connection to the host and port specified on the command line. Uses the following classes: /** Make simple connection to host and port specified. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class NetworkClientTest { public static void main(String[] args) { String host = "localhost"; int port = 8088; if (args.length > 0) { host = args[0]; } if (args.length > 1) { port = Integer.parseInt(args[1]); } NetworkClient nwClient = new NetworkClient(host, port); nwClient.connect(); } } NetworkClient.java Starting point for a network client to communicate with a remote computer. import java.net.*; import java.io.*; /** A starting point for network clients. You'll need to * override handleConnection, but in many cases connect can * remain unchanged. It uses SocketUtil to simplify the * creation of the PrintWriter and BufferedReader. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class NetworkClient { protected String host; protected int port; /** Register host and port. The connection won't * actually be established until you call * connect. */ public NetworkClient(String host, int port) { this.host = host; this.port = port; } /** Establishes the connection, then passes the socket * to handleConnection. */ public void connect() { try { Socket client = new Socket(host, port); handleConnection(client); } catch(UnknownHostException uhe) { System.out.println("Unknown host: " + host); uhe.printStackTrace(); } catch(IOException ioe) { System.out.println("IOException: " + ioe); ioe.printStackTrace(); } } /** This is the method you will override when * making a network client for your task. * The default version sends a single line * ("Generic Network Client") to the server, * reads one line of response, prints it, then exits. */ protected void handleConnection(Socket client) throws IOException { PrintWriter out = SocketUtil.getWriter(client); BufferedReader in = SocketUtil.getReader(client); out.println("Generic Network Client"); System.out.println ("Generic Network Client:\n" + "Made connection to " + host + " and got '" + in.readLine() + "' in response"); client.close(); } /** The hostname of the server we're contacting. */ public String getHost() { return(host); } /** The port connection will be made on. */ public int getPort() { return(port); } } SocketUtil.java Provides utilities for wrapping a BufferedReader around the Socket's input stream and a PrintWriter around the Socket's output stream import java.net.*; import java.io.*; /** A shorthand way to create BufferedReaders and * PrintWriters associated with a Socket. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class SocketUtil { /** Make a BufferedReader to get incoming data. */ public static BufferedReader getReader(Socket s) throws IOException { return(new BufferedReader( new InputStreamReader(s.getInputStream()))); } /** Make a PrintWriter to send outgoing data. * This PrintWriter will automatically flush stream * when println is called. */ public static PrintWriter getWriter(Socket s) throws IOException { // Second argument of true means autoflush. return(new PrintWriter(s.getOutputStream(), true)); } }
Aug 21
ShowSession.java Servlet that uses session tracking to determine if the client is a repeat visitor. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output.
ShowSession.java Servlet that uses session tracking to determine if the client is a repeat visitor. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output. package cwp; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import java.util.*; /** Simple example of session tracking. *
* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); String title = “Session Tracking Example”; HttpSession session = request.getSession(true); String heading; Integer accessCount = (Integer)session.getAttribute(“accessCount”); if (accessCount == null) { accessCount = new Integer(0); heading = “Welcome, Newcomer”; } else { heading = “Welcome Back”; accessCount = new Integer(accessCount.intValue() + 1); } // Use setAttribute instead of putValue in version 2.2. session.setAttribute(“accessCount”, accessCount); out.println(ServletUtilities.headWithTitle(title) + “\n” + ”
” + heading + “
\n" + "
Information on Your Session:
\n" + "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + "
Info Type | Value\n” + “ |
---|---|
ID\n” + “ | ” + session.getId() + “\n” + “ |
Creation Time\n” + “ | ” + new Date(session.getCreationTime()) + “\n” + “ |
Time of Last Access\n” + “ | ” + new Date(session.getLastAccessedTime()) + “\n” + “ |
Number of Previous Accesses\n” + “ | ” + accessCount + “\n” + “ |
\n" + ""); } /** Handle GET and POST requests identically. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Aug 20
LongLivedCookie.java Subclass of Cookie that automatically sets the max age to one year.
LongLivedCookie.java Subclass of Cookie that automatically sets the max age to one year. package cwp; import javax.servlet.http.*; /** Cookie that persists 1 year. Default Cookie doesn't * persist past current session. * * Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class LongLivedCookie extends Cookie { public static final int SECONDS_PER_YEAR = 60*60*24*365; public LongLivedCookie(String name, String value) { super(name, value); setMaxAge(SECONDS_PER_YEAR); } }