Friday, January 31, 2014

Install Tomcat on Mac OS X

Install Tomcat on Mac OS X

The most simple way is:

  1. Download Tomcat .zip file from internet, unzip it and then rename it to "Tomcat".
  2. Copy "Tomcat" folder to /Library or other folder.
  3. run terminal, execute the following commands:
    cd /Library/Tomcat/bin
    chmod +x startup.sh

    chmod +x shutdown.sh
    chmod +x catalina.sh
    chmod +x setclasspath.sh
    chmod +x bootstrap.jar
    chmod +x tomcat-jni.jar
  4. Run Tomcat by enter the below command:
    ./startup.sh


Other way from internet is as below:

(Original link: https://code.google.com/p/gbif-providertoolkit/wiki/TomcatInstallationMacOSX)

Table of Contents

  • Install Tomcat on Mac OS X
  • Table of Contents
    • Prerequisites
    • Steps
      • 1) Download Tomcat 6.x
      • 2) Install Tomcat 6.x
      • 3) Edit the Tomcat Configuration
      • 4) Run Tomcat
      • 5) Test Tomcat
      • 6) Shut down Tomcat
      • 7) Running Tomcat as a service daemon
      • 8) References
This tutorial explains how to install the Apache Tomcat 6.0.x on Mac OS X 10.5 or 10.6. This document is not tested to work with other versions of Tomcat or Java. For complete details, please consult the specific documentation for those software installations.
This tutorial is for now 'partially' tested with Tomcat 7.

Prerequisites

Following are the conditions assumed to be true in order to follow this tutorial.
1) The client version of OS X 10.5.8 Leopard or OS X 10.6 Snow Leopard. If you're running Server version of Mac OS X 10.5 or 10.6, Tomcat is pre-installed.
2) The latest security upgrades.
3) JAVA 5 or JAVA 6 Framework installed.
4) Logged in as an administrator.

Steps

1) Download Tomcat 6.x

Download the latest stable Tomcat 6 Binary Distribution Core (tar.gz) release from http://tomcat.apache.org/download-60.cgi. This should put a file of the form apache-tomcat-6.x.x.tar.gz (or apache-tomcat-6.x.x.tar if you download with Safari) into your Downloads folder.

2) Install Tomcat 6.x

Open the Terminal application to get a command prompt. The commands that follow assume that the Bourne Again SHell (bash) is in use. You can find out which shell you are using by typing the following and then hitting the ENTER key in the Terminal's command prompt:
echo $SHELL
All versions of OS X later than 10.3 use bash as the default shell. If the result echo command does not end in "/bash", you can change the default shell by using the System Preferences Accounts pane. If the pane is locked, unlock it. Control Click on your account name and a contextual menu will appear. Click on Advanced Options. You will then be presented with a dialog where you can change the default login shell to whatever you want. Select "bin/bash".
Change into the Library directory:
cd /Library
Create the Tomcat directory:
mkdir Tomcat
Set the owner of the Tomcat directory, where username should be the login name under which Tomcat will run:
chown username Tomcat
Set the group for the Tomcat directory to admin:
chgrp admin Tomcat
Change into the newly created Tomcat directory:
cd Tomcat
If the downloaded file was not already unzipped, unpack and unzip it into the Tomcat directory:
tar -xvzf ~/Downloads/apache-tomcat-6.x.x.tar.gz
Otherwise unpack the tar file:
tar -xvf ~/Downloads/apache-tomcat-6.0.x.tar
Create a Home symbolic link that points to the Tomcat directory:
ln -sfhv apache-tomcat-6.x.x Home

3) Edit the Tomcat Configuration

You will need to add a name and password to the tomcat-users.xml configuration file to access the Tomcat management and administration programs. Execute the following commands in Terminal:
Change into the Tomcat configuration directory:
cd Home/conf
Edit the tomcat-users.xml file. This example shows the command to edit using nano:
nano tomcat-users.xml
In the file, add the two lines below into the file above the line that says </tomcat-users> and outside of any comments (delimited with <!-- and-->). Substitute the name you want as the admin's username for "admin" and enter a password for that user to log in to the Tomcat Manager in place of "password".
<role rolename="manager"/>
<user username="admin" password="password" roles="standard,manager,admin"/>
If you're setting up Tomcat 7, the role is defined differently:
<user username="admin" password="password" roles="manager-gui"/>
In Tomcat 7, role names are automatically created.
Save the tomcat-users.xml file and exit from the editor.

4) Run Tomcat

