2013년 9월 9일 월요일

getHeader in jsp

<%
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = request.getHeader(name);
out.println(name + " = " + value+"<br>");
}
%>

2013년 1월 30일 수요일

javascript confirm

javascript confirm example

<script type="text/javascript">
  var option;
  option = confirm("confirm??");
  if (option == true) {
   alert("ok");
  }
  else if (option == false) {
   alert("cancel");
  }
 </script>

2013년 1월 1일 화요일

matlab 명령어

syms 심볼릭 변수 선언
clc 화면 지움
clear 변수 지움
factor 인수분해
solve 방정식

diff 미분
expand 전개
sqrt 근호

2012년 11월 5일 월요일

They're shoveling it on Mars too


Andrew Malcolm  
Political News & Commentary


Sponsored by:

They're shoveling it on Mars too

NASA
NASA
Without a caption this photo could be any Tonka project on a beach near you.
But it's near nothing.
It's on Mars, about 154 million miles away. There, newest NASA-JPL robotic rover, the one-ton Curiosity, is shovel-ready, unlike the economic stimulus projects closer to home. In recent days Curiosity has been taking its first scoops of soil for remote on-site analysis.
At the same time other Curiosity instruments are taking readings on the Martian atmosphere. So far, at least at its current location, no signs of methane yet, which would be a precursor to biological life, as it is on Earth. A main component of Curiosity's assignment is to look for signs of a past habitable environment on Mars.
Instruments show that Mars' atmosphere, much lighter than Earth's, has lost much of its components into space over time.
Mars is actually covered with vast amounts of dust, which blows about on local winds. It actually created some problems for previous rovers, Spirit and Opportunity, as it coated their solar panels, reducing their efficient in producing power.
Curiosity is powered by a small nuclear generator. Previous drilling of ancient rocks found signs of significant interaction with water. Current samples of the dust and local sands. Scientists reported initial analysis indicated the scooped soil was similar mineralogically to basaltic materials, including feldspar, pyroxene and olivine. Significant amounts are non-crystalline like volcanic glass.
"The ancient rocks, such as the conglomerates, suggest flowing water, while the minerals in the younger soil are consistent with limited interaction with water,” said David Bish, one of the investigating scientists from Indiana University.
Malcolm & Melissa Podcast


Read More At IBD: http://news.investors.com/politics-andrew-malcolm/110412-631740-mars-rover-curiosity-digs-first-scoop-of-soil.htm#ixzz2BJgygQ96

2012년 8월 7일 화요일

jquery select


// 뒤쪽에 옵션 추가
$("#myselect").append("<option value='1'>Apples</option>");
$("#myselect").append("<option value='2'>After Apples</option>");

// 앞쪽에 옵션 삽입
$("#myselect").prepend("<option value='0'>Before Apples</option>");

// 옵션변경
$("#myselect").html("<option value='1'>Some oranges</option><option value='2'>More Oranges</option><option value='3'>Even more oranges</option>");

// 인덱스 위치에 따라 옵션 변경
$("#myselect option:eq(1)").replaceWith("<option value='2'>Some apples</option>");
$("#myselect option:eq(2)").replaceWith("<option value='3'>Some bananas</option>");





// 2번째 옵션 셀렉트
$("#myselect option:eq(2)").attr("selected", "selected");

// 해당 텍스트를 가진 옵션 셀렉트
$("#myselect").val("Some oranges").attr("selected", "selected");

// 해당값을 가진 옵션 셀렉트
$("#myselect").val("2");

// 선택 옵션 제거
$("#myselect option:eq(0)").remove();

// 첫번째 옵션 제거
$("#myselect option:first").remove();

// 마지막 옵션 제거
$("#myselect option:last").remove();

// 셀렉트된 옵션 텍스트 리턴
alert($("#myselect option:selected").text());

// 셀렉트된 옵션 값리턴
alert($("#myselect option:selected").val());

// 셀렉트된 인덱스 리턴
alert($("#myselect option").index($("#myselect option:selected")));

// Alternative way to get the selected item
alert($("#myselect option:selected").prevAll().size());

// Insert an item in after a particular position
$("#myselect option:eq(0)").after("<option value='4'>Some pears</option>");

// Insert an item in before a particular position
$("#myselect option:eq(3)").before("<option value='5'>Some apricots</option>");

// Getting values when item is selected
$("#myselect").change(function() {
    alert($(this).val());
    alert($(this).children("option:selected").text());
});

2012년 7월 24일 화요일

Apache Tomcat 7


How to Install & Configure

