Wednesday 8 June 2011

How to compile and execute servlets on tomcat server using IDE






Now, the complete directory structure of your Project will be automatically created by Eclipse IDE.

Click on Demo2 project, go to Java Resources -> src. Right click on src select New -> Servlet

Give Servlet class name and click Next

click on Next Button



Leave everything else to default and click Finish

Now your Servlet is created, write some code inside it. You can take reference from the code in the picture



Add servlet-api.jar JAR file to your project. Click on Libraries, right click on Web App Libraries select Build Path -> Configure Build Path

Click on Add External JARs



Select servlet-api.jar from Apache Tomcat Directory
select servlet-api click on ok button

This JAR is now added to your project's build path.

Create web.xml file in WEB-INF folder under WebContent

Add the following code in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
 <servlet-name>example</servlet-name>
 <servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>example</servlet-name>
 <url-pattern>/myfirstservlet</url-pattern>
</servlet-mapping>
</web-app>



Now all you have to do is Start the server and run the application.

In case TomCat server is not downloaded then you need to install How to download Tomcat Server

Select required projects. Now we need only current project that is Demo2.


We need to add url pattern at the end of the address bar:
http://localhost:8080/Demo2/myfirstservlet

Again press enter

You may like the following posts:
How to download Tomcat Server
Prerequisite to learn Servlets

Thursday 2 June 2011

Write a servlet which displays current system date and time?

Write a servlet which displays current system date and time?
package ds;
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class DateServ extends GenericServlet {
 public DateServ() {
  System.out.println("SERVLET LOADED...");
 }
 public void init() {
  System.out.println("I AM FROM init METHOD...");
 }
 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  Date d = new Date();
  String s = d.toString();
  pw.println("<h1> WELCOME TO SERVLETS <h1>");
  pw.println("<h2> CURRENT DATE & TIME IS : " + s + "<h2>");
 }
 public void destroy() {
  System.out.println("I AM FROM destroy METHOD...");
 }
}

web.xml:
<web-app>
 <servlet>
   <servlet-name>kalyan</servlet-name>
   <servlet-class>ds.DateServ</servlet-class>
 </servlet>
 <servlet-mapping>
   <servlet-name>kalyan</servlet-name>
   <url-pattern>/suman</url-pattern>
 </servlet-mapping>
</web-app>


Write a servlet which illustrate the concept of ServletContext?

Write a servlet which illustrate the concept of ServletContext?
web.xml:
<web-app>
<context-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</context-param>
<context-param>
<param-name>v2</param-name>
<param-value>20</param-value>
</context-param>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
<init-param>
<param-name>v3</param-name>
<param-value>30</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
<init-param>
<param-name>v4</param-name>
<param-value>40</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/firstserv</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/secondserv</url-pattern>
</servlet-mapping>
</web-app>
Serv1.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Serv1 extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  ServletConfig config = getServletConfig();
  ServletContext ctx = config.getServletContext();
  String val1 = ctx.getInitParameter("v1");
  String val2 = ctx.getInitParameter("v2");
  String val3 = config.getInitParameter("v3");
  String val4 = config.getInitParameter("v4");
  int sum = Integer.parseInt(val1) + Integer.parseInt(val2);
  pw.println("<h3> Value of v1 is " + val1 + "</h3>");
  pw.println("<h3> Value of v2 is " + val2 + "</h3>");
  pw.println("<h3> Value of v3 is " + val3 + "</h3>");
  pw.println("<h3> Value of v4 is " + val4 + "</h3>");
  pw.println("<h2> Sum = " + sum + "</h2>");
 }
}

Serv2.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv2 extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  ServletContext ctx = getServletContext();
  Enumeration en = ctx.getInitParameterNames();
  while (en.hasMoreElements()) {
   Object obj = en.nextElement();
   String cpname = (String) obj;
   String cpvalue = ctx.getInitParameter(cpname);
   pw.println("</h2>" + cpvalue + " is the value of " + cpname + "</h2>");
  }
 }
}

Write a servlet which retrieves the data from database?

