Spring
1. Hello World Program
HelloWorld.java
package com.kodnest;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
MainApp.java
package com.kodnest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
2. How to create Spring applcation.
Create Java Class
package com.kodnest;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayInfo(){
System.out.println("Hello: "+name);
}
}
Create XML File
<?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-3.0.xsd">
<bean id="studentbean" class="com.kodnest.Student">
<property name="name" value="Raj Mehta"></property>
</bean>
</beans>
Create test class
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}
Load jar files required for spring framework
3. Dependency Injection using constructor.
Employee.java
package com.kodnest;
public class Employee {
private int id;
private String name;
public Employee() {System.out.println("Class Created");}
public Employee(int id) {this.id = id;}
public Employee(String name) { this.name = name;}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
void show(){
System.out.println(id+" "+name);
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="e" class="com.kodnest.Employee">
<constructor-arg value="10" type="int"></constructor-arg>
</bean>
</beans>
TestSample.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class TestSample {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
Output: 10 null
4. Constructor Injection with Dependent Object.
Address.java
package com.kodnest;
public class Address {
private String city;
private String state;
private String country;
public Address(String city, String state, String country) {
super();
this.city = city;
this.state = state;
this.country = country;
}
public String toString(){
return city+" "+state+" "+country;
}
}
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private Address address;//Aggregation
public Student() {System.out.println("Student class Created");}
public Student(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="a1" class="com.kodnest.Address">
<constructor-arg value="Bengaluru"></constructor-arg>
<constructor-arg value="Karanataka"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>
<bean id="e" class="com.kodnest.Student">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="Raj"></constructor-arg>
<constructor-arg>
<ref bean="a1"/>
</constructor-arg>
</bean>
</beans>
TestSample.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class TestSample {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Student s=(Student)factory.getBean("e");
s.show();
}
}
5. Constructor Injection with collection.
Question.java
package com.kodnest;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<String> answers;
public Question() {}
public Question(int id, String name, List<String> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<String> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="q" class="com.kodnest.Question">
<constructor-arg value="111"></constructor-arg>
<constructor-arg value="How are you?"></constructor-arg>
<constructor-arg>
<list>
<value>I am good.</value>
<value>I am fine</value>
</list>
</constructor-arg>
</bean>
</beans>
TestSample.java
package com.kodenst;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class TestSample {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6. Constructor Injection with Map
Question.java
package com.kodnest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map<String,String> answers;
public Question() {}
public Question(int id, String name, Map<String, String> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println("question id:"+id);
System.out.println("question name:"+name);
System.out.println("Answers....");
Set<Entry<String, String>> set=answers.entrySet();
Iterator<Entry<String, String>> itr=set.iterator();
while(itr.hasNext()){
Entry<String,String> entry=itr.next();
System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());
}
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="q" class="com.kodnest.Question">
<constructor-arg value="11"></constructor-arg>
<constructor-arg value="How are you?"></constructor-arg>
<constructor-arg>
<map>
<entry key="I am good" value="Raj Mehta"></entry>
<entry key="I am fine" value="Karan"></entry>
</map>
</constructor-arg>
</bean>
</beans>
TestSample.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class TestSample {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
7. Program to Inhert Bean in Spring
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private Address address;
public Student() {}
public Student(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Student(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
void show(){
System.out.println(id+" "+name);
System.out.println(address);
}
}
School.java
package com.kodnest;
public class School {
private String addressLine1,city,state,country;
public School(String addressLine1, String city, String state, String country) {
super();
this.addressLine1 = addressLine1;
this.city = city;
this.state = state;
this.country = country;
}
public String toString(){
return addressLine1+" "+city+" "+state+" "+country;
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="e1" class="com.kodenst.Employee">
<constructor-arg value="101"></constructor-arg>
<constructor-arg value="Raj"></constructor-arg>
</bean>
<bean id="address1" class="com.kodnest.Address">
<constructor-arg value="22,Lake View"></constructor-arg>
<constructor-arg value="Bengaluru"></constructor-arg>
<constructor-arg value="KA"></constructor-arg>
<constructor-arg value="USA"></constructor-arg>
</bean>
<bean id="e2" class="com.kodnest.Employee" parent="e1">
<constructor-arg ref="address1"></constructor-arg>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SampleTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Student s1=(Student)factory.getBean("e2");
s1.show();
}
}
8. Program for Dependency Injection using setter method.
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
void display(){
System.out.println(id+" "+name+" "+city);
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="obj" class="com.kodnest.Employee">
<property name="id">
<value>4</value>
</property>
<property name="name">
<value>Raj</value>
</property>
<property name="city">
<value>Bengaluru</value>
</property>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class SampleTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Student e=(Student)factory.getBean("obj");
s.display();
}
}
9. Program for Setter Injection with Dependent Object.
School.java
package com.kodnest;
public class School {
private String addressLine1,city,state,country;
//getters and setters
public String toString(){
return addressLine1+" "+city+" "+state+" "+country;
}
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private Address address;
//setters and getters
void displayInfo(){
System.out.println(id+" "+name);
System.out.println(address);
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="address1" class="com.kodnest.Address">
<property name="addressLine1" value="31,Lake View"></property>
<property name="city" value="Bengaluru"></property>
<property name="state" value="KA"></property>
<property name="country" value="India"></property>
</bean>
<bean id="obj" class="com.kodnest.Employee">
<property name="id" value="1"></property>
<property name="name" value="Raj Mehta"></property>
<property name="address" ref="address1"></property>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SampleTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Student s=(Student)factory.getBean("obj");
s.displayInfo();
}
}
10. Program for Setter Injection using Collection.
Question.java
package com.kodnest;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<String> answers;
//setters and getters
public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<String> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="q" class="com.kodnest.Question">
<property name="id" value="1"></property>
<property name="name" value="How are you?"></property>
<property name="answers">
<list>
<value>I am good.</value>
<value>I am fine.</value>
</list>
</property>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SampleTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
11. Program for Setter Injection using Map.
Question.java
package com.kodnest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map<String,String> answers;
//getters and setters
public void displayInfo(){
System.out.println("question id:"+id);
System.out.println("question name:"+name);
System.out.println("Answers....");
Set<Entry<String, String>> set=answers.entrySet();
Iterator<Entry<String, String>> itr=set.iterator();
while(itr.hasNext()){
Entry<String,String> entry=itr.next();
System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());
}
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="q" class="com.kodnest.Question">
<property name="id" value="1"></property>
<property name="name" value="How are you?"></property>
<property name="answers">
<map>
<entry key="I am fine" value="Raj Mehta"></entry>
<entry key="I am good" value="Karan"></entry>
</map>
</property>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SampleTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
12. Program for Autowiring.
B.java
package org.kodnest;
public class B {
B(){System.out.println("b is created");}
void print(){System.out.println("hello b");}
}
A.java
package org.kodnest;
public class A {
B b;
A(){System.out.println("a is created");}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
void print(){System.out.println("hello a");}
void display(){
print();
b.print();
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="b" class="org.kodnest.B"></bean>
<bean id="a" class="org.kodnest.A" autowire="byName"></bean>
</beans>
SampleTest.java
package org.kodnest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SampleTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
A a=context.getBean("a",A.class);
a.display();
}
}
13. Program for Spring jdbcTemplate
Create table
create table student(
id number(10),
name varchar2(100),
marks number(10)
);
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private float marks;
//no-arg and parameterized constructors
//getters and setters
}
StudentDao.java
package com.kodnest;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int saveStudent(Stuednt s){
String query="insert into student values(
'"+s.getId()+"','"+s.getName()+"','"+s.getMarks()+"')";
return jdbcTemplate.update(query);
}
public int updateStudent(Student s){
String query="update student set
name='"+s.getName()+"',marks='"+s.getMarks()+"' where id='"+s.getId()+"' ";
return jdbcTemplate.update(query);
}
public int deleteStudent(Student s){
String query="delete from student where id='"+s.getId()+"' ";
return jdbcTemplate.update(query);
}
}
applicationContext.java
<?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-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.kodnest.StudentDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SampleTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDao dao=(StudentDao)ctx.getBean("edao");
int status=dao.saveStudent(new Student(10,"Raj",35));
System.out.println(status);
}
}
14. Program for PreparedStatement in Spring.
create table
create table student(
id number(10),
name varchar2(100),
marks number(10)
);
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private float marks;
//no-arg and parameterized constructors
//getters and setters
}
StudentDao.java
package com.kodnest;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
public class StudentDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Boolean saveStudentByPreparedStatement(final Student s){
String query="insert into student values(?,?,?)";
return jdbcTemplate.execute(query,new PreparedStatementCallback<Boolean>(){
@Override
public Boolean doInPreparedStatement(PreparedStatement ps)
throws SQLException, DataAccessException {
ps.setInt(1,s.getId());
ps.setString(2,s.getName());
ps.setFloat(3,s.getMarks());
return ps.execute();
}
});
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.kodnest.StudentDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SampleTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDao dao=(StudentDao)ctx.getBean("edao");
dao.saveEmployeeByPreparedStatement(new Student(18,"Karan",32));
}
}
15. Program for ResultSetExtractor Interface to show all records of the table
create table
create table student(
id number(10),
name varchar2(100),
marks number(10)
);
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private float marks;
//no-arg and parameterized constructors
//getters and setters
}
StudentDao.java
package com.kodnest;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
public class StudentDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Student> getAllStudent(){
return template.query("select * from student",new ResultSetExtractor<List<Employee>>(){
@Override
public List<Employee> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Student> list=new ArrayList<Student>();
while(rs.next()){
Student s=new Student();
s.setId(rs.getInt(1));
s.setName(rs.getString(2));
s.setMarks(rs.getInt(3));
list.add(e);
}
return list;
}
});
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="sdao" class="com.kodnest.StudentDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SampleTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDao dao=(StudentDao)ctx.getBean("sdao");
List<Student> list=dao.getAllStudent();
for(Student s:list)
System.out.println(s);
}
}
16. Program for RowMapper Interface to show all records of the table.
create table
create table student(
id number(10),
name varchar2(100),
marks number(10)
);
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private float marks;
//no-arg and parameterized constructors
//getters and setters
public String toString(){
return id+" "+name+" "+marks;
}
}
StudentDao.java
package com.kodnest;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
public class StudentDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Student> getAllStudentRowMapper(){
return template.query("select * from student",new RowMapper<Employee>(){
@Override
public Student mapRow(ResultSet rs, int rownumber) throws SQLException {
Student s=new Student();
s.setId(rs.getInt(1));
s.setName(rs.getString(2));
s.setMarks(rs.getInt(3));
return e;
}
});
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.student.StudentDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
SampleTest.java
package com.kodnest;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SampleTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDao dao=(StudentDao)ctx.getBean("edao");
List<Student> list=dao.getAllStudentRowMapper();
for(Student s:list)
System.out.println(s);
}
}
17. Program for NamedParameterJDBCTemplate class.
create table
create table student(
id number(10),
name varchar2(100),
marks number(10)
);
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private float marks;
//no-arg and parameterized constructors
//getters and setters
}
StudentDao.java
package com.kodnest;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import java.util.*;
public class StudentDao {
NamedParameterJdbcTemplate template;
public StudentDao(NamedParameterJdbcTemplate template) {
this.template = template;
}
public void save (Student s){
String query="insert into student values (:id,:name,:marks)";
Map<String,Object> map=new HashMap<String,Object>();
map.put("id",s.getId());
map.put("name",s.getName());
map.put("marks",s.getMarks());
template.execute(query,map,new PreparedStatementCallback() {
@Override
public Object doInPreparedStatement(PreparedStatement ps)
throws SQLException, DataAccessException {
return ps.executeUpdate();
}
});
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jtemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="sdao" class="com.kodnest.StudentDao">
<constructor-arg>
<ref bean="jtemplate"/>
</constructor-arg>
</bean>
</beans>
SimpleTest.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SimpleTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
StudentDao dao=(StudentDao)factory.getBean("sdao");
dao.save(new Emp(23,"raj",50));
}
}
18. Program for SimpleJDBCTemplate class
create table
create table student(
id number(10),
name varchar2(100),
marks number(10)
);
Student.java
package com.kodnest;
public class Student {
private int id;
private String name;
private float marks;
//no-arg and parameterized constructors
//getters and setters
}
StudentDao.java
package com.kodnest;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
public class StudentDao {
SimpleJdbcTemplate template;
public StudentDao(SimpleJdbcTemplate template) {
this.template = template;
}
public int update (Student s){
String query="update student set name=? where id=?";
return template.update(query,e.getName(),e.getId());
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jtemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="sdao" class="com.kodnest.StudentDao">
<constructor-arg>
<ref bean="jtemplate"/>
</constructor-arg>
</bean>
</beans>
SimpleTest.java
package com.kodnest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SimpleTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
StudentDao dao=(StudentDao)factory.getBean("sdao");
int status=dao.update(new Student(3,"Raj",37));
System.out.println(status);
}
}
19. Program for SPEL using operator.
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class SimpleTest {
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
//arithmetic operator
System.out.println(parser.parseExpression("'Welcome to SPEL'+'!'").getValue());
System.out.println(parser.parseExpression("10 * 10/2").getValue());
System.out.println(parser.parseExpression("'Today is: '+ new java.util.Date()").getValue());
//logical operator
System.out.println(parser.parseExpression("true and true").getValue());
//Relational operator
System.out.println(parser.parseExpression("'sonoo'.length()==5").getValue());
}
}
20. Program for SPEL using variable.
calculation.java
public class Calculation {
private int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int cube(){
return number*number*number;
}
}
SimpleTest.java
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class SimpleTest {
public static void main(String[] args) {
Calculation calculation=new Calculation();
StandardEvaluationContext context=new StandardEvaluationContext(calculation);
ExpressionParser parser = new SpelExpressionParser();
parser.parseExpression("number").setValue(context,"5");
System.out.println(calculation.cube());
}
}
22. Program for Spring MVC Multiple View Page.
Adding dependencies to pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
Creating the request page
index.jsp
<html>
<body>
<a href="hello">Click Now.</a>
</body>
</html>
Creating controller class
HelloController.java
package com.kodnest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String redirect()
{
return "firstpage";
}
@RequestMapping("/helloopage")
public String display()
{
return "secondpage";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Defining bean in xml file
spring-servlet.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.kodnest" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
firstpage.jsp
<html>
<body>
<a href="helloagain">Spring Tutorials</a>
</body>
</html>
secondpage.jsp
<html>
<body>
<p>Welcome to Spring</p>
</body>
</html>
23. Spring MVC Program
Adding dependencies to pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
Creating request page
index.jsp
<html>
<body>
<form action="hello">
UserName : <input type="text" name="name"/> <br><br>
Password : <input type="text" name="pass"/> <br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Creating controller class
MVController.java
package com.kodnest;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MVController {
@RequestMapping("/hello")
public String display(HttpServletRequest req,Model m)
{
//read the provided form data
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(pass.equals("admin"))
{
String msg="Hello "+ name;
//add a message to the model
m.addAttribute("message", msg);
return "firstpage";
}
else
{
String msg="Sorry "+ name+". You entered an incorrect password";
m.addAttribute("message", msg);
return "errorpage";
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Defining bean in xml file
spring-servlet.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.kodnest" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
firstpage.jsp
<html>
<body>
${message}
</body>
</html>
errorpage.jsp
<html>
<body>
${message}
<br><br>
<jsp:include page="/index.jsp"></jsp:include>
</body>
</html>
24. Spring MVC Form Text Field Program.
Adding dependencies to pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
Creating bean class
Student.java
package com.kodnest;
public class Student {
private String firstName;
private String lastName;
public Student()
{
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Creating student controller
package com.kodnest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/student")
@Controller
public class StudentController {
@RequestMapping("/studentForm")
public String bookingForm(Model model)
{
//create a Student object
Student std=new Student();
//provide reservation object to the model
model.addAttribute("student", std);
return "student-page";
}
@RequestMapping("/submitForm")
// @ModelAttribute binds form data to the object
public String submitForm(@ModelAttribute("student") Student std)
{
return "confirmation-form";
}
}
Defining bean in the xml file
spring-servlet.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.kodnest" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Creating request page
index.jsp
<!DOCTYPE html>
<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<a href="student/studentForm">Click here for student registration.</a>
</body>
</html>
student-page.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>Student Registration Form</title>
</head>
<h3> Student Form</h3>
<body>
<form:form action="submitForm" modelAttribute="reservation">
First name: <form:input path="firstName" />
<br><br>
Last name: <form:input path="lastName" />
<br><br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
confirmation-page.jsp
<!DOCTYPE html>
<html>
<body>
<p>Your registration successfully. Please, re-check the details.</p>
First Name : ${student.firstName} <br>
Last Name : ${student.lastName}
</body>
</html>
25. Spring MVC CRUD Example
Creating bean class
Employee.java
package com.kodnest.beans;
public class Employee {
private int id;
private String name;
private float salary;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
}
Creating controller class
package com.kodenst.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.javatpoint.beans.Emp;
import com.javatpoint.dao.EmpDao;
@Controller
public class EmpController {
@Autowired
EmpDao dao;//will inject dao from XML file
/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/
@RequestMapping("/empform")
public String showform(Model m){
m.addAttribute("command", new Emp());
return "empform";
}
/*It saves object into database. The @ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
@RequestMapping(value="/save",method = RequestMethod.POST)
public String save(@ModelAttribute("emp") Emp emp){
dao.save(emp);
return "redirect:/viewemp";//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
@RequestMapping("/viewemp")
public String viewemp(Model m){
List<Emp> list=dao.getEmployees();
m.addAttribute("list",list);
return "viewemp";
}
/* It displays object data into form for the given id.
* The @PathVariable puts URL data into variable.*/
@RequestMapping(value="/editemp/{id}")
public String edit(@PathVariable int id, Model m){
Emp emp=dao.getEmpById(id);
m.addAttribute("command",emp);
return "empeditform";
}
/* It updates model object. */
@RequestMapping(value="/editsave",method = RequestMethod.POST)
public String editsave(@ModelAttribute("emp") Emp emp){
dao.update(emp);
return "redirect:/viewemp";
}
/* It deletes record for the given id in URL and redirects to /viewemp */
@RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public String delete(@PathVariable int id){
dao.delete(id);
return "redirect:/viewemp";
}
}
Creating DAO class
package com.kodnest.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.javatpoint.beans.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into Empp(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Empp set name='"+p.getName()+"', salary="+p.getSalary()+",designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Empp where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Empp where id=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Empp",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}
Defining bean in xml file
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.javatpoint.controllers"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value=""></property>
<property name="password" value=""></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.kodnest.dao.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
empform.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Add New Employee</h1>
<form:form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</form:form>
empeditform.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Edit Employee</h1>
<form:form method="POST" action="/SpringMVCCRUDSimple/editsave">
<table >
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Edit Save" /></td>
</tr>
</table>
</form:form>
viewemp.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Employees List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td><a href="editemp/${emp.id}">Edit</a></td>
<td><a href="deleteemp/${emp.id}">Delete</a></td>
</tr>
</c:forEach>
</table>
<br/>
<a href="empform">Add New Employee</a>
26. Spring MVC Validation Program
Creating bean class
package com.kodnest;
import javax.validation.constraints.Size;
public class Employee {
private String name;
@Size(min=1,message="required")
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
Creating controller class
package com.kodnest;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EmployeeController {
@RequestMapping("/hello")
public String display(Model m)
{
m.addAttribute("emp", new Employee());
return "viewpage";
}
@RequestMapping("/helloagain")
public String submitForm( @Valid @ModelAttribute("emp") Employee e, BindingResult br)
{
if(br.hasErrors())
{
return "viewpage";
}
else
{
return "final";
}
}
}
Defining bean in xml file
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.kodenst" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
viewpage.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<style>
.error{color:red}
</style>
</head>
<body>
<form:form action="helloagain" modelAttribute="emp">
Username: <form:input path="name"/> <br><br>
Password(*): <form:password path="pass"/>
<form:errors path="pass" cssClass="error"/><br><br>
<input type="submit" value="submit">
</form:form>
</body>
</html>
final.jsp
<html>
<body>
Username: ${emp.name} <br><br>
Password: ${emp.pass}
</body>
</html>
27. Spring MVC Tiles Program
Creating bean class
package com.kodnest.form;
public class Contact {
private String firstname;
private String lastname;
private String email;
private String telephone;
public String getEmail() {
return email;
}
public String getTelephone() {
return telephone;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
Creating controller class
TilesController
package com.kodnest.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TilesController {
@RequestMapping("/hello")
public String helloWorld(Model m) {
String message = "Hello World, Spring MVC @ Javatpoint";
m.addAttribute("message", message);
return "hello";
}
}
contactcontroller.java
package com.kodnest.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.kodnest.form.Contact;
@Controller
@SessionAttributes
public class ContactController {
@RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(@ModelAttribute("contact") Contact contact, BindingResult result) {
//write the code here to add contact
return "redirect:contact.html";
}
@RequestMapping("/contact")
public String showContacts(Model m) {
m.addAttribute("command", new Contact());
return "contact";
}
}
Defining bean in xml file
<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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.kodnestt.controller" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver"/>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
tiles.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="base.definition"
template="/WEB-INF/jsp/layout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="menu" value="/WEB-INF/jsp/menu.jsp" />
<put-attribute name="body" value="" />
</definition>
<definition name="contact" extends="base.definition">
<put-attribute name="title" value="Contact Manager" />
<put-attribute name="body" value="/WEB-INF/jsp/contact.jsp" />
</definition>
<definition name="hello" extends="base.definition">
<put-attribute name="title" value="Hello Spring MVC" />
<put-attribute name="body" value="/WEB-INF/jsp/hello.jsp" />
</definition>
</tiles-definitions>
index.jsp
<a href="contact.html">Contact</a>
contact.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring Tiles Contact Form</title>
</head>
<body>
<h2>Contact Manager</h2>
<form:form method="post" action="addContact.html">
<table>
<tr>
<td><form:label path="firstname">First Name</form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Email</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="lastname">Telephone</form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
layout.jsp
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
</head>
<body>
<div style="float:left;padding:10px;width:15%;"><tiles:insertAttribute name="menu" /></div>
<div style="float:left;padding:10px;width:80%;border-left:1px solid pink;">
<tiles:insertAttribute name="body" /></div>
</body>
</html>
27. Program for JAXB Integration
Student.java
package com.kodnest;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="student")
public class Student {
private int id;
private String name;
private float marks;
@XmlAttribute(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name="marks")
public float getMarks() {
return marks;
}
public void setMarks(float marks) {
this.marks = marks;
}
}
applicationContext.java
<?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:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<oxm:jaxb2-marshaller id="jaxbMarshallerBean">
<oxm:class-to-be-bound name="com.kodnest.Studnet"/>
</oxm:jaxb2-marshaller>
</beans>
School.java
package com.kodnest;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
public class School{
public static void main(String[] args)throws IOException{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshallerBean");
Student s=new Student();
s.setId(11);
s.setName("Raj Mehta");
s.setMarks(10);
marshaller.marshal(employee, new StreamResult(new FileWriter("student.xml")));
System.out.println("XML Created Sucessfully");
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="11">
<name>Raj Mehta</name>
<marks>10</marks>
</employee>
28. Program to send mail
Mailone.java
package com.kodnest;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
public class Mailone{
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String from, String to, String subject, String msg) {
//creating message
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(msg);
//sending message
mailSender.send(message);
}
}
applicationContext.xml
<?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-3.0.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="username" value="[email protected]" />
<property name="password" value="yourgmailpassword" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.port">465</prop>
</props>
</property>
</bean>
<bean id="mailMail" class="com.kodnest.Mailone">
<property name="mailSender" ref="mailSender" />
</bean>
</beans>
SampleTest.java
package com.kodnest;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class SampleTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory b=new XmlBeanFactory(r);
Mailone m=(Mailone)b.getBean("mailone");
String sender="[email protected]";//write here sender gmail id
String receiver="[email protected]";//write here receiver id
m.sendMail(sender,receiver,"hi","welcome");
System.out.println("success");
}
}
How to run the program
- Load the spring jar files for core and java mail
- Load the mail.jar and activation.jar
- Change the username and password property in the applicationContext.xml file, specifying your gmail id and password.
- Change the sender gmail id and receivermail id in the SampleTest.java file.
- Compile and Run the Test class
29. Program to send mails to multiple receivers.
You can send mails to multiple receivers by the help of SimpleMailMessage class. The setTo(String[] receivers) method of SimpleMailMessage class is used to send message to multiple receivers.
public void MultipleMail(String from, String[] to, String subject, String msg) {
//creating message
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);//passing array of recipients
message.setSubject(subject);
message.setText(msg);
//sending message
mailSender.send(message);
}
30. Program for Spring MimeMessagePreparator.
The applicationContext.xml and SampleTest.java files are same as given in example 28.
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
public class Mailone{
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(final String from, final String to,final String subject,final String msg) {
MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
mimeMessage.setFrom(new InternetAddress(from));
mimeMessage.setSubject(subject);
mimeMessage.setText(msg);
}
};
mailSender.send(messagePreparator);
}
}
31. Program to send Attachment using Spring MimeMessageHelper
The applicationContext.xml and SampleTest.java files are same as given in example 28.
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class Mailone{
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(final String from, final String to,final String subject,final String msg) {
try{
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(msg);
// attach the file
FileSystemResource file = new FileSystemResource(new File("c:/one.jpg"));
helper.addAttachment("image.jpg", file);//image will be sent by this name
mailSender.send(message);
}catch(MessagingException e){e.printStackTrace();}
}
}
32. Login using Spring and Strut2.
index.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<s:form action="login">
<s:textfield name="name" label="Username"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
strut.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="def" extends="struts-default">
<action name="login" class="login">
<result name="success">login_success.jsp</result>
<result name="error">login_error.jsp</result>
</action>
</package>
</struts>
applicationContext.xml
<?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-3.0.xsd">
<bean id="login" class="com.kodnest.Login">
<property name="successmessage" value="You are successfully logged in!"></property>
<property name="errormessage" value="Sorry, username or password error!"></property>
</bean>
</beans>
Login.java
package com.kodenst;
public class Login {
private String name,password,successmessage,errormessage;
//setters and getters
public String execute(){
if(password.equals("kodenst")){
return "success";
}
else{
return "error";
}
}
}
Login_success.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
${successmessage}
<br/>
Welcome, <s:property value="name"/><br/>
Login_error.jsp
${errormessage}
<jsp:include page="index.jsp"></jsp:include>
Responses