You are on page 1of 44

20

012

La
ara
a Te
ech
hnolog
gy
SPR
RING (ORM
(
M & MVC)
M
#102//12,2ndMain
n,5thCross,V
VenkateswaraCollegeRoaad,RamaiahG
Garden,
ChikkaAdugodi,Th
havarakere,B
Bangalore560029.
PhoneNo:08041310124

30/09
9/2012
2
1

LARATECHNOLOGY

LARATECHNOLOGY

Example 1:
Person.java:

package com.lara;
publicclassPerson
{
privateintid;
private String firstName;
private String lastName;
privateintage;
publicint getId() {
returnid;
}
publicvoid setId(int id) {
this.id = id;
}
public String getFirstName() {
returnfirstName;
}
publicvoid setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
returnlastName;
}
publicvoid setLastName(String lastName) {
this.lastName = lastName;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
}

2
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

Person.hbm.xml:
<hibernate-mappingpackage="com.lara">
<classname="Person"table="PERSON">
<idname="id"column="PERSON_ID"/>
<propertyname="firstName"/>
<propertyname="lastName"/>
<propertyname="age"/>
</class>
</hibernate-mapping>

Manager.java:
package com.lara;
import java.util.Properties;
import
import
import
import

org.hibernate.SessionFactory;
org.springframework.jdbc.datasource.DriverManagerDataSource;
org.springframework.orm.hibernate3.HibernateTemplate;
org.springframework.orm.hibernate3.LocalSessionFactoryBean;

publicclassManager
{
publicstaticvoid main(String[] args) throws Exception
{
DriverManagerDataSource dmds = new DriverManagerDataSource();
dmds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dmds.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
dmds.setUsername("system");
dmds.setPassword("great123");
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
lsfb.setDataSource(dmds);
lsfb.setMappingResources(newString[]{"com/lara/Person.hbm.xml"});
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
props.put("hibernate.show_sql", "true");
props.put("hibernate.hbm2ddl.auto", "create");
lsfb.setHibernateProperties(props);
lsfb.afterPropertiesSet();
3
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

HibernateTemplate template = new HibernateTemplate();


template.setSessionFactory((SessionFactory)lsfb.getObject());
template.afterPropertiesSet();
Person p1 = new Person();
p1.setId(100);
p1.setFirstName("abc");
p1.setLastName("xyz");
p1.setAge(22);
template.save(p1);
System.out.println("done");
}
}
Example 2:

Employee.java:

package com.lara;
publicclassEmployee
{
privateintid;
private String firstName;
private String lastName;;
private String emailId;
private String designation;
publicint getId() {
returnid;
}
publicvoid setId(int id) {
this.id = id;
}
public String getFirstName() {
returnfirstName;
}
publicvoid setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
returnlastName;
}
4
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

publicvoid setLastName(String lastName) {


this.lastName = lastName;
}
public String getEmailId() {
returnemailId;
}
publicvoid setEmailId(String emailId) {
this.emailId = emailId;
}
public String getDesignation() {
returndesignation;
}
publicvoid setDesignation(String designation) {
this.designation = designation;
}
}
Employee.hbm.xml
<hibernate-mappingpackage="com.lara">
<classname="Employee"table="Employee">
<idname="id"column="PERSON_ID"/>
<propertyname="firstName"/>
<propertyname="lastName"/>
<propertyname="emailId"/>
<propertyname="designation"/>
</class>
</hibernate-mapping>

EmployeeDAO.java:

package com.lara;
import org.springframework.orm.hibernate3.HibernateTemplate;
publicclass EmployeeDAO
{
private HibernateTemplate template;
5
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

publicvoid setTemplate(HibernateTemplate template)


{
this.template = template;
}
publicvoid save(Employee emp)
{
template.save(emp);
}
public Object load(Integer id)
{
returntemplate.load("com.lara.Employee", id);
}
publicvoid update(Employee emp)
{
template.update(emp);
}
}
beans.xml:
<beanid="dmds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName"
value="oracle.jdbc.driver.OracleDriver"/>
<propertyname="url"
value="jdbc:oracle:thin:@localhost:1521:XE"/>
<propertyname="username"
value="system"/>
<propertyname="password"
value="great123"/>
</bean>
<beanid="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

