Unit-10 :Servlet

5th Semester
  • java servlet
  1. write a servlet program to display the current system date time.
    1. Servlet Program

import javax.servlet.*;
import java.io.*;
import java.util.*;
public class ServletDemo extends GenericServlet
{
public void service(ServletRequest rq, ServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
rsp.setContentType(“text/html”);
Date dt=new Date();
pw.println(“<html>”);
pw.println(“<body>”);
pw.println(“Current date time=”+dt);
pw.println(“</body>”);
pw.println(“</html>”);
pw.close();
}
}
2. Web.xml

<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/showtime</url-pattern>
</servlet-mapping>
</web-app>

 
2. A servlet program that displays the name and roll number of a student sent by HTML file.
Servlet Program
import java.io.*;
import javax.servlet.*;
public class ServletParamDemo extends GenericServlet
{
public void service(ServletRequest req, ServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
String strname=req.getParameter(“txt_name”);
String strroll=req.getParameter(“txt_roll”);
pw.write(“Name=”+strname);
pw.write(” “);// for leaving some gap
pw.write(“Roll=”+strroll);
pw.close();
}
}
Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>example8</servlet-name>
<servlet-class>ServletParamDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example8</servlet-name>
<url-pattern>/runservlet</url-pattern>
</servlet-mapping>
</web-app>
HTML file
<html>
<body>
<form name=”myfrm” method=”post” action=”runservlet”>
Name:
<input type=textbox name=”txt_name” size=25 value=””>
Roll:
<input type=textbox name=”txt_roll” size=25 value=””>
<input type=submit value=”submit”>
</form>
</body>
</html>
 
3.Creating a simple servlet using javax.servlet.http package
1. Servlet Program
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse rsp) throws ServletException,
IOException
{
PrintWriter pw=rsp.getWriter();
rsp.setContentType(“text/html”);
pw.println(“<html><body>Hello World</body></html>”);
pw.close();
}
}
2. Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>
}
}
 
4. Passing parameter from HTML file to Servlet using doGet() Method
1. Servlet program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletParamDemo extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
String strname=req.getParameter(“txt_name”);
String strroll=req.getParameter(“txt_roll”);
String sem=req.getParameter(“opt_sem”);
pw.write(“Name=”+strname);
pw.write(” “);// for leaving some gap
pw.write(“Roll=”+strroll);
pw.write(” “);// for leaving some gap
pw.write(“Semester=”+sem);
pw.close();
}
}
2. Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletParamDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/runservlet</url-pattern>
</servlet-mapping>
</web-app>
3. Html file
<html>
<body>
<form name=”myfrm” method=”get” action=”runservlet”>
Name:
<input type=textbox name=”txt_name” size=25 value=””>
Roll:
<input type=textbox name=”txt_roll” size=25 value=””>
Semester:
<select name=”opt_sem”>
<option value=”Male”>Male</option>
<option value=”Female”>Female</option>
</select>
<input type=submit value=”submit”>
</form>
</body>
</html>
 
5. Passing parameter from HTML file to Servlet using doPost() Method
1. Servlet Program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletParamDemo extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
String strname=req.getParameter(“txt_name”);
String strroll=req.getParameter(“txt_roll”);
String sem=req.getParameter(“opt_sem”);
pw.write(“Name=”+strname);
pw.write(” “);// for leaving some gap
pw.write(“Roll=”+strroll);
pw.write(” “);// for leaving some gap
pw.write(“Semester=”+sem);
pw.close();
}
}
2. Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletParamDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/runservlet</url-pattern>
</servlet-mapping>
</web-app>
3. Html file
<html>
<body>
<form name=”myfrm” method=”post” action=”runservlet”>
Name:
<input type=textbox name=”txt_name” size=25 value=””>
Roll:
<input type=textbox name=”txt_roll” size=25 value=””>
Semester:
<select name=”opt_sem”>
<option value=”Male”>Male</option>
<option value=”Female”>Female</option>
</select>
<input type=submit value=”submit”>
</form>
</body>
</html>
 
