Wednesday, February 6, 2013

How to run a servlet using tomcat server

How to run a servlet using tomcat server

If you want to access a database using servlet,then refer the following steps:
Step1:Open the folder where Apache tomcat is installed, then goto  webapps folder, create a new folder of any name for eg: sonali
Then in "sonali" folder create a folder called "WEB-INF" and a "classes" folder in "WEB-INF".
Step2: Write your java code and save it in the "classes" folder.



Try the following ConnectDb.java code:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class ConnectDb extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:myServlet");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT* FROM servlet");
pw.print("<TABLE border=1 ALIGN=CENTER>");
pw.println("<TR>");
pw.println("<TH>Id </TH><TH> Name </TH><TH>Place</TH><br>");
while (rs.next()) {
pw.println("<TR>");
pw.println("<TD>"+rs.getObject(1).toString());
pw.println("<TD>"+rs.getObject(2).toString());
pw.println("<TD>"+rs.getObject(3).toString());
pw.println("<br>");
}pw.print("</TABLE>");
} catch (SQLException e) {
pw.println(e.getNextException());
} catch (ClassNotFoundException e) {
pw.println(e.getException());
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
pw.close();
}
}
}
}

Create a Database:
 

Make a web.xml file and save it in "WEB-INF" folder
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>dbconnection</display-name>
<servlet>
<servlet-name>ConnectDb</servlet-name>
<servlet-class>ConnectDb</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ConnectDb</servlet-name>
<url-pattern>/ConnectDb</url-pattern>
</servlet-mapping>
</web-app>

Step3: Make database connectivity using JDBC and Compile the ConnectDb.java file



Step 4: Start the Apache server as done in previous post
Now open your browser and type the following in url : http://localhost:9999/sonali/ConnectDb