Execute the following commands in Terminal: Change into the directory where Tomcat startup scripts are located
cd ../bin
Remove all of the scripts ending with .bat.
rm *.bat
Execute the Tomcat startup script:
./startup.sh
Check the Tomcat error log for errors:
less ../logs/catalina.out
If there are no error messages in the log files, then the installation has been completed successfully and Tomcat is running. There should be an informational message similar to the following near the end of the log file:
INFO: Server startup in 2412 ms
Under some circumstances the startup scripts do not execute because the execute permission has not been set. If this is the case you can change the execute permission to the scripts by typing the following:
cd ../bin
chmod 750 *.sh
This signifies read, write, and execute permissions for the owner, read and execute permissions for the group, and no permissions for others.

5) Test Tomcat

If Tomcat is running successfully following step 4, above, you should be able to see the Tomcat Welcome page at the following URL:

6) Shut down Tomcat

To shut down Tomcat type the following from the ./bin directory where Tomcat was installed (/Library/Tomcat/Home following the steps on this page):
./shutdown.sh

7) Running Tomcat as a service daemon

Mac OS X introduced launchd as the system-wide service management framework when Mac OS X 10.4 Tiger was released. Since then lanuchd succeeded traditional cron job management as the preferred way of daemonise system services on Mac OS X.
With the previous setup, to start up Tomcat while booting:
1. Create a script as [Tomcat home]/bin/tomcat-launchd.sh to start Tomcat as a non-daemonised process:
#!/bin/sh
#
# Wrapper for running Tomcat under launchd
# Required because launchd needs a non-daemonizing process
function shutdown()
{
        $CATALINA_HOME/bin/shutdown.sh
        /bin/rm $CATALINA_PID}
function wait_for_death()
{
        while /bin/kill -0 $1 2> /dev/null ; do
                sleep 2 
        done
}
export CATALINA_PID=$CATALINA_HOME/logs/tomcat.pid
$CATALINA_HOME/bin/startup.sh
trap shutdown QUIT ABRT KILL ALRM TERM TSTP
sleep 2
wait_for_death `cat $CATALINA_PID`
2. Create a launchd plist at /Library/LaunchDaemons/org.apache.tomcat.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>org.apache.tomcat</string>
        <key>Disabled</key>
        <false/>
        <key>OnDemand</key>
        <false/>
        <key>RunAtLoad</key>
        <true/>
        <key>ProgramArguments</key>
        <array>
                <string>/Library/Tomcat/bin/tomcat-launchd.sh</string>
        </array>
        <key>EnvironmentVariables</key>
        <dict>
                <key>CATALINA_HOME</key>
                <string>/Library/Tomcat</string>
                <key>JAVA_OPTS</key>
                <string>-Djava.awt.headless=true</string>
        </dict>
        <key>StandardErrorPath</key>
        <string>/Library/Tomcat/logs/tomcat-launchd.stderr</string>
        <key>StandardOutPath</key>
        <string>/Library/Tomcat/logs/tomcat-launchd.stdout</string>
        <key>UserName</key>
        <string>_appserver</string>
</dict>
</plist>
3. Load the launchd process by
$ sudo launchctl load /Library/LaunchDaemons/org.apache.tomcat.plist
You can replace the load subcommand as unloadstopstart to remove Tomcat from startup processes, stop or start it, respectively.
Please also note that, the sample launchd plist assume the service will run as the user _appserver, which is predefined on Mac OS X for running app services. So you'll have to make sure the Tomcat directories and IPT data directories are owned, writable and executable by_appserver. Or, please refer to this page.

8) References

For more thorough descriptions of Tomcat configuration on Mac OS X, also consult these sources:


Configuring an Oracle Datasource in Apache Tomcat

Configuring an Oracle Datasource in Apache Tomcat


Connect to a network Oracle 11g Application Express

You can connect to a network Oracle 11g Application Express via ip address + port + apex.  For example: enter http://192.168.0.245:8080/apex to connect to network Oracle Application Express. See below picture:



Thursday, January 23, 2014

You cannot access a shared folder that is located on a Windows 2000 or Windows 98-based computer from a Windows 7-based computer

You cannot access a shared folder that is located on a Windows 2000 or Windows 98-based computer from a Windows 7-based computer

Below link shows you how to solve this problem:
http://www.tannerwilliamson.com/2009/09/14/windows-7-seven-network-file-sharing-fix-samba-smb/

Please see the below screen shot:







There is another solution from Microsoft website:



Tuesday, January 14, 2014

Java Tutorials Code Sample – PrintUIWindow

Java Tutorials Code Sample – PrintUIWindow

Below sample can send the current UI as printing graphic to printer.
Printing 12 lines in the window

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.print.*;

public class PrintUIWindow implements Printable, ActionListener {

    JFrame frameToPrint;

    public int print(Graphics g, PageFormat pf, int page) throws
                                                        PrinterException {

        if (page > 0) { /* We have only one page, and 'page' is zero-based */
            return NO_SUCH_PAGE;
        }

        /* User (0,0) is typically outside the imageable area, so we must
         * translate by the X and Y values in the PageFormat to avoid clipping
         */
        Graphics2D g2d = (Graphics2D)g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());

        /* Now print the window and its visible contents */
        frameToPrint.printAll(g);

        /* tell the caller that this page is part of the printed document */
        return PAGE_EXISTS;
    }

    public void actionPerformed(ActionEvent e) {
         PrinterJob job = PrinterJob.getPrinterJob();
         job.setPrintable(this);
         boolean ok = job.printDialog();
         if (ok) {
             try {
                  job.print();
             } catch (PrinterException ex) {
              /* The job did not successfully complete */
             }
         }
    }

    public PrintUIWindow(JFrame f) {
        frameToPrint = f;
    }

    public static void main(String args[]) {
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        JFrame f = new JFrame("Print UI Example");
        f.addWindowListener(new WindowAdapter() {
           public void windowClosing(WindowEvent e) {System.exit(0);}
        });
        JTextArea text = new JTextArea(50, 20);
        for (int i=1;i<=50;i++) {
            text.append("Line " + i + "\n");
        }
        JScrollPane pane = new JScrollPane(text);
        pane.setPreferredSize(new Dimension(250,200));
        f.add("Center", pane);
        JButton printButton = new JButton("Print This Window");
        printButton.addActionListener(new PrintUIWindow(f));
        f.add("South", printButton);
        f.pack();
        f.setVisible(true);
    }
}

Original link: http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/2d/printing/examples/PrintUIWindow.java

Monday, January 13, 2014

Html in java


import javax.swing.*;

import java.io.*;

public class ExpToHTML {

private JTable _table;
private File _file;
private StringBuilder _html;

public ExpToHTML(JTable table, File file){
_table = table;
_file = file;
int rowcount = table.getRowCount();
int colcount = table.getColumnCount();

try{
BufferedWriter bw = new BufferedWriter(new FileWriter(_file));

_html.append("<tr>");
for(int i=0;i<colcount;i++){
_html.append("<th>")
    .append(_table.getColumnName(i))
    .append("</th>");
}
_html.append("</tr>\n");

for(int i=0;i<rowcount;i++){
_html.append("<tr>");
for(int k=0;k<colcount;k++){
_html.append("<td>")
    .append(GetData(_table, i, k))
    .append("</td>");
}
_html.append("</tr>\n");
}

bw.write(_html.toString());
bw.close();
}catch(Exception e){}
}

public String GetData(JTable table, int row_index, int col_index){
return table.getModel().getValueAt(row_index, col_index).toString();
}
}

Read txt file and then put it into html file

Read txt file and then put it into html file

import java.awt.Desktop;
import java.io.*;

public class ShowGeneratedHtml {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(
            new FileReader("D:\\New folder\\11.txt"));

        File f = new File("d:\\temp\\source.htm");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("<html>");
        bw.write("<body>");
        bw.write("<h1>ShowGeneratedHtml source</h1>");
        bw.write("<textarea cols=75 rows=20>");

        String line;
        while ((line=br.readLine())!=null) {
            bw.write(line);
            bw.newLine();
        }

        bw.write("</text" + "area>");
        bw.write("</body>");
        bw.write("</html>");

        br.close();
        bw.close();

        Desktop.getDesktop().browse(f.toURI());
    }
}

How to set windows look and feel in Java

1. Use the below code to set Windows look and feel in Java:
  try {
  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          } catch (Exception er) { }

2. Use the below code to set look and feel back to default:
  try {
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
  } catch (Exception er) { }

Sunday, January 12, 2014

Export JTable data to PDF file in Java using iText


Below example shows how to export JTable data to PDF file in Java using iText:


import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFTest{
  JTable table;
  JButton button;
  public static void main(String[] args) {
  new PDFTest();
 }
 
 public PDFTest(){
  JFrame frame = new JFrame("Getting Cell Values in JTable");
  JPanel panel = new JPanel();
  String data[][] = {{"Angelina","Mumbai"},{"Martina","Delhi"}};
  
  String col[] = {"Name","Address"};
  DefaultTableModel model = new DefaultTableModel(data, col);
  table = new JTable(model);
  JScrollPane pane = new JScrollPane(table);
  button=new JButton("Save to pdf");
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent ae){
       try{
   int count=table.getRowCount();
   Document document=new Document();
          PdfWriter.getInstance(document,new FileOutputStream("d:/data.pdf"));
          document.open();
          PdfPTable tab=new PdfPTable(2);
          tab.addCell("Name");
          tab.addCell("Address");
   for(int i=0;i<count;i++){
   Object obj1 = GetData(table, i, 0);
   Object obj2 = GetData(table, i, 1);
   String value1=obj1.toString();
   String value2=obj2.toString();
   
   tab.addCell(value1);
   tab.addCell(value2);
   }
   document.add(tab);
   document.close();
       }
       catch(Exception e){}
   }
  });
  panel.add(pane);
  panel.add(button);
  frame.add(panel);
  frame.setSize(500,500);
  frame.setUndecorated(true);
  frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
  frame.setVisible(true);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
  
  public Object GetData(JTable table, int row_index, int col_index){
  return table.getModel().getValueAt(row_index, col_index);
 }
}




Read .sql file and replace key in Java


1. Create "Search.sql" file in Java project. Input the below query and then save file.

select s.shipper_number as "SSCC number", 
       it.item_code as "Item code",
       CAST(ia.parameter as INTEGER)/1000 as "Weight (Kg)",
       i.create_time as "Date & time", 
       r.adjust_reason as "Operation", 
       (u.u_first_name||' '||u.u_last_name) as "User name", 
       u.u_username as "Employee Number",
       z.zone_name as "Zone name"
from shippers s, inventory_log i, reason_codes r, users u, locations l, zones z, items it, inventory_attrib ia
where s.shipper_id = i.shipper_id 
      and i.reason_code = r.reason_id 
      and i.user_id = u.u_id 
      and i.location_id = l.location_id
      and l.zone_id = z.zone_id
      and i.item_id = it.item_id
      and i.stock_id = ia.stock_id
      and ia.attribute = 'Weight'
      and s.shipper_number = '@ssccnumber'
order by i.create_time 
2.  Create search() method in Java program.

public void search(){
  String query = null, line = null;
  StringBuilder sb = new StringBuilder();
  
  try{
   FileReader fr = new FileReader(new File("search.sql"));
   BufferedReader bf = new BufferedReader(fr);
   while((line=bf.readLine())!=null){
    sb.append(line);
    sb.append("\n");
   }
  }catch(IOException e){
   e.printStackTrace();
  }
  //_sscreen.getSSCC() is text of JTextField.
  query = sb.toString().replace("@ssccnumber", _sscreen.getSSCC());
  _db.conToRDS();
  _db.setQuery(query);
 }
If you have more than one key word, you can use String.replace(oldChar, newChar).replace(oldChar2, newChar2);




FileReader and BufferedReader

A FileReader class is a general tool to read in characters from a File. The BufferedReader class can wrap around Readers, like FileReader, to buffer the input and improve efficiency. So you wouldn't use one over the other, but both at the same time by passing the FileReader object to the BufferedReader constructor.
Very Detail
FileReader is used for input of character data from a disk file. The input file can be an ordinary ASCII, one byte per character text file. A Reader stream automatically translates the characters from the disk file format into the internal char format. The characters in the input file might be from other alphabets supported by the UTF format, in which case there will be up to three bytes per character. In this case, also, characters from the file are translated into char format.
enter image description here
As with output, it is good practice to use a buffer to improve efficiency. Use BufferedReader for this. This is the same class we've been using for keyboard input. These lines should look familiar:
BufferedReader stdin =
    new BufferedReader(new InputStreamReader( System.in ));
These lines create a BufferedReader, but connect it to an input stream from the keyboard, not to a file.

Reading and Writing Files in Java

Below is a good example of reading and writing files in Java
http://www.caveofprogramming.com/frontpage/articles/java/java-file-reading-and-writing-files-in-java/

About File Handling in Java

You can read files using these classes:
  • FileReader for text files in your system’s default encoding (for example, files containing Western European characters on a Western European computer).
  • FileInputStream for binary files and text files that contain ‘weird’ characters.
