Follow by Email

Wednesday, 28 March 2012

Add Employee Controller(Spring)

AddEmployeeController:

AddEmployeeController .java

package com.spring.jagan.addemployee;
import org.springframework.web.servlet.mvc.*;
public class AddEmployeeController extends SimpleFormController
{
 EmployeeServices employeeServices;
 public AddEmployeeController(EmployeeServices es)
 {
  employeeServices=es;
 }
@Override
 public void doSubmitAction(Object commnad)
 {
 employeeServices.create((EmpDetails)commnad);
 
 }
}

EmpDetails .java

package com.spring.jagan.addemployee;
public class EmpDetails {
 public void EmpDetails()
 {
 System.out.println("In EmpDetails Constructor ,Constructing a new Instance for EmpDetails");
 }

private int empno,deptno,mgr;
private String name,job;
private double sal,comm;
public int getEmpno() {
 return empno;
}
public void setEmpno(int empno) {
 this.empno = empno;
}
public int getDeptno() {
 return deptno;
}
public void setDeptno(int deptno) {
 this.deptno = deptno;
}
public int getMgr() {
 return mgr;
}
public void setMgr(int mgr) {
 this.mgr = mgr;
}
public String getName() {
 return name;
}
public void setName(String name) {
 this.name = name;
}
public String getJob() {
 return job;
}
public void setJob(String job) {
 this.job = job;
}
public double getSal() {
 return sal;
}
public void setSal(double sal) {
 this.sal = sal;
}
public double getComm() {
 return comm;
}
public void setComm(double comm) {
 this.comm = comm;
}
}//class

EmployeeServices.java

package com.spring.jagan.addemployee;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
public class EmployeeServices {
 private JdbcTemplate jdbcTemplate;
 public EmployeeServices(JdbcTemplate jt)
 {
  jdbcTemplate =jt;
 }

 public void create( final EmpDetails user)
 {
  // TODO Auto-generated method stub
  jdbcTemplate.update("insert into emp values(?,?,?,?,?,?,?,?)",new PreparedStatementSetter(){
   public void setValues(PreparedStatement ps)throws SQLException
   {
    ps.setInt(1, user.getEmpno());
    ps.setString(2, user.getName());
    ps.setString(3, user.getJob());
    ps.setInt(4, user.getMgr());
    ps.setDate(5, new Date(System.currentTimeMillis()));
    ps.setDouble(6, user.getSal());
    ps.setDouble(7, user.getComm());
    ps.setInt(8, user.getDeptno());
  
   }
 });
 }
}
EmpVaidator.java

package com.spring.jagan.addemployee;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
 *
 * @author Jagan moha paspula
 *
 */
public class EmpVaidator  implements Validator
{
/**
 * @param Class
 */
 public boolean supports(Class c) {
  // TODO Auto-generated method stub
 boolean flag =c.equals(EmpDetails.class);
 return flag;
 }
 /**
  * @param target
  * @param Errors
  */
 public void validate(Object target, Errors errors)
 {
  // TODO Auto-generated method stub
  EmpDetails ud=(EmpDetails)target;
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required","The user filed cant be empty");
  if(ud.getDeptno()<10)
  {
   errors.rejectValue("deptno","field.minValue",new Object[]{Integer.valueOf(9)},"The deptno should greater than 9");
  
  }
  else if(ud.getDeptno()<10)
  {
   errors.rejectValue("deptno","field.maxValue",new Object[]{Integer.valueOf(99)},"The deptno should less than 99");
  
  }
 }
}
Addvariablepay.xml
<p> <?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Configuring DataSource -->
 <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName">
   <value>oracle.jdbc.driver.OracleDriver</value>
   </property>
   <property name="url">
   <value>jdbc:oracle:thin:@localhost:1521:orcl</value>
   </property>
   <property name="username">
   <value>scott</value>
   </property>
   <property name="password">
   <value>tiger</value>
   </property>
   </bean>
  <bean id="jdbctemp" class="org.springframework.jdbc.core.JdbcTemplate">
   <constructor-arg>
   <ref local="datasource"/>
  </constructor-arg>
   </bean>
   <bean id="employeeService" class="com.spring.jagan.addemployee.EmployeeServices">
   <constructor-arg>
   <ref local="jdbctemp"/>
  </constructor-arg>
   </bean>
 
 <bean name ="/addEmployee.spring" class="com.spring.jagan.addemployee.AddEmployeeController">
   <constructor-arg>
   <ref local="employeeService"/>
  </constructor-arg>
  <property name="commandClass">
 <value type="java.lang.Class">com.spring.jagan.addemployee.EmpDetails</value>
   </property>
   <property name="commandName">
  <value>
  EmpDetails
  </value>
   </property>
   <property name="validator">
 <bean class="com.spring.jagan.addemployee.EmpVaidator"/>
   </property>
   <!--property name="bindOnNewForm" value ="true"></property-->
   <property name="sessionForm" value="false"></property>
   <property name="formView"><value>/AddEmployee.jsp</value></property>
   <property name="successView"><value>/AddemployeeSucess.jsp</value></property>
   </bean>
  
    <!--<bean id="myurlmapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
     <property name="mappings">
     <props>
     <prop key = "/login.spring">logincnt</prop>
     </props>
   </property>
  </bean>

