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

  
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


  

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


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 answers;
public Question() {}
public Question(int id, String name, List 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 itr=answers.iterator();
    while(itr.hasNext()){
        System.out.println(itr.next());
    }
}
}  

applicationContext.xml


I am good.
I am fine
  

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();
}
} 

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




  

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

The plugin is available in English, French(Français), Arabic (العربية), Brazilian Portuguese(Português do Brasil), Italian(Italiano), Russian(Русский), Chinese(简体中文), Dutch(Nederlands), Serbian(Српски језик), Swedish(Svenska), Urdu(اردو), Japanese(日本語) and Polish(Polski).

Looking for an easy, user-friendly and robust Job board plugin?

Simple Job Board by PressTigers is an easy, light weight plugin that adds a job board to your WordPress website.
This plugin is extendible and easy to use. A customized job board is created to manage various job offers via WordPress with the Simple Job Board. You can add multiple job listings and can show them on any page by inserting [jobpost] shortcode. You can add multiple job features and customized application forms for every distinct job listing. You can also add notes to an application right from the dashboard.

 

SampleTest.java

package com.kodnet;
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


4
Raj
Bengaluru

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


  

SampleTest.java

package com.javatpoint;
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 answers;
//setters and getters
public void displayInfo(){
    System.out.println(id+" "+name);
    System.out.println("answers are:");
    Iterator itr=answers.iterator();
    while(itr.hasNext()){
        System.out.println(itr.next());
    }
}
}  

applicationContext.xml


I am good.
I am fine.
  

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




  

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.sssit;
public class B {
B(){System.out.println("b is created");}
void print(){System.out.println("hello b");}
}  

A.java

package org.sssit;
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


  

SampleTest.java

package org.sssit;
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


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.javatpoint;
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(){
    @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


SampleTest.java

package com.javatpoint;
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 getAllStudent(){
 return template.query("select * from student",new ResultSetExtractor(){
    @Override
     public List extractData(ResultSet rs) throws SQLException,
            DataAccessException {
        List list=new ArrayList();
        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


  

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 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 getAllStudentRowMapper(){
 return template.query("select * from student",new RowMapper(){
    @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


  

SampleTest.java

package com.javatpoint;
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 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.javatpoint;
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


  

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.javatpoint;
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


  

SimpleTest.java

package com.javatpoint;
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 using operator in SPEL.

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 using variable in SPEL.

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());
}
}  

21. Program for Spring MVC Multiple View Page.

Adding dependencies to pom.xml

    org.springframework
    spring-webmvc
    5.1.1.RELEASE
    javax.servlet
    servlet-api
    3.0-alpha-1
  
Creating the request page

index.jsp


Click Now.
  
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


  SpringMVC
    spring
    org.springframework.web.servlet.DispatcherServlet
    1
    spring
    /
  
Defining bean in xml file

spring-servlet.xml


  

firstpage.jsp


Spring Tutorials
  

secondpage.jsp

Welcome to Spring


  

22. Spring MVC Program

Adding dependencies to pom.xml

    org.springframework
    spring-webmvc
    5.1.1.RELEASE
    javax.servlet
    servlet-api
    3.0-alpha-1
  
Creating request page

index.jsp

UserName :

 

Password :


  
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


  SpringMVC
    spring
    org.springframework.web.servlet.DispatcherServlet
    1
    spring
    /
  
Defining bean in xml file

spring-servlet.xml


  

firstpage.jsp


${message}
 

errorpage.jsp


${message}


23. Spring MVC Form Text Field Program.

Adding dependencies to pom.xml

    org.springframework
    spring-webmvc
    5.1.1.RELEASE
    javax.servlet
    servlet-api
    3.0-alpha-1
    javax.servlet
    jstl
    1.2
    org.apache.tomcat
    tomcat-jasper
    9.0.12
  
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


  
Creating request page

index.jsp


Click here for student registration.
  

student-page.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

Student Form


        First name:
        

Last name:

confirmation-page.jsp

Your registration successfully. Please, re-check the details.


First Name : ${student.firstName} 
Last Name : ${student.lastName}

24. 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 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.class));
}
public List getEmployees(){
    return template.query("select * from Empp",new RowMapper(){
        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

  

empform.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Add New Employee

Name :  
Salary :  
Designation :  
 

        

empeditform.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Edit Employee

   
Name :  
Salary :  
Designation :  
 

           

viewemp.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
   <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Employees List

Id Name Salary Designation Edit Delete
${emp.id} ${emp.name} ${emp.salary} ${emp.designation} Edit Delete

   
Add New Employee

25. 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

  

viewpage.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

Username:  

Password(*):

final.jsp


Username: ${emp.name} 

Password: ${emp.pass}

26. 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

/WEB-INF/tiles.xml
  

tiles.xml


  

index.jsp

Contact  

contact.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

Contact Manager

First Name  
Last Name  
Email  
Telephone  

layout.jsp

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>

26. 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


  

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

Raj Mehta
10
  

27. 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


              true
              465
              javax.net.ssl.SSLSocketFactory
              465

SampleTest.java

package com.kodest;
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

Related Articles

Spring

1. Hello World Program HelloWorld.java MainApp.java 2. How to create Spring applcation. Create Java Class Create XML File Create test class Load jar files required…

Core Java

1. What are primitive types in Java ? byte, short, int, long, float, double, char, boolean… 2. What are tokens? Name the 5 types of tokens available in Java with an example…

Hackerearth-Java

     1. Challenge : Welcome to Java! Welcome to the world of Java! In this challenge, we practice printing to stdout. The code stubs…

Advance Java

1. Write an Example Snippet to Connect Java Application with mysql database. 2. Wap to get the object of ResultSetMetaData. The getMetaData() method of ResultSet…

Responses

Your email address will not be published. Required fields are marked *

×