Write a servlet which retrieves the data from database?
package ddrs;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class RetrieveDataBaseServ extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  try {
   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
   Connection con = DriverManager.getConnection("oracle:jdbc:thin:@localhost:1521:Hanuman ", "scott ","tiger ");
    Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from emp");
    while (rs.next()) {
     pw.println(rs.getString(1) + " " + rs.getString(2));
    }
   } catch (Exception e) {
    res.sendError(504, "PROBLEM IN SERVLET...");
   }
  }
 }

<web-app>
<servlet>
<servlet-name>Babu</servlet-name>
<serclet-class>ddrs.RetrieveDataBaseServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Babu</servlet-name>
<url-pattern>Dinesh</url-pattern>
</servlet-mapping>
</web-app>



You may like the following posts:

Develop a flexible servlet that should display the data of the database irrespective driver name, table name and dsn name?

Develop a flexible servlet that should display the data of the database irrespective driver name, table name and dsn name?
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class DbServ extends HttpServlet {
 ServletConfig sc = null;
 public void init(ServletConfig sc) throws ServletException {
  super.init(sc);
  this.sc = sc;
 }
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  String dname = sc.getInitParameter("dname");
  String url = sc.getInitParameter("url");
  String tab = sc.getInitParameter("tab");
  try {
   Class.forName(dname);
   Connection con = DriverManager.getConnection(url, "scott", "tiger");
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("select * from " + tab);
   while (rs.next()) {
    pw.println("<h2>" + rs.getString(1) + "" + rs.getString(2) + "" + rs.getString(3) + "</h2>");
   }
   con.close();
  } catch (Exception e) {
   res.sendError(503, "PROBLEM IN DATABASE...");
  }
 }
}

web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DbServ</servlet-class>
<init-param>
<param-name>dname</param-name>
<param-value>oracle.jdbc.driver.OracleDriver ()</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:Hanuman</param-value>
</init-param>
<init-param>
<param-name>tab</param-name>
<param-value>emp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/dbdata</url-pattern>
</servlet-mapping>
</web-app>

Write a servlet which accepts product details from html form and stores the product details into database?

Write a servlet which accepts product details from html form and stores the product details into database?
Product database:
create table Product
(
pid number (4),
pname varchar2 (15),
price number (6, 2)
);
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DatabaServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/getdata</url-pattern>
</servlet-mapping>
</web-app>
DarabaServ.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class DatabaServ extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  String pid1 = req.getParameter("prodata_pid");
  String pname = req.getParameter("prodata_pname");
  String price1 = req.getParameter("prodata_price");
  int pid = Integer.parseInt(pid1);
  float price = Float.parseFloat(price1);
  try {
   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
   Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:
    Hanuman ","
    scott ","
    tiger ");
    PreparedStatement ps = con.prepareStatement("insert into Product values (?,?,?)"); ps.setInt(1, pid); ps.setString(2, pname); ps.setFloat(3, price); int i = ps.executeUpdate(); pw.println("<h4>" + i + " ROWS INSERTED..."); con.close();
   } catch (Exception e) {
    res.sendError(503, "PROBLEM IN DATABASE...");
   }
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
   doGet(req, res);
  }
 }

Write a servlet which accepts client request and display the client requested data on the browser?

Write a servlet which accepts client request and display the client requested data on the browser?
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class DataServ extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  String name = req.getParameter("persdata_eurn");
  String cname = req.getParameter("persdata_eurc");
  pw.println("<center><h3>HELLO..! Mr/Mrs. " + name + "</h3></center>");
  pw.println("<center><h3>Your COURSE is " + cname + "</h3></center>");
 }
 public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  doGet(req, res);
 }
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DataServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/getdata</url-pattern>
</servlet-mapping>
</web-app>
NOTE:
1. Whenever we are not entering the data in html form that data will be treated as empty space.
2. Query string represents the data which is passed by client to the servlet through html form. URI stands for Uniform Resource Indicator which gives the location of servlet where it is available. URL stands for Uniform Resource Locator which gives at which port number, in which server a particular JSP or servlet is running. ht represents a context path which can be either a document root or a war file.