6. Write a servlet program to display “welcome to our site” on clicking submit button if the user input is “Bhesh” for username field and “javaiseasy” for passwordfield.
1. Servlet program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletParamDemo extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
String uname=req.getParameter(“txt_uname”);
String pwd=req.getParameter(“txt_pwd”);
if(uname.equals(“Bhesh”)&& pwd.equals(“javaiseasy”))
{
pw.write(“Welcome to our site”);
}
else
{
pw.write(“Invalid login”);
}
pw.close();
}
}
2. Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletParamDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/runservlet</url-pattern>
</servlet-mapping>
</web-app>
3. Html file
`<html>
<body>
<form name=”myfrm” method=”post” action=”runservlet”>
Name:
<input type=textbox name=”txt_uname” size=25 >
Password:
<input type=password name=”txt_pwd” size=25>
<input type=submit value=”submit”>
</form>
</body>
</html>
 
7.Cookies
1. Servlet Program
import javax.servlet.*;
import java.io.*;
import java.util.Date;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse rsp) throws ServletException, IOException
{
String last_value=””;
try
{
Cookie [] ck_last=rq.getCookies();//get cookies from header of http
Last_value=ck_last[0].getValue();// obtain the information from cookie stored in 0th index
}
catch(Exception e){}
PrintWriter pw=rsp.getWriter();
pw.write(“Last access time=”+last);
pw.write(” “);
Date dt=new Date();
Cookie ck_current=new Cookie(“ck_date”,dt.toString());// create a cookie whose name is ck_date
with value dtrsp.addCookie(ck_current);
pw.write(“\nCurrent access time=”+dt.toString());
}
}
2. Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1”?>
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/runcooki</url-pattern>
</servlet-mapping>
</web-app>
8. Session Tracking
Q. A servlet program that displays the last access time and current access time
1. Servlet program
import javax.servlet.*;
import java.io.*;
import java.util.Date;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse rsp) throws ServletException,
IOException
{
HttpSession hs=rq.getSession(true); //get the HttpSesson object
PrintWriter pw=rsp.getWriter();
Date dt=(Date)hs.getAttribute(“dat”);
if(dt!=null)
{
pw.write(“Last access time:”+dt);
}
dt=new Date();//get current date
hs.setAttribute(“dat”,dt);
pw.write(“\nCurrent access time:”+dt);
}
}
2. Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1”?>
<web-app>
<servlet>
<servlet-name>exampleefle</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>exampleefle</servlet-name>
<url-pattern>/runssn</url-pattern>
</servlet-mapping>
</web-app>
 
9.Servlet with Database
A database db_Customer consists of table named tbl_login having fields id, uname and pwd.Write a servlet program to display „welcome message to the user‟ on clicking submit button if the user input inputs valid username and password in textbox. [ Assume DSN: Bhesh]
Servlet Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ServletDemo extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
String uname=req.getParameter(“txt_uname”);
String pwd=req.getParameter(“txt_pwd”);
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “jdbc:odbc:Bhesh”; // Bhesh is Datasource name
Connection conn = DriverManager.getConnection(url,””,””);
Statement st = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery(“SELECT * from tbl_login where uname='”+uname+”‘ and pwd='”+pwd+”‘”);
if ( rs.next() )
{
pw.write(“Welcome to our site”);
}
else
{
pw.write(“Invalid login”);
}
pw.close();
conn.close();
}
catch (Exception e)
{
pw.write(“Error”+e);
}
}
}
HTML file
<html>
<body>
<H1>Login Page</H1>
<form name=”myfrm” method=”post” action=”runservlet6″>
Name:
<input type=textbox name=”txt_uname” size=35 value=””>
Password:
<input type=textbox name=”txt_pwd” size=86 value=””>
<input type=submit value=”submit”>
</form>
</body>
</html>
Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/runservlet6</url-pattern>
</servlet-mapping>
</web-app>
Write a servlet program to display all the records of students stored in the previous table tbl_student when the user clicks the submit button.
Servlet Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ServletDemo extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “jdbc:odbc:Nag”;
Connection conn = DriverManager.getConnection(url,””,””);
Statement st = conn.createStatement();
ResultSet rs;
rs=st.executeQuery(“Select * from tbl_student”);
rsp.setContentType(“text/html”);
pw.write(“<html>”);
pw.write(“<body bgcolor=orange>”);
pw.write(“<h1 align=center>Students Information</h1>”);
pw.write(“<table border=1 align=center>”);
pw.write(“<tr>”);
pw.write(“<td>”);
pw.write(“Full Name”);
pw.write(“</td>”);
pw.write(“<td>”);
pw.write(“Address”);
pw.write(“</td>”);
pw.write(“<td>”);
pw.write(“Gender”);
pw.write(“</td>”);
pw.write(“<td>”);
pw.write(“Hobby”);
pw.write(“</td>”);
pw.write(“<td>”);
pw.write(“Comment”);
pw.write(“</td>”);
pw.write(“</tr>”);
while(rs.next())
{
String fn=rs.getString(1);
String add=rs.getString(2);
String gen=rs.getString(3);
String hob=rs.getString(4);
String cmt=rs.getString(5);
pw.write(“<tr>”);
pw.write(“<td>”);
pw.write(fn);
pw.write(“</td>”);
pw.write(“<td>”);
pw.write(add);
pw.write(“</td>”);
pw.write(“<td>”);
pw.write(gen);
pw.write(“</td>”);
pw.write(“<td>”);
pw.write(hob);
pw.write(“</td>”);
pw.write(“<td>”);
pw.write(cmt);
pw.write(“</td>”);
pw.write(“</tr>”);
}
pw.write(“</table>”);
pw.write(“</body>”);
pw.write(“</html>”);
}
catch (Exception e)
{
pw.write(“Error”+e);
}
pw.close();
conn.close();
}
}
 
10 .Request dispatching – The forward() method, the include() method
Q.Create a HTML form with a textfiled and password field for entering username and password and a submit button.Write servlet program that validates if the username input “James” and “java is easy” for the user name and password respectively. Dispatch the request to another servlet to display welcome message “Welcome <username>” when the login was successful.
Html File
<HTML>
<BODY>
<FORM ACTION=”runservlet6″ METHOD=”post”>
Name: <INPUT TYPE=TEXT Name=uname>
<BR>
Password: <INPUT TYPE=PASSWORD Name=pwd>
<BR>
<INPUT TYPE=SUBMIT VALUE=”Login” name=”login”>
</FORM>
</BODY>
</HTML>
Servlet program 1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
String userName = req.getParameter(“uname”);
String password = req.getParameter(“pwd”);
if (userName != null && password != null && userName.equals(“james”) && password.equals(“java
is easy”))
{
RequestDispatcher rd = req.getRequestDispatcher(“WelcomeServlet”);
rd.forward(req, rsp);
}
else
{
pw.write(“Invalid Login”);
}
}
}
Servlet Program2
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Welcome extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
rsp.setContentType(“text/html”);
String userName = req.getParameter(“uname”);
PrintWriter out = rsp.getWriter();
out.println(“<HTML>”);
out.println(“<BODY>”);
out.println(“Welcome “+ userName);
out.println(“</BODY>”);
out.println(“</HTML>”);
}
}
Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/runservlet6</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>wservlet</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>wservlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
</web-app>
 
Q.Create a user interface with two textfields for entering current and previous meter reading of electricity consumption and a submit button. When the user clicks submit button, these information are passed to first servlet which is responsible for finding the bill amount. The first servlet must make request to another servlet for the rate per unit.[Hint: Bill amount=no of unit * rate per unit]
Html
<HTML>
<BODY>
<FORM ACTION=”bill” METHOD=”post”>
Previous Reading: <INPUT TYPE=TEXT Name=prev>
<BR>
Current Reading: <INPUT TYPE=TEXT Name=cur>
<BR>
<INPUT TYPE=SUBMIT VALUE=”Generate Bill”>
</FORM>
</BODY>
</HTML>
Servlet1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
PrintWriter pw=rsp.getWriter();
String prev = req.getParameter(“prev”);
String curr = req.getParameter(“cur”);
rsp.setContentType(“text/html”);
String userName = req.getParameter(“uname”);
PrintWriter out = rsp.getWriter();
out.println(“<HTML>”);
out.println(“<HEAD>”);
out.println(“<br> Previous Reading= “+prev);
out.println(“<br> Current Reading= “+curr);
RequestDispatcher rd = req.getRequestDispatcher(“rate”);
rd.include(req, rsp);
Object rate=req.getAttribute(“Rate”);
double r=(Double)rate;
double amount=r*(Double.parseDouble(curr)-Double.parseDouble(prev));
out.println(“<br>Amount to be paid= “+amount);
out.println(“</BODY>”);
out.println(“</HTML>”);
}
}
Servlet2
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet2 extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
{
rsp.setContentType(“text/html”);
String userName = req.getParameter(“uname”);
PrintWriter out = rsp.getWriter();
out.println(“<HTML>”);
out.println(“<BODY>”);
out.println(“<br>Current Electricity Rate= “+10.5);
req.setAttribute(“Rate”,10.5);
out.println(“</BODY>”);
out.println(“</HTML>”);
}
}
Web.xml
<?xml version=”1.0″ encoding =”ISO-8859-1″?>
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/rate</url-pattern>
</servlet-mapping>
</web-app>

Leave a Reply

Your email address will not be published. Required fields are marked *