--></beans>
</p>

Spring(sample)project

LoginController.java

package com.jagan.spring;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
import javax.servlet.http.*;
/**
 *
 * @author jagan mohan paspula
 *
 */
public class LoginController implements Controller
{

 LoginModel loginModel;

 public LoginController(LoginModel lm)
 {
  loginModel=lm;
 }

    /**@author jagan mohan paspula
     *
     */
 public ModelAndView handleRequest(HttpServletRequest req,
   HttpServletResponse res) throws Exception
   {
  // TODO Auto-generated method stub
  String uname =req.getParameter("uname");
  String pass = req.getParameter("pass");
  String type = loginModel.validate(uname,pass);
  if(type==null)
   throw new MyExpection("user deatils are not valid");
   //return new ModelAndView("/employeelogin.jsp");
  else if(type.equals("admin"))
   return new ModelAndView("/AdminHome.jsp");
  else
   return new ModelAndView("/userHome.jsp");

}
}

LoginModel .java

package com.jagan.spring;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
public class LoginModel {

 private JdbcTemplate jdbcTemplate;
 public LoginModel(JdbcTemplate jt)
 {
  jdbcTemplate = jt;
 }

  /**
   * @author jagan mohan paspula
   * @param uname
   * @param pass
   * @return
   */
 public String validate(String uname, String pass) {
  // TODO Auto-generated method stub
  try
  {
  return(String)jdbcTemplate.queryForObject("select type from userdeatils where username=\'"+uname+"\' and userpass=\'"+pass+"\'",String.class);
  }
  catch(EmptyResultDataAccessException e)
  {
   return null;
  }
   }
}

MyExpection .java

package com.jagan.spring;
public class MyExpection extends RuntimeException {

 public MyExpection(String name)
 {
  super(name);
 
 }
}

ds-servlet.xml

<p>
<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Configuring DataSource -->
 <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName">
   <value>oracle.jdbc.driver.OracleDriver</value>
   </property>
   <property name="url">
   <value>jdbc:oracle:thin:@localhost:1521:orcl</value>
   </property>
   <property name="username">
   <value>scott</value>
   </property>
   <property name="password">
   <value>tiger</value>
   </property>
   </bean>
 
  <bean id="jdbctemp" class="org.springframework.jdbc.core.JdbcTemplate">
   <constructor-arg>
   <ref local="datasource"/>
  </constructor-arg>
   </bean>
<bean id="loginModel" class="com.jagan.spring.LoginModel">
   <constructor-arg>
   <ref local="jdbctemp"/>
  </constructor-arg>
   </bean>
 
 <bean id="logincnt" class="com.jagan.spring.LoginController">
   <constructor-arg>
   <ref local="loginModel"/>
  </constructor-arg>
   </bean>

   <bean id="myurlmapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
     <property name="mappings">
     <props>
     <prop key = "/login.spring">logincnt</prop>
     </props>
   </property>
  </bean>

</beans>
</p>
EmployeeLogin.jsp

<html>
<body>
<form action="login.spring"><pre>
<br>user name:<input type="text" name="uname"/>
<br>
password:<input type="password" name="pass"/>
<br>
<input type="submit" value="LogIN">
</pre>
</form>
</body>
</html>
UserHome.jsp
<html>
<body>
<b>welcome</b>
user Name:<%=request.getParameter("uname")%>
</body>
</html>
Admin.jsp
<html>
<body>
<br>
Welcome to the AdminHome page
<%=request.getParameter("uname") %>
<br>
</body>
</html>
...................................................................................................................................................................
...................................................................................................................................................................
package com.spring.jagan.abstractvadiator;
import java.io.PrintWriter;
LoginController(validation):when extends with  AbstractCommandController it provides the below method
protected ModelAndView handle(HttpServletRequest req,
   HttpServletResponse res, Object command, BindException errors)
   throws Exception
LoginController.java
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
import javax.servlet.http.*;
public class LoginController extends AbstractCommandController
{

 LoginModel loginModel;