This tutorial can be completed in a 3-hour session, with guidance from instructor.
This installation and configuration guide is applicable to Tomcat 7, as well as the earlier versions.
(EE3072 P311 Students) This guide is NOT applicable to "EE3072 Module P311". Please read "Tomcat 6 - How to Install and Configure" instead.

Introduction

Introduction to Web Applications and HTTP

web application, unlike standalone application, runs over the Internet. Examples of web applications are google, amazon, ebay, among others. A web application is a 3-tier (or multi-tierclient-server application, usually involving a database. Most of the web applications run on the HTTP application protocol, with browser as the client to access an HTTP server.
A web database application requires five components, as illustrated below:
  1. HTTP Server: E.g., Apache HTTP Server, Microsoft IIS, Apache Tomcat, and etc.
  2. HTTP Client (Browser): E.g., MSIE, FireFox, Chrome, and etc.
  3. Database: E.g., MySQL, Oracle, DB2, Infomix, MS SQL Server, MS Access, and etc.
  4. Client-Side Programs: could be written in HTML Form, JavaScript, VBScript, Flash, and etc.
  5. Server-Side Programs: could be written in Java Servlet/JSP, ASP, PHP, and etc.
A user, via a web browser, issue a URL to an HTTP server to start a web application. The web application first downloads a client-side program (such as an HTML form) into the browser. The user fills up the query criteria in the form. The client-side program sends the query parameters to a server-side program, which queries the database and returns the query result to the client. The client-side program displays the result on the browser.
HTTP is an asynchronous request-response application-layer protocol. A client sends a request message to the server. The server returns a response message to the client. The syntax of the message is defined in the HTTP specification.

Introduction to Apache Tomcat

Apache Tomcat is a Java-capable HTTP server, which could execute Java programs. It is the official Reference Implementation (RI) for Java Servlets and JavaServer Pages (JSP) technologies. Tomcat is an open-source project, under the "Apache Software Foundation" (which also provides the famous open-source industrial-strength Apache HTTP Server). The mother site for Tomcat is http://tomcat.apache.org. Alternatively, you can find tomcat via the Apache mother site @http://www.apache.org.

How to Install Tomcat 7 

STEP 0: Read the Tomcat Documentation

Tomcat's documentation is available at Tomcat mother site @ http://tomcat.apache.org. Select "Documentation" ⇒ "Tomcat 7.0".

STEP 1: Download Tomcat

  1. From http://tomcat.apache.org ⇒ Select "Downloads" ⇒ "Tomcat 7.0" ⇒ "7.0.xx" ⇒ "Binary Distributions" ⇒ "Core" ⇒ "zip" ⇒ "apache-tomcat-7.0.xx.zip".
  2. UNZIP into a directory of your choice. DO NOT unzip onto the Desktop (because its path is hard to locate). I suggest using "d:\myproject". Tomcat will be unzipped into directory "d:\myproject\apache-tomcat-7.0.xx". For ease of use, we shall shorten and rename this directory to "d:\myproject\tomcat". Take note of Your Tomcat Installed Directory. Hereafter, I shall refer to the Tomcat installed directory as <TOMCAT_HOME>.
I recommend "zip" version, as you could simply delete the entire directory when Tomcat is no longer needed (without running any un-installer). You are free to move or rename the Tomcat's installed directory. You can install (unzip) multiple copies of Tomcat in the same machine.

STEP 2: Create an Environment Variable JAVA_HOME

You need to create an environment variable called "JAVA_HOME" and set it to your JDK installed directory.
  1. First, take note of your JDK installed directory (the default is "c:\program files\java\jdk1.7.0" or "c:\program files\java\jdk1.6.0_xx").
  2. Start a CMD shell, and issue the command "SET JAVA_HOME" to check if variable JAVA_HOME is set:
    prompt> set JAVA_HOME
    Environment variable JAVA_HOME not defined
    If JAVA_HOME is set (by other applications), check if it is set to your JDK installed directory.
  3. To set/change an environment variable in Windows 2000/XP/Vista/7: Click "Start" button ⇒ "Control Panel" ⇒ "System" ⇒ (Vista/7) "Advanced system settings" ⇒ Switch to "Advanced" tab ⇒ "Environment Variables" ⇒ "System Variables" (or "User Variables" for the current user only) ⇒ "New" (or "Edit" for modification) ⇒ In "Variable Name" field, enter "JAVA_HOME" ⇒ In "Variable Value" field, enter your JDK installed directory (e.g., "c:\program file\java\jdk1.7.0") - I suggest that you copy and paste the directory name to avoid typo error!
  4. To verify, RE-START a CMD shell and issue:
    prompt> set JAVA_HOME
    JAVA_HOME=c:\program file\java\jdk1.7.0   <== CHECK! YOUR JDK installed directory
(For Mac and Unix Users only) Take note of your JDK installed directory (most likely under /usr/local). Start a Terminal (Bash Shell), run:
$ java_home=your_jdk_install_directory  // Set environment variable java_home
$ export java_home                      // Make this variable available to all applications
To make permanent changes, store the above command in ".bash_profile" in your home directory (denoted as '~'), and run "source $HOME/.bash_profile" to refresh.

STEP 3: Configure Tomcat Server

The Tomcat configuration files are located in the "conf" sub-directory of your Tomcat installed directory (e.g. "d:\myproject\tomcat"). There are 3 configuration files:
  1. server.xml
  2. web.xml
  3. context.xml
Make a backup of the configuration files before you proceed.
Step 3(a) "server.xml" - Set the TCP Port Number
Use a text editor (e.g., NotePad++, TextPad or NotePad) to open the configuration file "server.xml", under the "conf" sub-directory of Tomcat installed directory.
The default TCP port number configured in Tomcat is 8080, you may choose any number between 1024 and 65535, which is not used by an existing application. We shall use port 9999 in this article. (For production server, you should use port 80, which is pre-assigned to HTTP server as the default port number.)
<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
<Connector port="9999" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
Step 3(b) "web.xml" - Enabling Directory Listing
Again, use a text editor to open the configuration file "web.xml", under the "conf" sub-directory of Tomcat installed directory.
We shall enable directory listing by changing "listings" from "false" to "true" for the "default" servlet, as shown in red.
<!-- The default servlet for all web applications, that serves static     -->
<!-- resources.  It processes all requests that are not mapped to other   -->
<!-- servlets with servlet mappings.                                      -->
<servlet>
  <servlet-name>default</servlet-name>
  <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
  <init-param>
    <param-name>debug</param-name>
    <param-value>0</param-value>
  </init-param>
  <init-param>
    <param-name>listings</param-name>
    <param-value>true</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
Step 3(c) "context.xml" - Enabling Automatic Reload
Again, use a text editor to open the configuration file "context.xml", under the "conf" sub-directory of Tomcat installed directory.
We shall add the attribute reloadable="true" to the <Context> element to enable automatic reload after code changes, as shown in red.
<Context reloadable="true">
   ......
</Context>

STEP 4: Start Tomcat Server

The Tomcat's executable programs are kept in the "bin" sub-directory of the Tomcat installed directory (e.g., "d:\myproject\tomcat\bin").
Step 4(a) Start Server
Launch a CMD shell. Set the current directory to "<TOMCAT_HOME>\bin", and run "startup.bat". A new Tomcat console window appears. Study the messages. Look out for the Tomcat's port number. Future error messages will be send to this console. System.out.println() issued by your Java servlets will also be sent to this console.
// Change the current directory to Tomcat's "bin"
// Assume that Tomcat is installed in "d:\myproject\tomcat"
prompt> d:                     // Change the current drive
D:\...> cd \                   // Change Directory to ROOT directory
D:\> cd \myproject\tomcat\bin  // Change Directory to YOUR Tomcat's "bin" directory
     
// Start Tomcat Server
D:\myproject\tomcat\bin> startup
......
INFO: Initializing Coyote HTTP/1.1 on http-9999
......
INFO: Starting Coyote HTTP/1.1 on http-9999
......
INFO: Server startup in 699 ms
Double check Tomcat server's HTTP port number on the Tomcat console.
(For Mac and Unix Users Only) First, change directory to Tomcat binary directory. You may need to use "./startup.sh" to start the server.
Step 4(b) Start a Client to Access the Server
Start a browser (client), and issue URL "http://localhost:9999" to access the Tomcat server's welcome page. The hostname "localhost" (with IP address of 127.0.0.1) is meant for local loop-back testing. For users on the other machines over the net, they have to use the server's IP address or DNS hostname in the format of "http://serverHostnameOrIPAddress:9999".
Step 4(c) Shutdown Server
You can shutdown the server by running "<TOMCAT_HOME>\bin\shutdown.bat". If Tomcat does not respond to the shutdown command, you could terminate Tomcat by pushing control-c (or control-break) on the Tomcat's console. DO NOT kill the cat by pushing the "close" button.
(Skip Unless ...) Cannot Start Tomcat
  • Check the Error Messages on Tomcat's Console. Most of the error messages have tens of lines. You need to scroll up slowly from the last message to look for the first-line of the error messages.
  • Check the Tomcat's log files, located at "<TOMCAT_HOME>\logs". "catalina.yyyy-mm-dd.log" shows the Tomcat's startup messages. Also check the "localhost.yyyy-mm-dd.log".

STEP 5: Develop and Deploy a Web Application

Step 5(a) Create the Directory Structure for your Web Application (webapp)
First of all, choose a name for your webapp. Let us call it "hello". Navigate to Tomcat's "webapps" sub-directory, and create the following directory structure for you webapp "hello", as illustrated:
  1. Under Tomcat's "webapps", create your web application root directory "hello" (i.e., "<TOMCAT_HOME>\webapps\hello").
  2. Under "hello", create a sub-directory "WEB-INF" (case sensitive, a dash not an underscore) (i.e., "<TOMCAT_HOME>\webapps\hello\WEB-INF").
  3. Under "WEB-INF", create a sub-directory "classes" (case sensitive, plural) (i.e., "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes").
You need to keep your web resources (e.g., HTMLs, CSSs, images, scripts, servlets, JSPs) in the proper directories:
  • "hello": The is called the context root (or document base directory) of your web application. You should keep all your HTML files and resources visible to the web users (e.g., CSSs, images, scripts, JSPs) under this context root.
  • "hello\WEB-INF": This directory, although under the context root, is not visible to the web users. This is where you keep your application's configuration files "web.xml".
  • "hello\WEB-INF\classes": This is where you keep all the Java classes such as servlet class-files.
You should RE-START your Tomcat server. Check the Tomcat's console to confirm that "hello" application has been properly depolyed:
......
INFO: Deploying web application directory hello
......
You can issue the following URL to access the web application "hello":
http://localhost:9999/hello
You should see the directory listing of the directory "<TOMCAT_HOME>\webapps\hello", which is probably empty.
Step 5(b) Write a Welcome Page
Create the following HTML page and save as "HelloHome.html" in your application's root directory "hello".
1
2
3
4
5
6
<html>
  <head><title>My Home Page</title></head>
  <body>
    <h1>My Name is so and so. This is my HOME.</h1>
  </body>
</html>
You can browse this page by issuing this URL:
http://localhost:9999/hello/HelloHome.html
Alternatively, you can issue an URL to your web application root "hello":
http://localhost:9999/hello
The server will return the directory listing of your base directory (only if you have enabled directory listing in your configuration in Step 3(b)). You can then click on "HelloHome.html".
Rename "HelloHome.html" to "index.html", and issue a directory request again:
http://localhost:9999/hello
Now, the server will redirect the directory request to "index.html", if the root directory contains an "index.html", instead of serving the directory listing.
You can check out the home page of your peers by issuing (or access your own server from another machine):
http://YourPeerHostnameOrIPAddress:9999/hello
http://YourPeerHostnameOrIPAddress:9999/hello/HelloHome.html
http://YourPeerHostnameOrIPAddress:9999/hello/index.html
with a valid "YourPeerHostnameOrIPAddress", provided that your peer has started his/her web server. You can use command such as "ipconfig", "winipcfg", "ping" to find your IP address.

(Skip Unless...) The likely errors are "Unable to Connect", "Internet Explorer cannot display the web page", and "404 File Not Found". Read "How to Debug" section.

STEP 6: Write a "Hello-world" Java Servlet

servlet is Java program that runs inside a Java-capable HTTP Server, such as Apache Tomcat. A web user invokes a servlet by issuing an appropriate URL from a web browser (or HTTP client).
Before you proceed, I shall assume that you are familiar with Java Programming and have installed the followings:
  1. JDK (Read "How to install JDK and Get Started").
  2. A programming text editor, such as TextPad or Notepad++ (Read "Programming Text Editor"); or a Java IDE such as Eclipse or NetBeans (Read "How to Install Eclipse" or "How to Install NetBeans").
Step 6(a) Install Servlet API Library 
Before we can write our first servlet, we need to install the Servlet API. Servlet API is not part of JDK (but belongs to Java EE). Tomcat also includes a copy of Servlets API.
COPY the Tomcat's Servlet API JAR-file located at "<TOMCAT_HOME>\lib\servlet-api.jar", (e.g., "d:\myproject\tomcat\lib\servlet-api.jar") into JDK's extension directory at "<JAVA_HOME>\jre\lib\ext", (e.g., "c:\program files\java\jdk1.7.0\jre\lib\ext").
(For Advanced Users Only) Alternatively, you could include the Servlet API JAR-file in the CLASSPATH. Open "Control Panel" ⇒ System ⇒ (Vista/7 only) Advanced system settings ⇒ Switch to "Advanced" tab ⇒ Environment variables ⇒ Choose "System Variables" (for all users in this system) or "User Variables" (for this login user only) ⇒ Choose "New" or "Edit"⇒ In "Variable Name", enter "classpath" ⇒ In "Variable Value", enter ".;path-to\servlet-api.jar", where "path-to" includes the drive letter and path of the Servlet API jar-file "servlet-api.jar". You can also compile your program using "javac -cp .;path-to\servlet-api.jar ServletName".
Step 6(b) Write a "Hello-world" Java Servlet
A Java servlet is a Java program that runs inside a HTTP server. A web user invokes a servlet by issuing a URL from a browser (or HTTP client).
In this example, we are going to write a Java servlet called HelloServlet, which says "Hello, world!". We will then write a configuration such that web users can invoke this servlet by issuing URL http://hostname:port/hello/sayhello from the browser, as illustrated:
Write the following source codes called "HelloServlet.java" and save it under your application "classes" directory (i.e., "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\HelloServlet.java"). Compile the source into "HelloServlet.class". This servlet says "Hello", echos some request information, and prints a random number upon each request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// To save as "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\HelloServlet.java"
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class HelloServlet extends HttpServlet {
   @Override
   public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws IOException, ServletException {
 
      // Set the response MIME type of the response message
      response.setContentType("text/html");
      // Allocate a output writer to write the response message into the network socket
      PrintWriter out = response.getWriter();
 
      // Write the response message, in an HTML page
      try {
         out.println("<html>");
         out.println("<head><title>Hello, World</title></head>");
         out.println("<body>");
         out.println("<h1>Hello, world!</h1>");  // says Hello
         // Echo client's request information
         out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
         out.println("<p>Protocol: " + request.getProtocol() + "</p>");
         out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
         out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
         // Generate a random number upon each request
         out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
         out.println("</body></html>");
      } finally {
         out.close();  // Always close the output writer
      }
   }
}

(Skip Unless...) Read "Common Errors in Compiling Java Servlet".
Step 6(c) Configure Servlet's Request URL in "webapps\hello\WEB-INF\web.xml"
A web user invokes a servlet, which is kept in the web server, by issuing a request URL from the browser. We need to configure this request URL for our HelloServlet.
Create the following configuration file called "web.xml", and save it under "webapps\hello\WEB-INF" (i.e., "<TOMCAT_HOME>\webapps\hello\WEB-INF\web.xml").
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 
   <!-- To save as "hello\WEB-INF\web.xml" -->
 
   <servlet>
      <servlet-name>HelloWorld</servlet-name>
      <servlet-class>HelloServlet</servlet-class>
   </servlet>
 
   <!-- Note: All <servlet> elements MUST be grouped together and
         placed IN FRONT of the <servlet-mapping> elements -->
 
   <servlet-mapping>
      <servlet-name>HelloWorld</servlet-name>
      <url-pattern>/sayhello</url-pattern>
   </servlet-mapping>
</web-app>
In the above configuration, a servlet having a class file "HelloServlet.class" is mapped to request URL "/sayhello" (via an arbitrary servlet-name "HelloWorld"), under this web application "hello". In other words, the complete request URL for this servlet is "http://hostname:port/hello/sayhello".
This configuration file, saved under your web application "hello", is applicable only to this particular web application "hello".
IMPORTANT: For each servlet, you need to write a pair of <servlet> and <servlet-mapping> elements with a common <servlet-name>. Take note that all the <servlet> elements MUST be grouped together and placed IN FRONT of the<servlet-mapping> elements.
Step 6(d) Invoke the Servlet
To run this servlet, start a browser, and issue the request URL configured earlier:
http://localhost:9999/hello/sayhello
You shall see the output of the servlet displayed in your web browser.
Refresh the browser, you shall see a new random number upon each refresh. In other word, the doGet() method of the servlet runs once per request.
Try "View Source" to look at the output received by the web users. Take note that the web users receive only the output of the servlet (generated via the out.println() statements). They have no access to the servlet programs (which may contain confidential information).
<html>
<head><title>Hello, World</title></head>
<body>
<h1>Hello, world!</h1>
<p>Request URI: /hello/sayhello</p>
<p>Protocol: HTTP/1.1</p>
<p>PathInfo: null</p>
<p>Remote Address: 127.0.0.1</p>
<p>A Random Number: <strong>0.3523682325749493</strong></p>
</body>
</html>

(Skip Unless...) The likely errors are "404 File Not Found" and "500 Internal Server Error". Read "How to debug" Section.

STEP 7: Write a Database Servlet 

This section assumes that you are familiar with Java database programming and MySQL database server. Otherwise, read "How to Install MySQL and Get Started".
Step 7(a) Setup a Database on MySQL
Start your MySQL server. Take note of the server's port number. I shall assume that the MySQL server is running on port 8888 (whereas the Tomcat is running on port 9999).
D:\myproject\mysql\bin> mysqld --console
Start a MySQL client. I shall assume that there is a user called "myuser" with password "xxxx".
D:\myproject\mysql\bin> mysql -u myuser -p
Run the following SQL statements to create a database called "ebookshop", with a table called "books" with 5 columns: idtitleauthorpriceqty.
create database if not exists ebookshop;

use ebookshop;

drop table if exists books;
create table books (
   id     int,
   title  varchar(50),
   author varchar(50),
   price  float,
   qty    int,
   primary key (id));

insert into books values (1001, 'Java for dummies', 'Tan Ah Teck', 11.11, 11);
insert into books values (1002, 'More Java for dummies', 'Tan Ah Teck', 22.22, 22);
insert into books values (1003, 'More Java for more dummies', 'Mohammad Ali', 33.33, 33);
insert into books values (1004, 'A Cup of Java', 'Kumar', 55.55, 55);
insert into books values (1005, 'A Teaspoon of Java', 'Kevin Jones', 66.66, 66);

select * from books;
Step 7(b) Install MySQL JDBC Driver
You need to download MySQL JDBC driver if you have not done so. Read Step 8(a) of "How to install MySQL and Get Started".
(Advanced) You could also place the MySQL driver jar-file "mysql-connector-java-5.1.xx-bin.jar" in Tomcat's "lib" directory.
Step 7(c) Write a Client-side HTML Form
Let's write an HTML script to create a query form with 3 checkboxes and a submit button, as illustrated below.  Save the HTML file as “querybook.html” in your application root directory “<TOMCAT_HOME>\webapps\hello”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html>
<head>
  <title>Yet Another Bookshop</title>
</head>
<body>
  <h2>Yet Another Bookshop</h2>
  <form method="get" action="http://localhost:9999/hello/doquery">
    <b>Choose an author:</b>
    <input type="checkbox" name="author" value="Tan Ah Teck">Ah Teck
    <input type="checkbox" name="author" value="Mohammad Ali">Ali
    <input type="checkbox" name="author" value="Kumar">Kumar
    <input type="submit" value="Search">
  </form>
</body>
</html>
You can browse the HTML page by issuing the following URL:
http://localhost:9999/hello/querybook.html
Check a box (e.g., "Tan Ah Teck") and click the "Search" button.  An HTTP GET request will be issued to the URL specified in the <form>'s "action" attribute.  Observe the URL of the HTTP GET request:
http://localhost:9999/hello/doquery?author=Tan+Ah+Teck
The request consists of two part: a URL corresponding to the "action" attribute of the <form> tag, and the "name=value" pair extracted from the <input> tag, separated by a '?'. Take note that blanks are replaced by '+' (or %20), because blanks are not allowed in the URL.
If you check two boxes (e.g., "Tan Ah Teck" and "Mohammad Ali"), you will get this URL, which has two "name=value" pairs separated by an '&'.
http://localhost:9999/hello/doquery?author=Tan+Ah+Teck&author=Mohammad+Ali
You are expected to get an error "404 File Not Found", as you have yet to write the server-side program.
Step 7(d) Write the Server-side Database Query Servlet
The next step is to write a Java servlet, which responses to the client’s request by querying the database and returns the query results.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// To save as "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\QueryServlet.java".
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class QueryServlet extends HttpServlet {  // JDK 6 and above only
 
   // The doGet() runs once per HTTP GET request to this servlet.
   @Override
   public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException {
      // Set the MIME type for the response message
      response.setContentType("text/html");
      // Get a output writer to write the response message into the network socket
      PrintWriter out = response.getWriter();
 
      Connection conn = null;
      Statement stmt = null;
      try {
         // Step 1: Allocate a database Connection object
         conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
            // database-URL(hostname, port, default database), username, password
 
         // Step 2: Allocate a Statement object within the Connection
         stmt = conn.createStatement();
 
         // Step 3: Execute a SQL SELECT query
         String sqlStr = "select * from books where author = "
              + "'" + request.getParameter("author") + "'"
              + " and qty > 0 order by price desc";
 
         // Print an HTML page as the output of the query
         out.println("<html><head><title>Query Response</title></head><body>");
         out.println("<h3>Thank you for your query.</h3>");
         out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
         ResultSet rset = stmt.executeQuery(sqlStr);  // Send the query to the server
 
         // Step 4: Process the query result set
         int count = 0;
         while(rset.next()) {
            // Print a paragraph <p>...</p> for each record
            out.println("<p>" + rset.getString("author")
                 + ", " + rset.getString("title")
                 + ", $" + rset.getDouble("price") + "</p>");
            count++;
         }
         out.println("<p>==== " + count + " records found =====</p>");
         out.println("</body></html>");
     } catch (SQLException ex) {
        ex.printStackTrace();
     } finally {
        out.close();  // Close the output writer
        try {
           // Step 5: Close the resources
           if (stmt != null) stmt.close();
           if (conn != null) conn.close();
        } catch (SQLException ex) {
           ex.printStackTrace();
        }
     }
   }
}
Step 7(e) Configure the Request URL for the Servlet
Open the configuration file "web.xml" of your application "hello" that you have created earlier for the HelloServlet, i.e., "<TOMCAT_HOME>\webapps\hello\WEB-INF\web.xml". Add the lines that are shown in red at the correct locations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 
   <!-- To save as "hello\WEB-INF\web.xml" -->
 
   <servlet>
      <servlet-name>HelloWorld</servlet-name>
      <servlet-class>HelloServlet</servlet-class>
   </servlet>
 
   <servlet>
      <servlet-name>UserQuery</servlet-name>
      <servlet-class>QueryServlet</servlet-class>
   </servlet>
 
   <!-- Note: All <servlet> elements MUST be grouped together and
         placed IN FRONT of the <servlet-mapping> elements -->
 
   <servlet-mapping>
      <servlet-name>HelloWorld</servlet-name>
      <url-pattern>/sayhello</url-pattern>
   </servlet-mapping>
 
   <servlet-mapping>
      <servlet-name>UserQuery</servlet-name>
      <url-pattern>/doquery</url-pattern>
   </servlet-mapping>
</web-app>
The above lines configure the following URL to invoke QueryServlet:
http://localhost:9999/hello/doquery
Step 7(f) Trigger the Servlet from the Client-Side Form
Issue the following URL to browse the HMTL form "querybook.html" that you have created earlier:
http://localhost:9999/hello/querybook.html
Select an author (e.g., "Tan Ah Teck") and click the submit button, which activates the following URL coded in the <form>'s "action" attribute, together with the name=value pair:
http://localhost:9999/hello/doquery?author=Tan+Ah+Teck
This URL "/doquery" triggers QueryServlet. The QueryServlet retrieves the name=value pair of "author=Tan+Ah+Teck". Inside the QueryServlet, the method request.getParameter("author") returns "Tan Ah Teck", which is inserted into the SQL SELECT command to query the database. The processed query result is then written to the client as an HTML document.

(Skip Unless...) The likely errors are "404 File Not Found" and "500 Internal Server Error". Read "How to debug" Section.

STEP 8: Deploying Servlet using @WebServlet (Servlet 3.0 on Tomcat 7)

Servlet 3.0, which is supported by Tomcat 7, introduces the @WebServlet annotation, which greatly simplifies the deployment of servlets. You no longer need to write the deployment descriptor in "web.xml". Instead, you can use the@WebServlet annotation to specify the url mapping.
For example, let us write a new servlet called HelloAgainServlet.java, by modifying the HelloServlet.java written earlier, with url mapping of "sayhi".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// To save as "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\AnotherHelloServlet.java"
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
 
@WebServlet("/sayhi")
public class AnotherHelloServlet extends HttpServlet {
   @Override
   public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws IOException, ServletException {
 
      // Set the response MIME type
      response.setContentType("text/html;charset=UTF-8");
      // Allocate a output writer to write the response message into the network socket
      PrintWriter out = response.getWriter();
 
      // Write the response message, in an HTML page
      try {
         out.println("<html>");
         out.println("<head><title>Hello, World</title></head>");
         out.println("<body>");
         out.println("<h1>Hello world, again!</h1>");  // says Hello
         // Echo client's request information
         out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
         out.println("<p>Protocol: " + request.getProtocol() + "</p>");
         out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
         out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
         // Generate a random number upon each request
         out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
         out.println("</body></html>");
      } finally {
         out.close();  // Always close the output writer
      }
   }
}
In Line 7, the annotation @WebServlet("/sayhi") is used to declare the url mapping for this servlet, i.e., http://localhost:9999/hello/sayhi. There is no need to provide any more configuration in "web.xml"!

How to Debug? 

"Everything that can possibly go wrong will go wrong."
Always...
  1. Refresh your browser using Cntl-F5 (instead of refresh button or simply F5) to get a fresh copy, instead of from the cache.
  2. You may re-start your Tomcat. You may also re-start your browser to clear the cache.
  3. Check your spelling! Always assume that all programs are case-sensitive. Don't type, copy and paste if possible!
  4. If Tomcat can be started, but you cannot run your servlet. Goto the Tomcat's home page (http://localhost:9999), and try to run the "servlets examples" to ensure that Tomcat is properly installed.
  5. Try accessing your application root, e.g., http://localhost:9999/hello. You shall see the directory listing (if you have enabled the directory listing option in "web.xml" in Step 3(b)).
  6. and MOST IMPORTANTLY - Find the ERROR MESSAGE!!!
    1. Check the Error Messages on Tomcat's Console. Most of the error messages have tens of lines. You need to scroll up slowly from the last message to look for the first-line of the error messages.
    2. Check the Tomcat's log files, located at "<TOMCAT_HOME>\logs" directory. "catalina.yyyy-mm-dd.log" shows the Tomcat's startup messages. Also check the "localhost.yyyy-mm-dd.log".
  7. If things were running fine until the lightning strikes, ask yourself "what have I changes?"
(Firefox) Unable to Connect
(IE) Internet Explorer cannot display the webpage
(Chrome) Oops! Google Chrome could not connect to ...
Cause: You are simply not connecting to your Tomcat.
Solution:
  1. Check if your Tomcat has started?
  2. Check the hostname (localhost, NOT host) and port number, separated by a colon ':', of your URL (http://localhost:9999/...).
Error 404 File Not Found
Cause: You have connected to your Tomcat. But Tomcat cannot find the HTML file or Servlet that your requested.
Solution:
  1. Check your spelling! The path is case-sensitive!
  2. For HTML file with URL http://localhost:9999/xxxx/filename.html:
    1. Open Tomcat's "webapps" directory, check if sub-directory "xxxx" exists. It is case-sensitive.
    2. Open the "xxxx" directory, check if "filename.html" exists.
  3. For Servlet with URL http://localhost:9999/xxxx/servletURL:
    1. Check the Tomcat's console for error message. Your application cannot be deployed if you make a mistake in editing "web.xml", which triggered many error messages.
    2. Check the Tomcat console to make sure that your application has been deployed.
    3. Open Tomcat's "webapps" directory, check if sub-directory "xxxx" exists.
    4. Open the "xxxx" directory, check if sub-sub-directory "WEB-INF" (uppercase with a dash) exists.
    5. Open the "WEB-INF", check if sub-sub-sub directory "classes" (lowercase, plural) exists.
    6. Open the configuration file "WEB-INF\web.xml":
      1. Check that servletURL is defined in a <servlet-mapping> tag. Take note of the name in <servlet-name> tag.
      2. Based on the name noted, look for the matching <servlet-class> tag. Take note of the ServletClassname.
      3. Open "WEB-INF\classes", check if "ServletClassname.class" that you noted exists (Note: It is ".class", and NOT ".java". You need to compile the ".java" to get the ".class".)
Error 500 Internal Server Error
Error 500 should have triggered many error message in the Tomcat's console. Go to the Tomcat's console, find the error message. The error message spans tens of lines. You need to scroll up slowly to look for the first line of the error message. The error message should tell you the cuase of this error, e.g. SQL syntax error, wrong user/password, etc.
For database servlet, you may check the error messages at "Common Errors in JDBC Programming".
  • For "No suitable driver found" (Windows) or NullPointerException (Mac and Linux): Read Step 7(b) again, again, and again.
Error 505: GET (or POST) Method Not Supported
Check you servlet to make sure that you have defined a doGet() (or doPost()) method.
Others
Try searching "Common Error Messages".

REFERENCES & RESOURCES

  1. Apache Tomcat mother site @ http://tomcat.apache.org
  2. Apache Tomcat Documentation @ "<TOMCAT_HOME>\webapps\docs".
  3. "How to install MySQL and Get Started".


http://www3.ntu.edu.sg/home/ehchua/programming/howto/tomcat_howto.html