FileReader (for text files) should usually be wrapped in aBufferedFileReader. This saves up data so you can deal with it a line at a time or whatever instead of character by character (which usually isn’t much use).
If you want to write files, basically all the same stuff applies, except you’ll deal with classes named FileWriter with BufferedFileWriter for text files, orFileOutputStream for binary files.
import java.io.*;

public class Test {
    public static void main(String [] args) {

        // The name of the file to open.
        String fileName = "temp.txt";

        // This will reference one line at a time
        String line = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            } 

            // Always close files.
            bufferedReader.close();   
        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileName + "'");    
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileName + "'");     
            // Or we could just do this: 
            // ex.printStackTrace();
        }
    }
}
If “temp.txt” contains this:
I returned from the City about three o'clock on that 
May afternoon pretty well disgusted with life. 
I had been three months in the Old Country, and was 
fed up with it. 
If anyone had told me a year ago that I would have 
been feeling like that I should have laughed at him; 
but there was the fact. 
The weather made me liverish, 
the talk of the ordinary Englishman made me sick, 
I couldn't get enough exercise, and the amusements 
of London seemed as flat as soda-water that 
has been standing in the sun. 
'Richard Hannay,' I kept telling myself, 'you 
have got into the wrong ditch, my friend, and 
you had better climb out.'
The program outputs this:
I returned from the City about three o'clock on that
May afternoon pretty well disgusted with life.
I had been three months in the Old Country, and was
fed up with it.
If anyone had told me a year ago that I would have
been feeling like that I should have laughed at him;
but there was the fact.
The weather made me liverish,
the talk of the ordinary Englishman made me sick,
I couldn't get enough exercise, and the amusements
of London seemed as flat as soda-water that
has been standing in the sun.
'Richard Hannay,' I kept telling myself, 'you
have got into the wrong ditch, my friend, and
you had better climb out.'

Reading Binary Files in Java

If you want to read a binary file, or a text file containing ‘weird’ characters (ones that your system doesn’t deal with by default), you need to useFileInputStream instead of FileReader. Instead of wrapping FileInputStream in a buffer, FileInputStream defines a method called read() that lets you fill a buffer with data, automatically reading just enough bytes to fill the buffer (or less if there aren’t that many bytes left to read).
Here’s a complete example.
import java.io.*;

public class Test {
    public static void main(String [] args) {

        // The name of the file to open.
        String fileName = "temp.txt";

        try {
            // Use this for reading the data.
            byte[] buffer = new byte[1000];

            FileInputStream inputStream = 
                new FileInputStream(fileName);

            // read fills buffer with data and returns
            // the number of bytes read (which of course
            // may be less than the buffer size, but
            // it will never be more).
            int total = 0;
            int nRead = 0;
            while((nRead = inputStream.read(buffer)) != -1) {
                // Convert to String so we can display it.
                // Of course you wouldn't want to do this with
                // a 'real' binary file.
                System.out.println(new String(buffer));
                total += nRead;
            } 

            // Always close files.
            inputStream.close();  

            System.out.println("Read " + total + " bytes");
        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileName + "'");    
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileName + "'");     
            // Or we could just do this: 
            // ex.printStackTrace();
        }
    }
}
I returned from the City about three o'clock on that
May afternoon pretty well disgusted with life.
I had been three months in the Old Country, and was
fed up with it.
If anyone had told me a year ago that I would have
been feeling like that I should have laughed at him;
but there was the fact.
The weather made me liverish,
the talk of the ordinary Englishman made me sick,
I couldn't get enough exercise, and the amusements
of London seemed as flat as soda-water that
has been standing in the sun.
'Richard Hannay,' I kept telling myself, 'you
have got into the wrong ditch, my friend, and
you had better climb out.'

Read 649 bytes
Of course, if you had a ‘real’ binary file — an image for instance — you wouldn’t want to convert it to a string and print it on the console as above.

Writing Text Files in Java

To write a text file in Java, use FileWriter instead of FileReader, andBufferedOutputWriter instead of BufferedOutputReader. Simple eh?
Here’s an example program that creates a file called ‘temp.txt’ and writes some lines of text to it.
import java.io.*;

