Thursday, 17 April 2025

Write servlet program to accept name of city from where employee belongs and display all records from employee table who belongs to that city in tabular format.


   cityform.html

<html>

<body>

    <h2>Enter City Name</h2>

    <form action="EmployeeCityServlet" method="post">

        City: <input type="text" name="city">

        <input type="submit" value="Search">

    </form>

</body>

</html>

EmployeeCityServlet.java

import java.io.*;

import java.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

 

public class EmployeeCityServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

       

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        String city = request.getParameter("city");

 

        // JDBC connection details (adjust as per your setup)

               try {

             Class.forName("com.mysql.jdbc.Driver");

 Connection con =  DriverManager.getConnection("jdbc:mysql://localhost:3306/mca", "root", "");

 

            String sql = "SELECT * FROM employee WHERE city = ?";

            PreparedStatement ps = con.prepareStatement(sql);

            ps.setString(1, city);

            ResultSet rs = ps.executeQuery();

 

            out.println("<html><body>");

            out.println("<h2>Employees from " + city + "</h2>");

            out.println("<table border='1'><tr><th>ID</th><th>Name</th><th>City</th><th>Salary</th></tr>");

 

            boolean found = false;

            while (rs.next()) {

                found = true;

                out.println("<tr>");

                out.println("<td>" + rs.getInt("id") + "</td>");

                out.println("<td>" + rs.getString("name") + "</td>");

                out.println("<td>" + rs.getString("city") + "</td>");

                out.println("<td>" + rs.getDouble("salary") + "</td>");

                out.println("</tr>");

            }

 

            if (!found) {

                out.println("<tr><td colspan='4'>No employees found in this city.</td></tr>");

            }

 

            out.println("</table>");

            out.println("</body></html>");

 

            rs.close();

            ps.close();

            con.close();

        } catch (Exception e) {

            out.println("<p>Error: " + e.getMessage() + "</p>");

        }

    }

}

 

C:\apac