Saturday, 19 May 2012
Wednesday, 16 May 2012
JSF + SPRING + JDBC TEMPLATE
CustomerBo.java
package com.jagan.customer.bo;
import java.util.List;
import com.jagan.CustomerBean;
public interface CustomerBo{
void addCustomer(String name);
}
CustomerBoImpl .java
package com.jagan.customer.bo.impl;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.faces.context.FacesContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;
import com.jagan.CustomerBean;
import com.jagan.customer.bo.CustomerBo;
import com.jagan.customer.dao.CustomerDao;
public class CustomerBoImpl implements CustomerBo{
private JdbcTemplate jdbcTemplate;
public CustomerBoImpl(JdbcTemplate jt)
{
jdbcTemplate =jt;
}
public void addCustomer( final String name)
{
// TODO Auto-generated method stub
jdbcTemplate.update("insert into customer values(?)",new PreparedStatementSetter(){
public void setValues(PreparedStatement ps)throws SQLException
{
ps.setString(1, name);
}
});
}
}
CustomerBean .java
package com.jagan;
import java.io.Serializable;
import java.util.List;
import javax.faces.context.FacesContext;
import org.springframework.beans.BeanUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;
import com.jagan.customer.bo.CustomerBo;
import com.jagan.customer.bo.impl.CustomerBoImpl;
import com.jagan.customer.dao.CustomerDao;
public class CustomerBean implements Serializable{
//DI via Spring
CustomerBo custmerService;
public CustomerBo getCustmerService() {
return custmerService;
}
public void setCustmerService(CustomerBo custmerService) {
this.custmerService = custmerService;
}
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String addCustomers()
{
/*
CustomerBo customerBO = (CustomerBo) FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()).getBean("custmerService");
//copy customerform to model
BeanUtils.copyProperties(customer, customer);*/
String name = getName();
System.out.println("Name:"+name);
if(name != null){
custmerService.addCustomer(name);
}
clearForm();
return "";
}
//clear form values
private void clearForm(){
setName("");
}
}
default.xhtml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <head> <h1>JSF 2.0 + Spring + JDBC Example</h1> <h2>Add New Customer</h2> </head> <body> <h:form> Name : <h:inputText id="name" value="#{customer.name}" size="20" required="true" label="Name">
</h:inputText> <h:message for="name" style="color:red" /> <h:commandButton value="Submit" action="#{customer.addCustomers}" /> </h:form> </body> </html>
application-context.xml :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<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="custmerService" class="com.jagan.customer.bo.impl.CustomerBoImpl">
<constructor-arg>
<ref local="jdbctemp"/>
</constructor-arg>
</bean>
</beans>
faces-config.xml
..............
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
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-facesconfig_2_0.xsd"
version="2.0">
<application>
<!--
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
-->
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<managed-bean>
<managed-bean-name>customer</managed-bean-name>
<managed-bean-class>com.jagan.CustomerBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>custmerService</property-name>
<value>#{custmerService}</value>
</managed-property>
</managed-bean>
</faces-config>
we
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="2.5">
<display-name>JavaServerFaces</display-name>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<!-- Add Support for Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- Change to "Production" when you are ready to deploy -->
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>default.xhtml</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<!--Tomcat 5 Workaround: Listener used to initialize JSF on startup-->
<!--Remove comment tags to enable listener.
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
-->
<!--Tomcat 5 Workaround: Listener implementation to handle web application lifecycle event-->
<!--Remove comment tags to enable listener.
<listener>
<listener-class>com.sun.faces.application.WebappLifecycleListener</listener-class>
</listener>
-->
</web-app>
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>
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>
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>
Wednesday, 23 November 2011
Sample web project
COMMING SOON
Admin.jsp
Registration.jsp
Login.Jsp
Employee search .jsp
Employee File upload.jsp
Student Registartion.jsp
Student Search.jsp
Student File Upload.jsp
Admin.jsp
Registration.jsp
Login.Jsp
Employee search .jsp
Employee File upload.jsp
Student Registartion.jsp
Student Search.jsp
Student File Upload.jsp
Saturday, 19 November 2011
CASE STUDIES ON SESSION MANAGEMENT
COMMING SOON
Subscribe to:
Posts (Atom)