Search code examples
jspservletsmodel-view-controllerjavabeans

pass session value in mvc concept from jsp to servlet in java


I am using mvc concept in that i have one class with some private field and setter and getter method, one login class one operation class which is EmployeeBean in that all functions are there login class is working properly when i am reaching to another page EmployeeDetail.jsp and after that when i am moving to DailyWork.jsp through normal url way i can retrieve the session variable and i have kept one variable which empID and it is getting printed even i am not maintaing session still it is reaching but when i am moving to DailyWorkUpdate servlet and trying to receive the session variable in the given manner

 String z = emp.getName();

System.out.println("....name is " +z);
System.out.println("....n is " +n);
emp.setEmpId(emp.getEmpId());

n is integer show it is 0 and z is string showing null please help me to solve this

here is full code...

   public class Employee {
   private int empId;
   private String Name;
   private String phone;
   private String email;
   private float salary;
   private String designation;
   private String password;
   private String access_type;
   private boolean valid;
   private String field1;
   private String field2;
   private String field3;
  public String getAccess_type() {
    return access_type;
  }
  public void setAccess_type(String access_type) {
    this.access_type = access_type;
  }
  public boolean isValid() {
    return valid;
  }

  public String getField1() {
    return field1;
  }
  public void setField1(String field1) {
    this.field1 = field1;
  }
  public String getField2() {
    return field2;
 }
 public void setField2(String field2) {
    this.field2 = field2;
 }
 public String getField3() {
    return field3;
 }
 public void setField3(String field3) {
    this.field3 = field3;
 }

  public void setValid(boolean valid) {
    this.valid = valid;
  }
  public int getEmpId() {
    return empId;
  }
  public void setEmpId(int empId) {
    this.empId = empId;
  }
  public String getName() {
    return Name;
  }
  public void setName(String Name) {
    this.Name = Name;
  }
  public String getPhone() {
    return phone;
  }
  public void setPhone(String phone) {
    this.phone = phone;
  }
  public String getEmail() {
    return email;
  }
  public void setEmail(String email) {
    this.email = email;
  }
  public float getSalary() {
    return salary;
  }
  public void setSalary(float salary) {
    this.salary = salary;
  }
  public String getDesignation() {
    return designation;
  }
  public void setDesignation(String designation) {
    this.designation = designation;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
  }

EmployeeBean class

    public class EmployeeBean {
     public Employee login(int id, String password) {
        Connection con = null;
        Employee emp = null;
        Statement stmt = null;
        try {

            con = ConnectionManager.getConnection();
            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM emp WHERE empId 
         ='"+id+"' and password ='"+password+"'");
            boolean more = rs.next();
             if (!more) {

     System.out.println("Sorry, you are not a registered user! Please sign up first");
             emp.setValid(false);
            }
            else if(more)
            {
                emp = new Employee();
                emp.setEmpId(rs.getInt("empId"));
                emp.setName(rs.getString("empName"));
                emp.setPhone(rs.getString("phone"));
                emp.setEmail(rs.getString("email"));
                emp.setSalary(rs.getFloat("salary"));
                emp.setDesignation(rs.getString("desig"));
                emp.setPassword(rs.getString("password"));
                emp.setAccess_type(rs.getString("employee_type"));
                String Name = rs.getString("empId");

                System.out.println("id is :" +Name);

                emp.setValid(true);
            }
        } catch (SQLException  ex) {

        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException ex) {
            Logger.getLogger(EmployeeBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return emp;
    }

Login.Java

   @WebServlet(name = "Login", urlPatterns = {"/Login"})
    public class Login extends HttpServlet {
    protected void processRequest(HttpServletRequest request, 
    HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(true);    
        Employee emp = new Employee();
        int id = Integer.parseInt(request.getParameter("empId"));
        String password = request.getParameter("password");
        EmployeeBean eb = new EmployeeBean();
       emp = eb.login(id,password);
       if(emp.isValid())
       {
           session.setAttribute("emp",emp);
           response.sendRedirect("EmployeeDetail.jsp"); 
           }


   }
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }

           @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }

         @Override
        public String getServletInfo() {
            return "Short description";
        }
      }

EmployeeDetail.jsp

  <%@page import="com.info.EmployeeBean"%>
  <%@page import="com.info.Employee"%>
  <%@page import="java.util.List"%>

 <html>
 <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="style.css" rel="stylesheet" type="text/css"/>
    <title>Employee Update Page</title>
  </head>
  <body>

 <ul>
  <li class='has-sub'>
        <a href="./DailyWork.jsp"><span>Update Your Work</span></a></li>
  <li class='has-sub'>
        <a href="./WorkDetail"><span>View Your Work Details</span></a></li>
  <li class='has-sub'>
    <a href="./ExcelFileGen.jsp"><span>Generetae Excel Sheet</span></a></li>
  </ul>


     <table align=center cellspacing=1 cellpadding=3>
   <p>Emp Id: ${info.empId}</p>
   <p> name is :${info.name}</p>
   <p>password is: ${info.password}</p>
    <p>designation: ${info.designation}</p>
 <p>email : ${info.email}</p>
 <p>salary: ${info.salary}</p>
 </table>
 </body>
 </html>

Login.jsp

    <%@page import="com.info.EmployeeBean"%>
   <%@page import="com.info.Employee"%>
   <%@page import="java.util.List"%>
<html>
   <form name="form" action="Login" method="post">

    <input type="text" name="empId" /><br>
   <input type="password" name ="password" /><br>
  <input type="submit" name="login" value="login" >
   </form>
   </html>

DailyWorkUpdate.jsp

   <%@page import="com.info.EmployeeBean"%>
   <%@page import="com.info.Employee"%>
    <%@page import="java.util.List"%>


  <html>
  <head>
 </head>

   <body>

  <%
  Employee emp = (Employee)session.getAttribute("emp");
  session.setAttribute("emp",emp);
  %>

      <ul>
     <li class='has-sub'>
         <a href="./DailyWork.jsp"><span>Update Your Work</span></a>
    </li>
     <li class='has-sub'>
         <a href="./WorkDetail"><span>View Your Work Details</span></a>
     </li>
     <li class='has-sub'>
         <a href="./ExcelFileGen.jsp"><span>Generetae Excel Sheet</span></a>
    </li>
     </ul>


     <table width="780" align=center cellspacing=0 border="4" cellpadding=0>
      <tr>
                    <td>
                        <fieldset id="fieldhead">
                            <legend>Update your DailyWork</legend>
                            <BR>
                            <table align=center cellspacing=1 cellpadding=3>
                        <form  name ="form" method= get action="DailyWorkUpdate">
                                <center>
                                    <tr>
                                    <Td>Support HRS</td>
                                    <TD><input name="field1"></td>
                                </tr>

                                <tr>
                                    <td> emp id</td>
                                    <td>${emp.empId}</td>
                                    </tr>
                                <tr>
                                    <Td>Leave  HRS</td>
                                    <TD><input name="field2" ></td>
                                </tr>

                                <tr>
                                    <Td>Project name</td>
                                    <TD><input name="field3"></td>
                                </tr>
            <tr><td><input type="submit"  value="DailyWorkUpdate" />
        &nbsp;&nbsp;<button type=reset accesskey="R"><u>R</u>efresh</button></td></tr>
                                </center>
                            </table>
                            <BR>
                        </fieldset>
                    </td>
                </tr>
            </table>
      </body>
     </html>






  @WebServlet(name = "DailyWorkUpdate", urlPatterns = {"/DailyWorkUpdate"})
  public class DailyWorkUpdate extends HttpServlet
  {

 protected void processRequest(HttpServletRequest request, 
 HttpServletResponse response)
        throws ServletException, IOException {
   HttpSession session = request.getSession(true);  

  Employee emp = (Employee)session.getAttribute("emp");
  session.setAttribute("emp",emp);
  java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());

  emp = new Employee();
int n = emp.getEmpId();
String z = emp.getName();

   System.out.println("....name is " +z);// it is showing null
 System.out.println("....n is " +n);// it is showing 0 why i dont know how to get this 
 emp.setEmpId(emp.getEmpId());
 emp.setField1(request.getParameter("field1"));
 emp.setField2(request.getParameter("field2"));
  emp.setField3(request.getParameter("field3"));

  emp.setDate(date);
  EmployeeBean eb = new EmployeeBean();
 eb.addWorkDetail(emp);
 }


  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      processRequest(request, response);
  }

     @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      processRequest(request, response);
  }

   @Override
  public String getServletInfo() {
      return "Short description";
  }
  }

Solution

  • Take a look at your code in :

     Employee emp = (Employee)session.getAttribute("emp");
      session.setAttribute("emp",emp);
      java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
    
      emp = new Employee();   // HERE you are reseting emp variable, so it no longer holds session data but new employee object with null name and 0 id, so just remove that line
    int n = emp.getEmpId();
    String z = emp.getName();
    
       System.out.println("....name is " +z);// it is showing null
     System.out.println("....n is " +n);// it is showing 0 why i dont know how to get this