6
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

<propertyname="dataSource"
ref="dmds"/>
<propertyname="mappingResources">
<list>
<value>com/lara/Employee.hbm.xml</value>
</list>
</property>
<propertyname="hibernateProperties">
<props>
<propkey="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<propkey="hibernate.show_sql">true</prop>
<propkey="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<beanid="hibernateTemplate"
">

class="org.springframework.orm.hibernate3.HibernateTemplate
<propertyname="sessionFactory"
ref="mySessionFactory">
</property>
</bean>
<beanid="eDAO"
class="com.lara.EmployeeDAO">
<propertyname="template"
ref="hibernateTemplate"/>
</bean>

Manager.java:
7
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

package com.lara;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
publicclassManager
{
publicstaticvoid main(String[] args)
{
BeanFactory factory = new XmlBeanFactory(new
ClassPathResource("beans.xml"));
EmployeeDAO empDAO = (EmployeeDAO)factory.getBean("pDAO");
Employee emp = new Employee();
emp.setId(30);
emp.setFirstName("pilo");
emp.setLastName("kio");
emp.setEmailId("abc@xyz.com");
empDAO.save(emp);
System.out.println("done");
}
}
Example 3:
Student.java:

package com.lara;
publicclassStudent
{
privateintid;
private String firstName;
private String lastName;
privateintage;
publicint getId() {
returnid;
}
publicvoid setId(int id) {
this.id = id;
}
public String getFirstName() {
returnfirstName;
}
publicvoid setFirstName(String firstName) {
8
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

this.firstName = firstName;
}
public String getLastName() {
returnlastName;
}
publicvoid setLastName(String lastName) {
this.lastName = lastName;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
}
Student.hbm.xml:

<hibernate-mappingpackage="com.lara">
<classname="Student"table="Student">
<idname="id"column="PERSON_ID"/>
<propertyname="firstName"/>
<propertyname="lastName"/>
<propertyname="age"/>
</class>
</hibernate-mapping>
StudentDAO.java:

package com.lara;
import java.sql.SQLException;
import java.util.List;
import
import
import
import
import

org.hibernate.Criteria;
org.hibernate.HibernateException;
org.hibernate.Session;
org.springframework.orm.hibernate3.HibernateCallback;
org.springframework.orm.hibernate3.HibernateTemplate;

9
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

publicclass StudentDAO
{
private HibernateTemplate template;
publicvoid setTemplate(HibernateTemplate template)
{
this.template = template;
}
publicvoid save(Student s)
{
template.save(s);
}
public Object load(Integer id)
{
returntemplate.load(Student.class, id);
}
public List<Student> read()
{
HibernateCallback action = new HibernateCallback()
{
@Override
public Object doInHibernate(Session arg0)
throws HibernateException,SQLException
{
Criteria ctr =
arg0.createCriteria(com.lara.Student.class);
List<Student> list = ctr.list();
return list;
}
};
return (List<Student>)template.execute(action);
}
}
config.xml:

<beanid="dmds"

10
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName"
value="oracle.jdbc.driver.OracleDriver"/>
<propertyname="url"
value="jdbc:oracle:thin:@localhost:1521:XE"/>
<propertyname="username"
value="system"/>
<propertyname="password"
value="great123"/>
</bean>
<beanid="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<propertyname="dataSource"
ref="dmds"/>
<propertyname="mappingResources">
<list>
<value>com/lara/Student.hbm.xml</value>
</list>
</property>
<propertyname="hibernateProperties">
<props>
<propkey="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<propkey="hibernate.show_sql">true</prop>
<propkey="hibernate.hbm2ddl.auto">create</prop>
11
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

</props>
</property>
</bean>
<beanid="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<propertyname="sessionFactory"
ref="mySessionFactory">
</property>
</bean>
<beanid="sDAO"
class="com.lara.StudentDAO">
<propertyname="template"
ref="hibernateTemplate"/>
</bean>
Manager.java:

package com.lara;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
publicclass Manager
{
publicstaticvoid main(String[] args)
{
BeanFactory factory = new XmlBeanFactory(new
ClassPathResource("config.xml"));
StudentDAO sDAo = (StudentDAO)factory.getBean("sDAO");
Student s1 = new Student();
s1.setId(13);
s1.setFirstName("abc");
s1.setLastName("xyz");
s1.setAge(22);
sDAo.save(s1);
12
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

System.out.println("done");
}
}

Spring Web MVC


Example 1:
web.xml:
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

controller-servlet.xml:
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<prop key="hello.do">hello</prop>
</props>
</property>
</bean>
hello.jsp:
<a href="hello.do">call to Spring</a>
13
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

controller-servlet.xml:
<bean id="hello"
class="com.lara.HelloController"/>

HelloController.java:
package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
publicclass HelloController implements Controller
{
@Override
publicModelAndView handleRequest(
HttpServletRequest arg0,
HttpServletResponse arg1)
throws Exception
{
System.out.println("handleRequest");
ModelAndView mav = new ModelAndView("message.jsp");
}

return mav;

message.jsp:
Hello to All

Example 2:
testForm.jsp:

<formaction="test.do">
14
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

Parameter1:
<inputtype="text"
name="param1"><br/>
Parameter2:
<inputtype="text"
name="param2"><br/>
<inputtype="submit"
value="Submit">
</form>

controller-servlet.xml:

<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<prop key="test.do">test</prop>
</props>
</property>
</bean>

TestController.java:
package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
publicclass TestController implements Controller
{
@Override
public ModelAndView handleRequest(
HttpServletRequest arg0,
HttpServletResponse arg1)
15
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

throws Exception
{
String s1 =
arg0.getParameter("param1");
String s2 =
arg0.getParameter("param2");
System.out.println(s1);
System.out.println(s2);
ModelAndView mav = new ModelAndView("success.jsp");
return mav;
}
}
success.jsp:
This is From sucess.jsp Page

controller-servlet.xml:
<bean id="test"
class="com.lara.TestController"/>

Example 3:
login.jsp:
<formaction="login.do">
${msg}</br>
UserName:
<inputtype="text"
name="username"><br/>
Password:
<inputtype="password"
name="password"><br/>
<inputtype="submit"
value="Submit">
</form>
16
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

controller-servlet.xml:
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<prop key="login.do">login</prop>
</props>
</property>
</bean>
<bean id="login"
class="com.lara.LoginController"/>

LoginController.java:
package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
publicclass LoginController implements Controller
{
@Override
public ModelAndView handleRequest(
HttpServletRequest arg0,
HttpServletResponse arg1)
throws Exception
{
String un =
arg0.getParameter("username");
String pw =
arg0.getParameter("password");
ModelAndView mav =
new ModelAndView();
17
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

if("lara".equals(un) &&
"rst".equals(pw))
{
mav.addObject("msg", "Login page is very success");
mav.setViewName("loginSuccess.jsp");
}
else
{
mav.addObject("msg", "The UserName or Password
Which you have entered is Wrong Pls Try Again");
mav.setViewName("login.jsp");
}
return mav;
}
}
loginSuccess.jsp:

${msg}<br/>

Example 4:
reg.jsp:
${msg}
<formaction="registration.do">
First Name:
<inputtype='text'
name='firstName'/></br>
Last Name:
<inputtype='text'
name='lastName'/></br>
<inputtype='submit'
value='submit'/>
</form>

controller-servlet.xml:
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
18
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

<props>
<prop key="registration.do">registration</prop>
</props>
</bean>

</property>

<bean id="registration"
class="com.lara.RegistrationController"/>

RegistrationController.java:
package com.lara;
import javax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
publicclass RegistrationController implements Controller
{
@Override
public ModelAndView handleRequest(
HttpServletRequest arg0,
HttpServletResponse arg1)
throws Exception
{
String fName =
arg0.getParameter("firstName");
String lName =
arg0.getParameter("lastName");
System.out.println(fName);
System.out.println(lName);
ModelAndView mav =
new ModelAndView();
19
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

mav.addObject("obj1", fName);
mav.addObject("obj2", lName);
mav.setViewName("regSuccess.jsp");
return mav;
}
}
regSuccess.jsp:

${obj1}</br>
${obj2}</br>

Example 5:
Web.xml:
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

applicationContext.xml:
<beanid="messageSource"
>

class="org.springframework.context.support.ResourceBundleMessageSource"

<propertyname="basename"value="messages"/>
20
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

</bean>

messages.properties(develop one properties file in src folder)

index.jsp:
<a href="login.do">Login</a></br>
<a href="reg.do">Registraion</a></br>

controller-servlet.xml:
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<propkey="login.do">loginSettings</prop>
</props>
</property>
</bean>
<beanid="loginSettings"
class="com.lara.login.LoginController">
<propertyname="formView"
value="login.jsp"/>
<propertyname="commandClass"
value="com.lara.login.LoginForm"/>
<propertyname="commandName"
value="loginForm"/>
<propertyname="validator"
ref="loginValidator"/>
</bean>
<beanid="loginValidator"
class="com.lara.login.LoginValidator"/>
login.jsp:
<%@taglibprefix="c"
uri="http://www.springframework.org/tags"%>
<%@taglibprefix="f"
uri="http://www.springframework.org/tags/form"%>
<f:formcommandName="loginForm">
21
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

<c:messagecode="loginForm.username"/>
<c:bindpath="loginForm.username">
<inputtype='text'
name='username'
value='${status.value}'/>
${status.errorMessage }
</c:bind></br>
<c:messagecode="loginForm.password"/>
<c:bindpath="loginForm.password">
<inputtype='password'
name='password'
value='${status.value}'/>
${status.errorMessage }
</c:bind></br>
<inputtype='submit'value='submit'/>
</f:form>

messages.properties:
loginForm.username=Username
loginForm.password=Password
LoginForm.java:
package com.lara.login;
publicclass LoginForm
{
private String username;
private String password;
public String getUsername() {
returnusername;
}
publicvoid setUsername(String username) {
this.username = username;
}
public String getPassword() {
returnpassword;
}
publicvoid setPassword(String password) {
this.password = password;
}
}
LoginValidator.java:
22
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

package com.lara.login;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
publicclass LoginValidator implements Validator
{
@Override
publicboolean supports(Class arg0)
{
return arg0.equals(LoginForm.class);
}
@Override
publicvoid validate(Object arg0,
Errors arg1)
{
LoginForm login = (LoginForm) arg0;
String s1 = login.getUsername();
if(s1 == null || s1.length() == 0)
{
arg1.rejectValue("username",
"loginForm.username.required", "Username is mandatory");
}
String s2 = login.getPassword();
if(s2 == null || s2.length() == 0)
{
arg1.rejectValue("password",
"loginForm.password.required", "Password is mandatory");
}
}
}
LoginController.java:
package com.lara.login;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
publicclass LoginController extends SimpleFormController
{
@Override
protected ModelAndView onSubmit(
Object command)
throws Exception
{
23
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

LoginForm login =
(LoginForm) command;
String un = login.getUsername();
String pw = login.getPassword();
ModelAndView mav =
new ModelAndView();
mav.addObject("username", un);
mav.addObject("password", pw);
mav.setViewName("success.jsp");
return mav;
}
}
success.jsp:
${username}</br>
${password}</br>

Example 6:
controller-servlet.xml
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<propkey="reg.do">regSettings</prop>
</props>
</property>
</bean>
<beanid="regSettings"
class="com.lara.RegistrationController">
<propertyname="formView"
value="reg.jsp"/>
<propertyname="commandClass"
value="com.lara.RegForm"/>
<propertyname="commandName"
value="regForm"/>
<propertyname="validator"
ref="regValidator"/>
24
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

</bean>
<beanid="regValidator"
class="com.lara.RegValidator"/>

reg.jsp:
<%@taglibprefix="c"
uri="http://www.springframework.org/tags"%>
<%@taglibprefix="f"
uri="http://www.springframework.org/tags/form"%>
<f:formcommandName="regForm">
<c:messagecode="firstName"/>
<c:bindpath="regForm.firstName">
<inputtype='text'
name='firstName'
value='${status.value}'/>
${status.errorMessage}
</c:bind></br>
<c:messagecode="lastName"/>
<c:bindpath="regForm.lastName">
<inputtype='text'
name='lastName'
value='${status.value}'/>
${status.errorMessage}
</c:bind></br>
<inputtype='submit'value='submit'/>
</f:form>

messages.properties:
firstName=FirstName
lastName=LastName

RegForm.java:
package com.lara;
publicclass RegForm
{
private String firstName;
private String lastName;
public String getFirstName() {
returnfirstName;
}
publicvoid setFirstName(String firstName) {
this.firstName = firstName;
}
25
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

public String getLastName() {


returnlastName;
}
publicvoid setLastName(String lastName) {
this.lastName = lastName;
}
}
RegValidator.java:
package com.lara;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
publicclass RegValidator implements Validator
{
@Override
publicboolean supports(Class arg0)
{
return arg0.equals(RegForm.class);
}
@Override
publicvoid validate(Object arg0,
Errors arg1)
{
RegForm reg = (RegForm) arg0;
String fName = reg.getFirstName();
if(fName == null || fName.length() == 0)
{
arg1.rejectValue("firstName", "firstName.required", "First Name
is mandatory");
}
String lName = reg.getLastName();
if(lName == null || lName.length() == 0)
{
arg1.rejectValue("lastName", "lastName.required", "Last Name
is mandatory");
}
}
}
RegistrationController.java:
26
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

package com.lara;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
publicclass RegistrationController extends SimpleFormController
{
@Override
protected ModelAndView onSubmit(
Object command)
throws Exception
{
RegForm reg = (RegForm) command;
System.out.println(reg.getFirstName());
System.out.println(reg.getLastName());
ModelAndView mav =
new ModelAndView();
mav.setViewName("regSuccess.jsp");
return mav;
}
}
regSuccess.jsp:
success

Example 7:
web.xml:

<servlet>
<servlet-name>application</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>application</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>

<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>

27
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

</listener>

applicationContext.xml:
<beanid="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
>
<propertyname="basename"
value="app.messages"/>
</bean>

messages.properties(develop one properties file in src/app folder)


WebContent:
index.jsp:
<ahref='test.do'>Test Request</a></br>
<ahref='add.do'>Add</a></br>
<ahref="hello.do?abc=add">Adding</a><br>
<ahref="hello.do?abc=list">List</a><br>
<ahref="hello.do?abc=delete">Delete</a><br>
<ahref="reg.do">Registration</a></br>
application-servlet.xml
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<propkey="test.do">testSettings</prop>
</props>
28
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

</property>
</bean>
<beanid="testSettings"
class="com.lara.TestController">
<propertyname="formView"
value="test"/>
<propertyname="commandClass"
value="com.lara.TestForm"/>
<propertyname="commandName"
value="testForm"/>
<propertyname="validator"
ref="testValidator"/>
</bean>
<beanid="testValidator"
class="com.lara.TestValidator"/>
<beanid="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<propertyname="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<propertyname="prefix"
value="/WEB-INF/jsp/"/>
<propertyname="suffix"
value=".jsp"/>
</bean>
<beanid="ex-maps"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionRes
olver">
<propertyname="exceptionMappings">
<props>
<propkey="java.lang.NullPointerException">
error
</prop>
<propkey="java.lang.ClassCastException">
error1
</prop>
</props>
</property>
</bean>
<beanid="multipartResolver"
lver">

class="org.springframework.web.multipart.commons.CommonsMultipartReso

<propertyname="maxUploadSize"
value="100000"/>
29
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

</bean>
WEB-INF(jsp):
error.jsp:
from error.jsp</br>
${exception}
error1.jsp:
from error1.jsp</br>
${exception}
test.jsp:
<%@taglibprefix="core"
uri="http://www.springframework.org/tags"%>
<%@taglibprefix="form"
uri="http://www.springframework.org/tags/form"%>
<core:messagecode="title"/>
<form:formcommandName="testForm"enctype="multipart/form-data">
<core:messagecode="param1"/>
<core:bindpath="testForm.param1">
<inputtype='text'
name='param1'
value='${status.value}'/>
${status.errorMessage}
</core:bind></br>
<core:messagecode="param2"/>
<core:bindpath="testForm.param2">
<inputtype='text'
name='param2'
value='${status.value}'/>
${status.errorMessage}
</core:bind></br>
<core:messagecode="resume"/>
<core:bindpath="testForm.resume">
<inputtype='file'
name='resume'
value='${status.value}'/>
${status.errorMessage}
</core:bind></br>
30
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

<inputtype='submit'value='submit'/>
</form:form>
messages.properties:
title=TestApplication
param1=Parameter1
param2=Parameter2
resume=Resume
TestForm.java:
package com.lara;
import org.springframework.web.multipart.MultipartFile;
publicclass TestForm
{
private String param1;
private String param2;
private MultipartFile resume;

publicMultipartFile getResume() {
returnresume;
}
publicvoid setResume(MultipartFile resume) {
this.resume = resume;
}
public String getParam1() {
returnparam1;
}
publicvoid setParam1(String param1) {
this.param1 = param1;
}
public String getParam2() {
returnparam2;
}
publicvoid setParam2(String param2) {
this.param2 = param2;
}
31
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

}
TestValidator.java:
package com.lara;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;
publicclass TestValidator implements Validator
{
@Override
publicboolean supports(Class arg0)
{
return arg0.equals(TestForm.class);
}
@Override
publicvoid validate(Object arg0,
Errors arg1)
{
TestForm test = (TestForm) arg0;
String p1 = test.getParam1();
if(p1 == null || p1.length() == 0)
{
arg1.rejectValue("param1", "param1.required", "");
}
String p2 = test.getParam2();
if(p2 == null || p2.length() == 0)
{
arg1.rejectValue("param2", "param2.required", "");
}
MultipartFile f1 = test.getResume();
String fileName = f1.getOriginalFilename();
if(fileName == null || fileName.length() == 0)
{
arg1.rejectValue("resume", "resume.required", "");
}
}
}
messages.properties:
32
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

param1.required=Parameter1isrequiredone.
param2.required=Parameter2isrequiredone.
resume.required=Resumeisrequiredone.

TestController.java:
package com.lara;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
publicclass TestController extends SimpleFormController
{
@Override
protected ModelAndView onSubmit(
Object command)
throws Exception
{
TestForm test = (TestForm) command;
String p1 = test.getParam1();
String p2 = test.getParam2();
System.out.println(p1);
System.out.println(p2);
MultipartFile resume =
test.getResume();
byte x[] = resume.getBytes();
System.out.println(x.length);
ModelAndView mav =
new ModelAndView();
mav.setViewName("success");
return mav;
}

success.jsp:
This is a success</br>
<ahref='index.jsp'>Again</a>
33
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

Example 8:
application-servlet.xml
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<propkey="add.do">addSettings</prop>
</props>
</property>
</bean>
<beanid="addSettings"
class="com.lara.AddController">
<propertyname="formView"
value="add"/>
<propertyname="commandClass"
value="com.lara.AddForm"/>
<propertyname="commandName"
value="addForm"/>
</bean>
add.jsp
<%@taglibprefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglibprefix="core"
uri="http://www.springframework.org/tags"%>
<%@taglibprefix="form"
uri="http://www.springframework.org/tags/form"%>
<form:formcommandName="addForm">
First Name:
<core:bindpath="addForm.firstName">
<inputtype='text'
name='firstName'
value='${status.value}'/>
</core:bind></br>
Last Name:
<core:bindpath="addForm.lastName">
<inputtype='text'
34
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

name='lastName'
value='${status.value}'/>
</core:bind></br>
Skills:
<core:bindpath="addForm.skills">
<c:forEachitems="${skills}"
var="skill">
<inputtype='checkbox'
name='skills'
value='${skill}'/>
${skill} &nbsp;&nbsp;
</c:forEach>
</core:bind></br>
<inputtype='submit'
value='submit'/>
</form:form>
AddForm.java:
package com.lara;
publicclass AddForm
{
private String firstName;
private String lastName;
private String skills[];
public String getFirstName() {
returnfirstName;
}
publicvoid setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
returnlastName;
}
publicvoid setLastName(String lastName) {
this.lastName = lastName;
}
public String[] getSkills() {
returnskills;
}
publicvoid setSkills(String[] skills) {
this.skills = skills;
}
35
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

}
AddController.java:
package com.lara;
import
import
import
import

java.util.ArrayList;
java.util.Arrays;
java.util.HashMap;
java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
publicclass AddController extends SimpleFormController
{
@Override
protected Map referenceData(HttpServletRequest request)
throws Exception
{
System.out.println("referenceData");
Map map = new HashMap();
ArrayList list =
new ArrayList();
list.add("C");
list.add("C++");
list.add("Java");
list.add("Oracle");
map.put("skills", list);
return map;
}
@Override
protected Object formBackingObject(
HttpServletRequest request)
throws Exception
{
System.out.println("formBackingObject");
AddForm form = new AddForm();
form.setFirstName("abc");
return form;
}
@Override
protected ModelAndView onSubmit(
36
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

Object command)
throws Exception
{
System.out.println("onsubmit");
AddForm add = (AddForm) command;
System.out.println(add.getFirstName());
System.out.println(add.getLastName());
System.out.println(Arrays.toString(add.getSkills()));
returnnew ModelAndView("success");
}
}
success.jsp:
This is a success</br>
<ahref='index.jsp'>Again</a>
Example 9:
application-servlet.xml:
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<propkey="hello.do">helloSettings</prop>
</props>
</property>
</bean>
<beanid="helloSettings"
class="com.lara.HelloController">
<propertyname="methodNameResolver"
ref="paramResolver"/>
</bean>
<beanid="paramResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodN
ameResolver">
<propertyname="paramName"
value="abc"/>
</bean>
37
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

HelloController.java:
package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.multiaction.MultiActionController;
publicclass HelloController extends MultiActionController
{
public ModelAndView add(HttpServletRequest arg0,
HttpServletResponse arg1)
throws Exception
{
ModelAndView mav =
new ModelAndView("success");
mav.addObject("type","add");
System.out.println("add called");
return mav;
}
public ModelAndView list(HttpServletRequest arg0,
HttpServletResponse arg1)
throws Exception
{
ModelAndView mav =
new ModelAndView("success");
mav.addObject("type","list");
System.out.println("list called");
returnmav;
}
public ModelAndView delete(HttpServletRequest arg0,
HttpServletResponse arg1)
throws Exception
{
ModelAndView mav =
new ModelAndView("success");
mav.addObject("type","delete");
System.out.println("delete called");
return mav;
}
}
38
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

success.jsp:
This is a success</br>
<ahref='index.jsp'>Again</a>

Example 9:
application-servlet.xml
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<propkey="reg.do">regSettings</prop>
</props>
</property>
</bean>
<beanid="regSettings"
class="com.lara.RegistrationController">
<propertyname="commandClass"
value="com.lara.RegistrationForm"/>
<propertyname="commandName"
value="registrationForm"/>
<propertyname="pages">
<list>
<value>reg0</value>
<value>reg1</value>
</list>
</property>
<propertyname="sessionForm"
value="true"/>
</bean>
WEB-INF(jsp folder):
reg0.jsp:
<%@taglibprefix="core"
uri="http://www.springframework.org/tags"%>
<%@taglibprefix="form"
39
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

uri="http://www.springframework.org/tags/form"%>
<form:formcommandName="registrationForm">
First Name:
<core:bindpath="registrationForm.firstName">
<inputtype='text'
name='firstName'
value='${status.value}'/>
${status.errorMessage}
</core:bind></br>
Last Name:
<core:bindpath="registrationForm.lastName">
<inputtype='text'
name='lastName'
value='${status.value}'/>
${status.errorMessage}
</core:bind></br>
<inputtype="submit"
value="Submit"
name="_target1">
</form:form>
WEB-INF(jsp folder):
reg1.jsp:
<%@taglibprefix="core"
uri="http://www.springframework.org/tags"%>
<%@taglibprefix="form"
uri="http://www.springframework.org/tags/form"%>
<form:formcommandName="registrationForm">
Age:
<core:bindpath="registrationForm.age">
<inputtype='text'
name='age'
value='${status.value}'/>
${status.errorMessage}
</core:bind></br>
Email:
<core:bindpath="registrationForm.email">
<inputtype='text'
name='email'
value='${status.value}'/>
${status.errorMessage}
</core:bind></br>
40
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

<inputtype="submit"
value="Submit"
name="_finish">
</form:form>
RegistrationForm.java:
package com.lara;
publicclass RegistrationForm
{
private String firstName;
private String lastName;
privateintage;
private String email;
public String getFirstName() {
returnfirstName;
}
publicvoid setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
returnlastName;
}
publicvoid setLastName(String lastName) {
this.lastName = lastName;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
public String getEmail() {
returnemail;
}
publicvoid setEmail(String email) {
this.email = email;
}
}
RegistrationController.java:
41
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

package com.lara;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
import
import
import

org.springframework.validation.BindException;
org.springframework.validation.Errors;
org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.mvc.AbstractWizardFormController;

publicclass RegistrationController extends AbstractWizardFormController


{
@Override
protected ModelAndView processFinish(
HttpServletRequest arg0,
HttpServletResponse arg1,
Object arg2,
BindException arg3)
throws Exception
{
RegistrationForm reg =
(RegistrationForm) arg2;
System.out.println(reg.getFirstName());
System.out.println(reg.getLastName());
System.out.println(reg.getAge());
System.out.println(reg.getEmail());
returnnew ModelAndView("success");
}
@Override
protectedvoid validatePage(Object command,
Errors errors,
int page)
{
RegistrationForm reg =
(RegistrationForm) command;
if(page == 0)
{
String fn = reg.getFirstName();
if(fn == null ||
fn.length() == 0)
{
errors.rejectValue("firstName", "", "First Name is
Mandatory");
}
String ln = reg.getLastName();
if(ln == null ||
42
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

ln.length() == 0)
{
Mandatory");

errors.rejectValue("lastName", "", "Last Name is

}
}
if(page == 1)
{
int age = reg.getAge();
if(age == 0 ||
Integer.toString(age).length() == 0)
{
errors.rejectValue("age", "", "Age is Mandatory");
}
String email = reg.getEmail();
if(email == null ||
email.length() == 0)
{
errors.rejectValue("email", "", "Email is
Mandatory");
}
}
}
}
success.jsp:
This is a success</br>
<ahref='index.jsp'>Again</a>
Example 10:
messageResources.properties:
msg=This is From Default Bundle
messageResources_aus_AUS.properties:
msg=This is From Aus Bundle
messageResources_en_UK.properties:
msg=This is From UK Bundle
messageResources_fr_FR.properties:
43
www.laratechnology.com08041310124

LARATECHNOLOGY

LARATECHNOLOGY

msg=This is From French Bundle


I18N.java:
package com.lara;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Scanner;
publicclass I18N
{
publicstaticvoid main(String[] args)
{
String country = null;
String language = null;
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter Language code:");
language = sc.next();
System.out.println("Please Enter Country code:");
country = sc.next();
Locale locale = new Locale(language, country);
ResourceBundle rb = null;
rb = ResourceBundle.getBundle("messageResources", locale);
String message = rb.getString("msg");
System.out.println(message);
}
}

44
www.laratechnology.com08041310124

You might also like