public class Test {
    public static void main(String [] args) {

        // The name of the file to open.
        String fileName = "temp.txt";

        try {
            // Assume default encoding.
            FileWriter fileWriter =
                new FileWriter(fileName);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter =
                new BufferedWriter(fileWriter);

            // Note that write() does not automatically
            // append a newline character.
            bufferedWriter.write("Hello there,");
            bufferedWriter.write(" here is some text.");
            bufferedWriter.newLine();
            bufferedWriter.write("We are writing");
            bufferedWriter.write(" the text to the file.");

            // Always close files.
            bufferedWriter.close();
        }
        catch(IOException ex) {
            System.out.println(
                "Error writing to file '"
                + fileName + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        }
    }
}
The output file now looks like this (after running the program):
Hello there, here is some text.
We are writing the text to the file.

Use String replace function to make sure the output file extension is .xls

Using String replace function to make sure the output file extension is .xls. Below is example code:
int rVal = c.showSaveDialog(SaveButton.this);
  if (rVal == JFileChooser.APPROVE_OPTION) {
    String str = c.getSelectedFile().getName();
    _filename = str.replace(".xls", "");
    _dir = c.getCurrentDirectory().toString();
    _fullpath = _dir + "\\" + _filename + ".xls";
    _file = new File(_fullpath);

Friday, January 10, 2014

Simple Web Server


Below sample is very simple and easy to understand for creating a simple web server. The original link is:
http://bethecoder.com/applications/tutorials/java/socket-programming/simple-web-server.html

Type http://localhost:8888 in your browser to browse server page.

Simple Web Server 

This turoial shows how to build a prototypic web server using java socket programming. Here the web server is implemented as a stand alone java application with a single java class and client is nothing but the web browser.



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleWebServer {

  public static final int DEFAULT_WEB_SERVER_PORT = 6666;
  private int webServerPort = DEFAULT_WEB_SERVER_PORT;
  private int webServerRequestCount = 0;
  private ServerSocket webServerSocket;
  
  public SimpleWebServer(int webServerPort) {
    this.webServerPort = webServerPort;
    this.webServerRequestCount = 0;
  }
  
  /**
   * Start the web server 
   */
  protected void start() {
    
    log("Starting web server on port : " + webServerPort);
    
    try {
      //Web server socket creation
      webServerSocket = new ServerSocket(webServerPort);
      log("Started web server on port : " + webServerPort);
      
      /**
       * Wait for clients
       */
      listen();
      
    catch (Exception e) {
      hault("Error: " + e);
    }
  }
  
  /**
   * Listening on webServerPort for the clients to connect. 
   */
  protected void listen() {
    log("Waiting for connection");
    while (true) {
      try {
        // Got a connection request from client
        Socket client = webServerSocket.accept();
        webServerRequestCount ++;
        
        //Handle client request
        //This processing can be in a separate Thread
        //if we would like to handle multiple requests
        //in parallel.
        serveClient(client);
        
      catch (Exception e) {
        log("Error: " + e);
      }
    }
  }

  protected void serveClient(Socket clientthrows IOException {
    
    /**
     * Read the client request (parse the data if required)
     */
    readClientRequest(client);
    
    /**
     * Send the response back to the client.
     */
    writeClientResponse(client);
  }
  
  protected void readClientRequest(Socket clientthrows IOException {
    
    log("\n--- Request from : " + client + " ---");
    
    /**
     * Read the data sent by client.
     */
    BufferedReader in = new BufferedReader(
          new InputStreamReader(client.getInputStream()));
    
    // read the data sent. We basically ignore it,
    // stop reading once a blank line is hit. This
    // blank line signals the end of the client HTTP
    // headers.
    String str = ".";
    while (!str.equals("")) {
      str = in.readLine();
      log(str);
    }
  }
  
  protected void writeClientResponse(Socket clientthrows IOException {
    PrintWriter out = new PrintWriter(client.getOutputStream());
    // Send the response
    // Send the headers
    out.println("HTTP/1.0 200 OK");
    out.println("Content-Type: text/html");
    out.println("Server: SimpleWebServer");
    // this blank line signals the end of the headers
    out.println("");
    // Send the HTML page
    out.println("<CENTER>");
    out.println("<H1 style='color:red'>Welcome to SimpleWebServer<H1>");
    out.println("<H2>This page has been visited <span style='color:blue'>" 
        webServerRequestCount + " time(s)</span></H2>");
    out.println("</CENTER>");
    out.flush();
    client.close();
  }
  
  private static void log(String msg) {
    System.out.println(msg);
  }
  
  private static void hault(String msg) {
    System.out.println(msg);
    System.exit(0);
  }
  
  public static void main(String args[]) {
    /**
     * Start web server on port '8888'
     */
    SimpleWebServer ws = new SimpleWebServer(8888);
    ws.start();
  }
}