Check if parameter exists in servlet request

In this Example we can Add and Update the Details of Employee using Servlet.

Check if parameter exists in servlet request

Update Employee Records

     

In this Example we can Add and Update the Details of Employee using Servlet. We create four file employee.jsp, viewdata.jsp, EmployeeAdd.java and viewdata.java. When a web page ("employee.jsp") run on browser then it will called to Servlet ("EmployeeAdd.java") and add the new Employee Record in the database and provide a link on browser, by this link user redirect to Servlet "viewdata". This Servlet retrieves the data and show on browser.  

Step 1: Source code of employee.jsp to add and update the Employee records.

<%@page import="java.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <style>
  .tdcls{
  font-weight:bold;
}
A:visited  
{color: #00000;font-weight:bold; text-decoration: underline}
A:link  {color: #FFC0C0; text-decoration: none}
A:active  {color: #C0FFC0; text-decoration: none}
A:hover   { color: #FF0000;  text-decoration: none}
  </style>
 </HEAD>
 <BODY>
 <br><br> 
 <form name="frm" action="empsave" method="post">
 <%
 String emp_id = "";
 String first_name = "";
 String last_name = "";
 String request_status = "";
 String pend_request_type="";
 String pend_request_date="";
 String pend_request_data="";
 String readonly="";
 String  bttn_value="Add";
 int pend_request_id = 0;
if(request.getParameter("emp_id")!=null 
  && request.getParameter("emp_id")!="")
 {
    emp_id= request.getParameter("emp_id").toString();
 pend_request_id= Integer.parseInt
(request.getParameter("pend_request_id").toString());
   readonly = "readonly";
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "user_register";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root"; 
    String password = "root";
	bttn_value = "Update"; 
	Statement st;	 
    try {
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection
       (url+dbName,userName,password);
      System.out.println("Connected to the database");
      String query1 = 
       "SELECT * from pend_requests where emp_id='"+emp_id+"' 
        and pend_request_id='"+pend_request_id+"'";
	String query2 = "SELECT * from employee_details "+
        "where eid='"+emp_id+"'";
	  st = conn.createStatement();	
		ResultSet rs1 = st.executeQuery(query1);
		while(rs1.next())
		{
			 request_status = rs1.getString(1);
             pend_request_type=rs1.getString(5);
            pend_request_date=rs1.getString(6);
            pend_request_data=rs1.getString(7);			
		}
	ResultSet rs2 = st.executeQuery(query2);
	while(rs2.next())
	   {
             first_name = rs2.getString(2);
             last_name = rs2.getString(3);			 
		}		
	}
	catch (Exception e) {
      e.printStackTrace();
    }
 }
   %>
   <input type="hidden"  name="pid" value="<%=pend_request_id%>">
  <table width="350" align="center" border=0 bgcolor=#3EA99F>
  <tr><td colspan=2 align="center" class="tdcls">
   Employee Details</td></tr>
   <tr>
    <td width="150px" class="tdcls">Employee Id</td>
    <td width="200px">
<input type="text" name="emp_id" value="<%=emp_id%>" 
 <%=readonly%>></td></tr> 
   <tr>
    <td class="tdcls">First Name</td>
  <td><input type="text" name="first_name" 
  value="<%=first_name%>"></td> </tr><tr>
   <td class="tdcls">Last Name</td>
<td><input type="text" name="last_name" 
 value="<%=last_name%>"></td>
  </tr> 
	     <tr><td class="tdcls">Request Status</td>
		<td><select name="request_status">
<option value="open"  <% 
if(request_status.equals("open"))out.println("selected");
%>>Open</option>
 <option value="pending" <%
 if(request_status.equals("pending"))out.println("selected");
%>>Pending</option>
  <option value="deferred"  <% 
if(request_status.equals("deferred"))out.println("selected");
%>>Deferred</option>
   <option value="closed" <% 
if(request_status.equals("closed"))out.println("selected");
%>>Closed</option>
	</select>
	</td></tr>
	<tr>
         <td class="tdcls">Request Type</td>
       <td><select name="pend_request_type">
      <option value="admin" <%
   if(pend_request_type.equals("admin"))out.println("selected");
%>>Admin</option>
	  <option value="user" <% 
if(pend_request_type.equals("user"))out.println("selected");
%>>User</option>
		</select>
      
		 </td></tr> 
		 <tr>
            <td class="tdcls">Date (yyyy-mm-dd)</td>
    <td>
  <input type="text" name="pend_request_date"
 value="<%=pend_request_date%>"  <%=readonly%>>
</td>
         </tr> 
		  <tr><td class="tdcls">Description</td>
           <td>
<input type="text" name="pend_request_data" 
value="<%=pend_request_data%>"></td></tr>
     <tr>
<td colspan=2 align="center">
<input type="submit" name="submit" value="<%=bttn_value%>">
</td></tr></table>
	<br><br>
	<%
	 if(!(request.getParameter("emp_id")!=null 
           && request.getParameter("emp_id")!=""))
           {
	 %>
	<table width="100%" align="center">
	   <tr>
          <td  align="center"><a href="viewdata">
     Click here To show all records</a></td>
</tr>
    </table>
	<%
 }
	 %>
	        
 </BODY>
</HTML>

Step 2:Source code of Servlet (EmployeeAdd.java) to add and update the data. 

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
import java.util.*;
import java.text.*;

public class EmployeeAdd extends HttpServlet{ 
 
 public void doPost(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException,IOException{
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();

 System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "user_register";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root"; 
  String password = "root";
  String emp_id = request.getParameter("emp_id"); 
  String first_name = request.getParameter("first_name");
  String last_name = request.getParameter("last_name");
  String request_status = request.getParameter("request_status");
  String pend_request_date = request.getParameter("pend_request_date");
  String pend_request_type = request.getParameter("pend_request_type");
  String pend_request_data = request.getParameter("pend_request_data");
  int pend_request_id =  Integer.parseInt(request.getParameter("pid"));
  String bttn_value = request.getParameter("submit");
  String ardate[] = pend_request_date.split("-");

 if(ardate.length!=3)
 {
  response.sendRedirect("employee.jsp");
 }
  
  Statement st;
  
  try {

  java.util.Date date = new java.util.Date();
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  int j=0;
  int i=0;
  if(bttn_value.equals("Add"))
  {
  String query_1 = "insert into employee_details set eid='"+
   emp_id+"',first_name='"+first_name+"',
   last_name='"+last_name+"'";
  out.println("query_1 " + query_1);
  out.println("<br>");
  st = conn.createStatement();
  i = st.executeUpdate(query_1);
  out.println("<br>");
  out.println("i " + i);
  String query_2 =
"insert into pend_requests set pend_request_status='"+request_status+"',
emp_id='"+emp_id+"',pend_request_type='"+pend_request_type+"',
pend_request_date='"+pend_request_date+"',
pend_request_data='"+pend_request_data+"'";
  out.println("query_2 " + query_2);
 out.println("<br>");
  st = conn.createStatement();
 j = st.executeUpdate(query_2);
 response.sendRedirect("viewdata");
  }
  else if(bttn_value.equals("Update"))
  {
 java.util.Date now = new java.util.Date();
  String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
 SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
  String strDateNew = sdf.format(now) ;
  String query_1 = 
  "update  employee_details set first_name='"+first_name+"',
  last_name='"+last_name+"' 
  where eid='"+emp_id+"'";
   out.println("query_1 " + query_1);
 out.println("<br>");
 st = conn.createStatement();
   i = st.executeUpdate(query_1);
 out.println("<br>");
   out.println("i " + i);
  String query_2 = 
"update pend_requests set pend_request_status='"+request_status+"',
emp_id='"+emp_id+"',pend_request_type='"+pend_request_type+"',
pend_request_date='"+pend_request_date+"',
pend_request_data='"+pend_request_data+"',
respond_date='"+strDateNew+"' where pend_request_id="+
pend_request_id+" and emp_id='"+emp_id+"'";
  out.println("query_2 " + query_2);
 out.println("<br>");
  st = conn.createStatement();
 j = st.executeUpdate(query_2);
 response.sendRedirect("viewdata");
  } 
  //  pw.println(query);
  conn.close();
  System.out.println("Disconnected from database");
  } catch (Exception e) {
 response.sendRedirect("viewdata");
  e.printStackTrace();
  }
  }
}

Step 3:Source code of Servlet (viewdata.java) to retrieve the data. 

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
import java.util.*;

public class viewdata extends HttpServlet{ 
 
 public void doGet(HttpServletRequest request,
  HttpServletResponse response)
    throws ServletException,IOException{
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();

 System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "user_register";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root"; 
  String password = "root";
  String respond_date="";
  Statement st;
  ArrayList arData=null;
  ArrayList arDataList=new ArrayList();
 HttpSession session=request.getSession(true);
  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection
  (url+dbName,userName,password);
  System.out.println("Connected to the database");
  String query = 
  "SELECT p1.pend_request_id,p1.emp_id,p1.pend_request_type,"+
  "p1.pend_request_date,p1.pend_request_status,"+
  "p1.pend_request_data,p2.first_name,p2.last_name,"+
  "p1.respond_date FROM pend_requests p1,"+
  "employee_details p2 where p1.emp_id=p2.eid"; 
  st = conn.createStatement();  
  ResultSet rs = st.executeQuery(query);  
  while(rs.next())
  {
 arData=new  ArrayList();
 System.out.println(rs.getString(9));
 pw.println(rs.getString(9));
  if(rs.getString(9)==null)
  {
  respond_date = "Not Responding";
  }
  else
  {
  respond_date = rs.getString(9);
  }
  arData.add(rs.getInt(1));
  arData.add(rs.getString(2));
  arData.add(rs.getString(7));
  arData.add(rs.getString(8));
  arData.add(rs.getString(5));
  arData.add(rs.getString(3));
  arData.add(rs.getString(4));
  arData.add(respond_date);
  
  arDataList.add(arData);
  }
  
 pw.println("query4 " + query);
  pw.println("<br>");
  session.setAttribute("arDataList",arDataList);
   pw.println("arData " + arData);
   pw.println("<br>");
   pw.println("arDataList " + arDataList);
   pw.println("<br>");
   pw.println("session "+ session.getAttribute("arDataList"));
   pw.println("<br>");
 response.sendRedirect("viewdata.jsp");
  //  pw.println(query);
  conn.close();
  System.out.println("Disconnected from database");
  } catch (Exception e) {
  response.sendRedirect("viewdata.jsp");
  e.printStackTrace();
  }
  }
}

Step 4: Mapping the servlet (timer.java) in to web.xml file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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_2_5.xsd"
version="2.5">

<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>viewData</servlet-name>
<servlet-class>viewdata</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>viewData</servlet-name>
<url-pattern>/viewdata</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>empSave</servlet-name>
<servlet-class>EmployeeAdd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>empSave</servlet-name>
<url-pattern>/empsave</url-pattern>
</servlet-mapping>


<servlet>
<servlet-name>empUpdate</servlet-name>
<servlet-class>EmpUpdate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>empUpdate</servlet-name>
<url-pattern>/empupdate</url-pattern>
</servlet-mapping>

</web-app>

Step 5: To create a web page (viewdata.jsp) to show all the records.

<%@page import="java.util.*"%>
<html>
<head>
<title>Employee request form</title>
<style>
A:visited {color: #00000;font-weight:bold; text-decoration: underline}
A:link {color: #FFC0C0; text-decoration: none}
A:active {color: #C0FFC0; text-decoration: none}
A:hover { color: #FF0000; text-decoration: none}
.loginhead1{
text-align:left;
padding-left:5px;
}
</style>
</head>
<body>
<center>
<table border="1" width="800px" cellspacing="0"
cellpadding="0" bgcolor="bluelight">
<tr>
<td width="10%" class="loginhead1" align="center"><b>Emp ID</b></td>
<td width="19%" class="loginhead1" align="center"><b>Name</b></td>
<td width="10%" class="loginhead1" align="center"><b>Request</b></td>
<td width="14%" class="loginhead1" align="center"><b>Type</b></td>
<td width="19%" class="loginhead1" align="center"><b>
Request Date</b></td>
<td width="20%" class="loginhead1" align="center"><b>
Received Date</b></td>
<td width="11%" class="loginhead1" align="center" height="25px"><b>
Status</b></td>
<td width="11%" class="loginhead1" align="center" height="25px"><b>
Update</b></td>
</tr>
<%
String ename="";
ArrayList arList=null;
ArrayList AdminPendrequest = (ArrayList)session.getAttribute("arDataList");
//out.println(AdminPendrequest);
out.println("<br>");
int count=0;

if(AdminPendrequest!= null){
for(int i=0;i<AdminPendrequest.size();i++)
{
count++;
arList = (ArrayList)AdminPendrequest.get(i);

int pend_request_id = Integer.parseInt((arList.get(0).toString()));
String emp_id =arList.get(1).toString();
String first_name = arList.get(2).toString();
String last_name = arList.get(3).toString();
String request_status = arList.get(4).toString();
String request_type = arList.get(5).toString();
String request_date = arList.get(6).toString();
String respond_date = arList.get(7).toString();
ename = first_name+ " " + last_name;%>
<tr><form name="frm" method="post" action="employee.jsp">
<input type="hidden" name="emp_id" value="<%=emp_id%>">
<input type="hidden" name="pend_request_id" value="<%=pend_request_id%>">
<td width="10%" class="loginhead1" align="center"><%=emp_id%></td>
<td width="19%" class="loginhead1" align="center"><%=ename%></td>
<td width="10%" class="loginhead1" align="center"><%=request_status%></td>
<td width="14%" class="loginhead1" align="center"><%=request_type%></td>
<td width="19%" class="loginhead1" align="center"><%=request_date%></td>
<td width="20%" class="loginhead1" align="center"><%=respond_date%></td>
<td width="11%" class="loginhead1" align="center" height="25px">
<select name="request_status">

<%
if(request_status.equals("open"))
{
%>
<option value="pending">pending</option>
<option value="deferred">Deferred</option>
<option value="closed">Closed</option>
<%

else if(request_status.equals("pending"))
{
%>
<option value="deferred">Deferred</option>
<option value="closed">Closed</option>
<%
}
else if(request_status.equals("deferred"))
{%>
<option value="pending">Pending</option>
<option value="closed">Closed</option>

<%}
else
{
%>
<option value="closed">Closed</option>
<%
}

%> 
</select>
</td>
<td width="19%" class="loginhead1" align="center">
<input type="submit" name="submit" value="Update"</td>
<%
%>
</tr> 
</form>
<%
}
}
%>
</table>
<br>
<br>
<table>
<tr><td align="center">
<a href="employee.jsp">Add More Employee</a></td></tr>
</table>
</center>
</body>
</html>


Step 5:
Start tomcat and type http://localhost:8080/updaterequest/employee.jsp in on the browser and Click on Text Link "Click here To Show all records" . Your browser should display all the records.

Successful Output of the program:







 

Download the full web application shows here.

Download the application