 public LoginController(LoginModel lm)
 {
  loginModel=lm;
 }

   
 /**
   * @ author jagan mohan paspula
   */
 protected ModelAndView handle(HttpServletRequest req,
   HttpServletResponse res, Object command, BindException errors)
   throws Exception {
  // TODO Auto-generated method stub
  String type = loginModel.validate((UserDetails)command);
  if(errors.hasErrors())
  {
  System.out.println("Errors in validation");
  //code to write the error message to client
  //this logic is used to demonstarate practillay the workflow
  //about the handle method returnin null
  PrintWriter out = res.getWriter();
  out.println("we have found some erors in the data submited by you:");
  out.println("<br>Total Number of errors  :<b>"+errors.getErrorCount()+"</br><br/>");
  out.println("The errors are associated with uname field are:<br/>");
  java.util.List<FieldError> errors_list =errors.getFieldErrors("uname");
  for(FieldError error:errors_list)
  out.println(error.getDefaultMessage()+"<br/>");
  out.println("<br>The errors are associated with pass field are:<br/>");
  errors_list =errors.getFieldErrors("pass");
  for(FieldError error:errors_list)
   out.println(error.getDefaultMessage()+"<br/>");
  return null;
  }
  if(type==null)
   return new ModelAndView("/employeelogin.jsp");
  else if(type.equals("admin"))
   return new ModelAndView("/AdminHome.jsp");
  else
   return new ModelAndView("/userHome.jsp");

 }
}

LoginModel.java

package com.spring.jagan.abstractvadiator;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
public class LoginModel {

 private JdbcTemplate jdbcTemplate;
 public LoginModel(JdbcTemplate jt)
 {
  jdbcTemplate = jt;
 }

  /**
   * @author jagan mohan paspula
   * @param uname
   * @param pass
   * @return
   */
 public String validate(UserDetails ud) {
  // TODO Auto-generated method stub
  try
  {
  return(String)jdbcTemplate.queryForObject("select type from userdeatils where username=\'"+ud.getUname()+"\' and userpass=\'"+ud.getPass()+"\'",String.class);
  }
  catch(EmptyResultDataAccessException e)
  {
   return null;
  }
   }
}
UserDeatilsValidator .java

package com.spring.jagan.abstractvadiator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
 *
 * @author jagan mohan paspula
 *
 */
public class UserDeatilsValidator implements Validator
{
 /**
  * @param Class
  */
 public boolean supports(Class c) {
  // TODO Auto-generated method stub
  return c.equals(UserDetails.class);
 
 }
/**
 * @param Object
 * @param Errors
 */
 public void validate(Object target, Errors errors) {
  // TODO Auto-generated method stub
  UserDetails ud=(UserDetails)target;
  //Rejects the given filed if is empty or contains only whitespace
  /*Note:The Object whose filed is being validated does not need to passed
   * becoz the 'erros' instance can resolve filed values by itself it will
   * usually hold an internal refrence to the target object
   *
   */
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "uname", "field.required","The user filed cant be empty");
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "pass", "field.required","The pass filed cant be empty");
  if(ud.getPass()!=null&&ud.getPass().equals("")&& ud.getPass().length()<5);
  {
   errors.rejectValue("pass","field.minlength",new Object[]{Integer.valueOf(5)},"The password conations minmum 5 character");
  }
 }
}

UserDetails .java
package com.spring.jagan.abstractvadiator;
public class UserDetails
{
String uname,pass;
public String getUname() {
 return uname;
}
public void setUname(String uname) {
 this.uname = uname;
}
public String getPass() {
 return pass;
}
public void setPass(String pass) {
 this.pass = pass;
}
}
Note:please follow the above UserHome.jsp and Admin.jsp
dsvalidator.xml
<p><?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Configuring DataSource -->
 <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName">
   <value>oracle.jdbc.driver.OracleDriver</value>
   </property>
   <property name="url">
   <value>jdbc:oracle:thin:@localhost:1521:orcl</value>
   </property>
   <property name="username">
   <value>scott</value>
   </property>
   <property name="password">
   <value>tiger</value>
   </property>
   </bean>
 
  <bean id="jdbctemp" class="org.springframework.jdbc.core.JdbcTemplate">
   <constructor-arg>
   <ref local="datasource"/>
  </constructor-arg>
   </bean>
<bean id="loginModel" class="com.spring.jagan.abstractvadiator.LoginModel">
   <constructor-arg>
   <ref local="jdbctemp"/>
  </constructor-arg>
   </bean>
 
 <bean id="logincnt" class="com.spring.jagan.abstractvadiator.LoginController">
   <constructor-arg>
   <ref local="loginModel"/>
  </constructor-arg>
  <property name="commandClass">
 <value type="java.lang.Class">com.spring.jagan.abstractvadiator.UserDetails</value>
   </property>
   <property name="commandName">
  <value>
  UserDetails
  </value>
   </property>
   <property name="validator">
 <bean class="com.spring.jagan.abstractvadiator.UserDeatilsValidator"/>
   </property>
   </bean>
    <bean id="myurlmapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
     <property name="mappings">
     <props>
     <prop key = "/login.spring">logincnt</prop>
     </props>
   </property>
  </bean>

</beans></p>