Category Archives: Spring Boot

Spring boot rabbitmq example using maven

This tutorial is about Spring boot rabbitmq configuration with Maven build tool.

RabbitConfig.java

package com.candidjava.springboot.configuration;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
   @Value("${jsa.rabbitmq.queue}")
   private String queueName;
   
   @Value("${jsa.rabbitmq.exchange}")
   private String exchange;
   
   @Value("${jsa.rabbitmq.routingkey}")
   private String routingKey;
   
   @Bean
   Queue queue() {
      return new Queue(queueName, false);
   }

   @Bean
   DirectExchange exchange() {
      return new DirectExchange(exchange);
   }

   @Bean
   Binding binding(Queue queue, DirectExchange exchange) {
      return BindingBuilder.bind(queue).to(exchange).with(routingKey);
   }
   @Bean
   public MessageConverter jsonMessageConverter() {
      return new Jackson2JsonMessageConverter();
   }

   
   @Bean
   public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
      final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
      rabbitTemplate.setMessageConverter(jsonMessageConverter());
      return rabbitTemplate;
   }

}

Publisher.java

package com.candidjava.springboot.publisher;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Publisher {
   @Autowired
   private AmqpTemplate amqpTemplate;
   
   @Value("${jsa.rabbitmq.exchange}")
   private String exchange;
   
   @Value("${jsa.rabbitmq.routingkey}")
   private String routingKey;
   
   public void produceMsg(String msg){
      amqpTemplate.convertAndSend(exchange, routingKey, msg);
      System.out.println("Send msg = " + msg);
   }
}

Subscriber.java

package com.candidjava.springboot.subcriber;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class Subcriber {
   @RabbitListener(queues="${jsa.rabbitmq.queue}")
    public void receivedMessage(String msg) {
        System.out.println("Received Message: " + msg);
    }
}

application.properties

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.queue=jsa.queue1
jsa.rabbitmq.exchange=jsa.direct1
jsa.rabbitmq.routingkey=jsa.routingkey1

HelloworldController.java

package com.candidjava.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.candidjava.springboot.publisher.Publisher;


@RestController
public class HelloworldController {
   
   @Autowired
   Publisher publisher;
   
   @RequestMapping("/send")
   public String sendMessage(@RequestParam("msg") String msg){
      System.out.println("*****"+msg);
      for(int i =0; i<25;i++){
      publisher.produceMsg(msg);
      }
      return "Successfully Msg Sent";
   }
   


}

application.java

package com.candidjava.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class Application {
   
public static void main(String[] args) {
   SpringApplication.run(Application.class, args);
}
}

pom.xml

<?xml version="1.0"?>

-<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">

<modelVersion>4.0.0</modelVersion>

<groupId>com.spring-boot-rabbitmq</groupId>

<artifactId>Spring-Boot-Rabbitmq</artifactId>

<packaging>war</packaging>

<version>0.0.1-SNAPSHOT</version>

<name>Spring-Boot-Rabbitmq Maven Webapp</name>

<url>http://maven.apache.org</url>


-<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.4.RELEASE</version>

<relativePath/>

<!-- lookup parent from repository -->


</parent>


-<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>


-<dependencies>


-<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>


-<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-amqp</artifactId>

</dependency>

</dependencies>


-<build>


-<plugins>


-<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

<finalName>Spring-Boot-Rabbitmq</finalName>

</build>

</project>

Output

Request:
      endpoint: http://localhost:8080/send?msg=hai candid
      method:get
      Response:
      200
      Successfully Msg Sent

      Console:

      *****hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Received Message: hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Send msg = hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid
      Received Message: hai candid

Download

Spring boot rabbitmq

spring boot mongodb example with maven

MongoDB is an opensource NoSQL database which is opensource too. In this following program learn how to configure spring boot MongoDB with maven examples. Here is Configuration of spring boot MongoDB example with maven.

Pom.xml

<?xml version="1.0"?>

-<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">

<modelVersion>4.0.0</modelVersion>

<groupId>com.spring-boot-mongodb</groupId>

<artifactId>Spring-Boot-Mongo</artifactId>

<packaging>war</packaging>

<version>0.0.1-SNAPSHOT</version>

<name>Spring-Boot-Mongo Maven Webapp</name>

<url>http://maven.apache.org</url>


-<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.9.RELEASE</version>

<relativePath/>

<!-- lookup parent from repository -->


</parent>


-<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>


-<dependencies>


-<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>


-<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-mongodb</artifactId>

</dependency>

</dependencies>


-<build>


-<plugins>


-<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

<finalName>Spring-Boot-Mongo</finalName>

</build>

</project>

Application.properties

logging.level.org.springframework.web=DEBUG

#Mongo
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=sampledb

UserRepository.java

package com.candidjava.spring.repository;

import org.springframework.data.repository.CrudRepository;
import com.candidjava.spring.bean.User;
public interface UserRepository extends CrudRepository<User, String>{

}

UserController.java

package com.candidjava.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value={"/","/user"})
public class UserController {
   @Autowired
   UserService userService;
   @GetMapping(value="/",produces = MediaType.APPLICATION_JSON_VALUE)
   public String get(){
      return "Please give url as Spring-Boot-Rest/user/get";
      
   }
    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserById(@PathVariable("id") String id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
    
    @PostMapping(value="/create",headers="Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
        System.out.println("Creating User "+user.getName());
        userService.createUser(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @GetMapping(value="/get", headers="Accept=application/json")
    public List<User> getAllUser() {   
     List<User> tasks=userService.getUser();
     return tasks;
   
    }

   @PutMapping(value="/update", headers="Accept=application/json")
   public ResponseEntity<String> updateUser(@RequestBody User currentUser)
   {
      System.out.println("sd");
   User user = userService.findById(currentUser.getId());
   if (user==null) {
      return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
   }
   userService.update(currentUser, currentUser.getId());
   return new ResponseEntity<String>(HttpStatus.OK);
   }
   
   @DeleteMapping(value="/{id}", headers ="Accept=application/json")
   public ResponseEntity<User> deleteUser(@PathVariable("id") String id){
      User user = userService.findById(id);
      if (user == null) {
         return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
      }
      userService.deleteUserById(id);
      return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
   }
   
   @PatchMapping(value="/{id}", headers="Accept=application/json")
   public ResponseEntity<User> updateUserPartially(@PathVariable("id") String id, @RequestBody User currentUser){
      User user = userService.findById(id);
      if(user ==null){
         return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
      }
      User usr = userService.updatePartially(currentUser, id);
      return new ResponseEntity<User>(usr, HttpStatus.OK);
   }
}

User.java

package com.candidjava.spring.bean;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;


@SuppressWarnings("serial")
@Document(collection = "user")
public class User  extends BaseEntity{

   
   private String country;
   
   private String name;
   
   public User(){
      
   }
   public User(String country, String name){
      this.country = country;
      this.name = name;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }

}

BaseEntity.java

package com.candidjava.spring.bean;

import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

   @SuppressWarnings("serial")
   @Document
   public abstract class BaseEntity implements Serializable {
       @Id
       private String id;

      public String getId() {
         return id;
      }

      public void setId(String id) {
         this.id = id;
      }
       

   }

UserService.java

package com.candidjava.spring.service;

import java.util.List;
import com.candidjava.spring.bean.User;

public interface UserService {
   public void createUser(User user);
   public List<User> getUser();
   public User findById(String id);
   public User update(User user, String l);
   public void deleteUserById(String id);
   public User updatePartially(User user, String id);
}

UserServiceImp.java

package com.candidjava.spring.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.candidjava.spring.bean.User;
import com.candidjava.spring.repository.UserRepository;

@Service
@Transactional
public class UserServiceImp implements UserService {
   @Autowired
   UserRepository userRepository;

   public void createUser(User user) {
      // TODO Auto-generated method stub
      userRepository.save(user);
   }

   public List<User> getUser() {
      // TODO Auto-generated method stub
      return (List<User>) userRepository.findAll();
   }

   public User findById(String id) {
      // TODO Auto-generated method stub
      return userRepository.findOne(id);
   }

   public User update(User user, String l) {
      // TODO Auto-generated method stub
      return userRepository.save(user);
   }

   public void deleteUserById(String id) {
      // TODO Auto-generated method stub
      userRepository.delete(id);
   }

   public User updatePartially(User user, String id) {
      // TODO Auto-generated method stub
      User usr = findById(id);
      usr.setCountry(user.getCountry());
      return userRepository.save(usr);
   }



}

Application.java

package com.candidjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
   }

}

Output

Request
	method:post
	endpoint: http://localhost:8080/user/create
	Content-Type:application/json
	body: {
			"country":"India",
			"name":"Mathan"
		   }
		   
Response
	Status: 201
	

Request
	method:GET
	endpoint: http://localhost:8080/user/get
	Content-Type:application/json
		   
Response
	Status: 200
	content: [{"id":"5afec0ad72637160400936b6","country":"India","name":"Mathan"}]

DOWNLOAD SOURCE FILE

Spring boot quartz scheduler example code

Spring boot quartz scheduler:

Quartz scheduler in spring boot purpose is to scheduling job as per your convenient. Here this library can be integrated with all types of Java applications. using this, you can convert your simple java components into a job that you can schedule and run as per your need.

SimpleJob.java

package com.candidjava.springboot;

import org.quartz.Job;
import org.quartz.JobExecutionContext;

public class SimpleJob implements Job{
 
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
       
       System.out.println("Candidjava welcomes simple job");
        
    }
}

 

SpringJobFactory.java

package com.candidjava.springboot;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public final class SpringJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
    
    
       private transient AutowireCapableBeanFactory beanFactory;
       @Override
       public void setApplicationContext(final ApplicationContext context) {
           beanFactory = context.getAutowireCapableBeanFactory();
       }
    
       @Override
       protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
           final Object job = super.createJobInstance(bundle);
           System.out.println("create job instance");
           beanFactory.autowireBean(job);
           return job;
       }
   }

 

SchedulerConfig.java

package com.candidjava.springboot;

import java.io.IOException;
import java.util.Properties;
import org.quartz.JobDetail;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

@Configuration
public class SchedulerConfig {

   @Bean
   public JobFactory jobFactory(ApplicationContext applicationContext) {
      SpringJobFactory jobFactory = new SpringJobFactory();
      jobFactory.setApplicationContext(applicationContext);
      return jobFactory;
   }

   @Bean
   public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory,
         Trigger simpleJobTrigger) throws IOException {
      SchedulerFactoryBean factory = new SchedulerFactoryBean();
      factory.setJobFactory(jobFactory);
      factory.setQuartzProperties(quartzProperties());
      factory.setTriggers(simpleJobTrigger);
      System.out.println("starting jobs....");
      return factory;
   }

   @Bean
   public SimpleTriggerFactoryBean simpleJobTrigger(
         @Qualifier("simpleJobDetail") JobDetail jobDetail,
         @Value("${simplejob.frequency}") long frequency) {
      System.out.println("simpleJobTrigger");

      SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
      factoryBean.setJobDetail(jobDetail);
      factoryBean.setStartDelay(0L);
      factoryBean.setRepeatInterval(frequency);
      factoryBean.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
      return factoryBean;
   }

   @Bean
   public Properties quartzProperties() throws IOException {
      PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
      propertiesFactoryBean.setLocation(new ClassPathResource(
            "/quartz.properties"));
      propertiesFactoryBean.afterPropertiesSet();
      return propertiesFactoryBean.getObject();
   }

   @Bean
   public JobDetailFactoryBean simpleJobDetail() {
      JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
      factoryBean.setJobClass(SimpleJob.class);
      factoryBean.setDurability(true);
      return factoryBean;
   }
}

 

Application.java

package com.candidjava.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
   }
}

 

application.properties

simplejob.frequency=1000

 

quartz.properties

org.quartz.scheduler.instanceName=springBootQuartzApp
org.quartz.scheduler.instanceId=AUTO
org.quartz.threadPool.threadCount=5

 

pom.xml

<?xml version="1.0"?>

      -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">

<modelVersion>4.0.0</modelVersion>

<groupId>com.spring-boot-quartz</groupId>

<artifactId>Spring-Boot-Quartz</artifactId>

<packaging>war</packaging>

<version>0.0.1-SNAPSHOT</version>

<name>Spring-Boot-Quartz Maven Webapp</name>

<url>http://maven.apache.org</url>


-<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.7.RELEASE</version>

<relativePath/>

<!-- lookup parent from repository -->


</parent>


-<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>


-<dependencies>


-<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>


-<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<scope>test</scope>

</dependency>


-<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-tx</artifactId>

</dependency>


-<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

</dependency>


-<dependency>

<groupId>org.quartz-scheduler</groupId>

<artifactId>quartz</artifactId>

<version>2.2.3</version>

</dependency>


-<dependency>

<groupId>org.quartz-scheduler</groupId>

<artifactId>quartz-jobs</artifactId>

<version>2.2.3</version>

</dependency>

</dependencies>


-<build>


-<plugins>


-<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

<finalName>Spring-Boot-Quartz</finalName>

</build>

</project>

For file  Download

Spring boot jetty example

Common servlet container settings can be configured using Spring Environment properties. Usually, you would define the properties in your application.properties file.

Spring boot jetty as an embedded server

Step 1: exclude tomcat from spring boot web starter

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

  Step 2: Now add Jetty dependency – spring-boot-starter-jetty maven

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Thats All…

How to run

mvn spring-boot:run

 

Download

Jetty as embedded server maven

 

Alternatively you can try Programmatic customization for jetty configuration

If you need to configure your embedded servlet container programmatically you can register a Spring bean that implements the EmbeddedServletContainerCustomizer interface. EmbeddedServletContainerCustomizer provides access to the ConfigurableEmbeddedServletContainer which includes numerous customization setter methods.

import org.springframework.boot.context.embedded.*;
        import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(9000);
    }

}

 

Spring boot import configuration

In this simple spring boot import example, You don’t need to put all your @Configuration into a single class. The @Import annotation can be used to import additional configuration classes.

Spring boot @Import example :

package com.candidjava.spring.configuration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@ComponentScan(basePackages = "com.candidjava")
@Import({ SpringConfiguration.class })
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}

 

SpringConfiguration class

package com.candidjava.spring.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
public class SpringConfiguration extends WebMvcConfigurerAdapter{

    @Bean(name = "jspViewResolver")
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

}

 

SpringWebIntializer class

package com.candidjava.spring.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;


public class SpringWebIntializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {
        // TODO Auto-generated method stub
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setServletContext(container);
        ServletRegistration.Dynamic servlet = container.addServlet(
                "dispatcher", new DispatcherServlet(context));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

 

Spring controller

package com.candidjava.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.candidjava.spring.entity.User;

@Controller
public class UserController {

    @GetMapping("/")
    public ModelAndView register(User user) {
        return new ModelAndView("register");
    }

    @PostMapping("/register")
    public ModelAndView create(@ModelAttribute("user") User user) {
        ModelAndView model = new ModelAndView("view");
        // user bean will be automatically binded to view refer @ModelAttribute
        System.out.println(user.getName());
        model.addObject("name",user.getName());
        model.addObject("gender",user.getGender());
        model.addObject("email", user.getEmail());
        model.addObject("country", user.getCountry());
        model.addObject("password", user.getPassword());
        return model;
    }

    @GetMapping("/register")
    public ModelAndView viewData(User user) {

        ModelAndView model = new ModelAndView("register");
        return model;
    }

}

 

User.java

package com.candidjava.spring.entity;

import java.util.List;

public class User
{
    private String name;

    private List<String> language;

    private String country;

    private String gender;

    private String password;

    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getLanguage() {
        return language;
    }

    public void setLanguage(List<String> language) {
        this.language = language;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

 

index.jsp

<meta http-equiv="refresh" content="0; URL='index'" />

 

register.jsp

    <%@page import="org.springframework.validation.ObjectError"%>
<%@ page import="com.candidjava.spring.entity.User" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.err
{
color:red;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>

   <h2>Simple spring form handling</h2>
   <form action="register" method="POST" modelAttribute="user">
   Name:<input type="text"name="name"/><br>
Gender : Male<input type="radio" name="gender" value="male" path="gender"/>   Female<input type="radio"  name="gender" value="female" path="gender"/><br>
   Email : <input type="text" name="email" path="email"/><br>
   Country : <select name="country" path="country">
               <option value="">select country</option>
               <option value="india">INDIA</option>
               <option value="usa">USA</option>
               <option value="china">CHINA</option>
             </select>
             
            <br>  
            Password:<input type="password" name="password" path="password"/><br>  
            <input type="submit" value="submit" />
   </form>
</body>
</html>

 

view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="com.candidjava.spring.entity.User" %>
<!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>Insert title here</title>
</head>
<body>
<h2>User Info</h2>

<strong>User Name </strong>: ${name} <br>
<strong>Gender </strong> : ${gender}<br>
<strong>Email </strong> : ${email}<br>
<strong>Country </strong>: ${country} <br> 
<strong>Password</strong>: ${password}<br> 
   
</body>
</html>

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>spring-boot-webapp-import</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-webapp-import</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <!-- This is a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Need this to compile JSP,
            tomcat-embed-jasper version is not working, no idea why -->
        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

How to run

mvn spring-boot:run

 

Screenshot

 

Download

Spring boot @import maven

 

 

Spring boot jpa mysql example

This tutorial shows you how to create Spring Boot JPA MySQL example. Here we established to provide quick programming examples which can be used to quickly create a MySQL-based Spring Boot app.

Here Java Persistence API is a standard technology that lets you “map” objects to relational databases. The spring-boot-starter-data-jpa POM provides a quick way to get started.

It provides the following key dependencies:

  • Hibernate: One of the most popular JPA implementations.
  • Spring Data JPA: Makes it easy to implement JPA-based repositories.
  • Spring ORMs: Core ORM support from the Spring Framework.

 

Environment Used

  • Eclipse
  • Maven
  • JDK 1.8
  • Spring Boot 1.4.2
  • Spring 4.3
  • Mysql 5.1 or greater

Spring Boot JPA Repository example

Central repository marker interface. Captures the domain type to manage as well as the domain type’s id type. General purpose is to hold type information as well as being able to discover interfaces that extend this one during classpath scanning for easy Spring bean creation.

Spring crudrepository

Interface for generic CRUD operations on a repository for a specific type.

package com.candidjava.spring.repository;

import org.springframework.data.repository.CrudRepository;

import com.candidjava.spring.bean.User;
public interface UserRepository extends CrudRepository<User, Long>{

}

Spring boot JPA hibernate configuration in application.properties

logging.level.org.springframework.web=DEBUG
# Database
spring.datasource.driver = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test3
spring.datasource.username = root
spring.datasource.password = root


spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Service Interface

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
    public void createUser(User user);
    public List<User> getUser();
    public User findById(long id);
    public User update(User user, long l);
    public void deleteUserById(long id);
    public User updatePartially(User user, long id);
}

Service Implementation

package com.candidjava.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.repository.UserRepository;

@Service
@Transactional
public class UserServiceImp implements UserService {
    @Autowired
    UserRepository userRepository;

    public void createUser(User user) {
        // TODO Auto-generated method stub
        userRepository.save(user);
    }

    public List<User> getUser() {
        // TODO Auto-generated method stub
        return (List<User>) userRepository.findAll();
    }

    public User findById(long id) {
        // TODO Auto-generated method stub
        return userRepository.findOne(id);
    }

    public User update(User user, long l) {
        // TODO Auto-generated method stub
        return userRepository.save(user);
    }

    public void deleteUserById(long id) {
        // TODO Auto-generated method stub
        userRepository.delete(id);
    }

    public User updatePartially(User user, long id) {
        // TODO Auto-generated method stub
        User usr = findById(id);
        usr.setCountry(user.getCountry());
        return userRepository.save(usr);
    }
}

Controller

package com.candidjava.spring.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value={"/user"})
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserById(@PathVariable("id") long id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @PostMapping(value="/create",headers="Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
        System.out.println("Creating User "+user.getName());
        userService.createUser(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @GetMapping(value="/get", headers="Accept=application/json")
    public List<User> getAllUser() {
        List<User> tasks=userService.getUser();
        return tasks;

    }

    @PutMapping(value="/update", headers="Accept=application/json")
    public ResponseEntity<String> updateUser(@RequestBody User currentUser)
    {
        System.out.println("sd");
        User user = userService.findById(currentUser.getId());
        if (user==null) {
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        userService.update(currentUser, currentUser.getId());
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @DeleteMapping(value="/{id}", headers ="Accept=application/json")
    public ResponseEntity<User> deleteUser(@PathVariable("id") long id){
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }

    @PatchMapping(value="/{id}", headers="Accept=application/json")
    public ResponseEntity<User> updateUserPartially(@PathVariable("id") long id, @RequestBody User currentUser){
        User user = userService.findById(id);
        if(user ==null){
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        User usr = userService.updatePartially(currentUser, id);
        return new ResponseEntity<User>(usr, HttpStatus.OK);
    }
}

Bean Class

package com.candidjava.spring.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;


@Entity
@Table(name="UserInfo")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    @Column(name="country")
    private String country;
    @Column(name="name")

    private String name;


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

}

Application.java

package com.candidjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Spring boot JPA Maven configuration (pom.xml)

By adding spring-boot-starter-data-jpa in you pom.xml your dependency in ready to use.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>Spring-Boot-Jpa-mysql</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-Jpa-mysql Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- Tomcat embedded container -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>Spring-Boot-Jpa-mysql</finalName>
    </build>
</project>

How to run

mvn spring-boot:run

Download

Spring boot data JPA mysql maven – Download

 

References

JPA repository – Official site

JPA CurdRepository – Official site

 

Spring boot hibernate crud example

Here spring boot with hibernate simple curd operation with an example program.

Environment Used

Eclipse

Maven

JDK 1.8

Spring Boot 1.4.2

Spring 4.3

Hibernate 5

Mysql 5.1 or greater

 

Spring boot hibernate mysql example

This tutorial shows you how to integrate spring boot with hibernate framework.

 

Hibernate Configuration

This code contains the hibernate configuration to load in spring boot application, this is not specific to spring boot. I just used the old spring hibernate integration configuration code to work with spring boot hibernate

package com.candidjava.spring.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {

    @Value("${db.driver}")
    private String DB_DRIVER;

    @Value("${db.password}")
    private String DB_PASSWORD;

    @Value("${db.url}")
    private String DB_URL;

    @Value("${db.username}")
    private String DB_USERNAME;

    @Value("${hibernate.dialect}")
    private String HIBERNATE_DIALECT;

    @Value("${hibernate.show_sql}")
    private String HIBERNATE_SHOW_SQL;

    @Value("${hibernate.hbm2ddl.auto}")
    private String HIBERNATE_HBM2DDL_AUTO;

    @Value("${entitymanager.packagesToScan}")
    private String ENTITYMANAGER_PACKAGES_TO_SCAN;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
        hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
        sessionFactory.setHibernateProperties(hibernateProperties);
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DB_DRIVER);
        dataSource.setUrl(DB_URL);
        dataSource.setUsername(DB_USERNAME);
        dataSource.setPassword(DB_PASSWORD);
        return dataSource;
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }
}

Spring boot applications.properties

This file contains the spring boot hibernate mysql configuration value, change this value according to your database.

logging.level.org.springframework.web=DEBUG
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/test
db.username: root
db.password: root

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: update
entitymanager.packagesToScan: com

@RestController

Contains the old spring 4.3 version rest Controller code

package com.candidjava.spring.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value={"/user"})
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserById(@PathVariable("id") int id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @PostMapping(value="/create",headers="Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
        System.out.println("Creating User "+user.getName());
        userService.createUser(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @GetMapping(value="/get", headers="Accept=application/json")
    public List<User> getAllUser() {
        List<User> tasks=userService.getUser();
        return tasks;

    }

    @PutMapping(value="/update", headers="Accept=application/json")
    public ResponseEntity<String> updateUser(@RequestBody User currentUser)
    {
        System.out.println("sd");
        User user = userService.findById(currentUser.getId());
        if (user==null) {
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        userService.update(currentUser, currentUser.getId());
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @DeleteMapping(value="/{id}", headers ="Accept=application/json")
    public ResponseEntity<User> deleteUser(@PathVariable("id") int id){
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }

    @PatchMapping(value="/{id}", headers="Accept=application/json")
    public ResponseEntity<User> updateUserPartially(@PathVariable("id") int id, @RequestBody User currentUser){
        User user = userService.findById(id);
        if(user ==null){
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        User usr = userService.updatePartially(currentUser, id);
        return new ResponseEntity<User>(usr, HttpStatus.OK);
    }
}

Bean class

package com.candidjava.spring.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;


@Entity
@Table(name="UserInfo")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    @Column(name="country")
    private String country;
    @Column(name="name")

    private String name;


    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 getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

}

Service Interface

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
    public void createUser(User user);
    public List<User> getUser();
    public User findById(int id);
    public User update(User user, int id);
    public void deleteUserById(int id);
    public User updatePartially(User user, int id);
}

Service Impl

package com.candidjava.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.dao.UserDao;

@Service
@Transactional
public class UserServiceImp implements UserService {
    @Autowired
    UserDao userDao;


    public List<User> getUser() {
        // TODO Auto-generated method stub
        return userDao.getUser();
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        return userDao.findById(id);
    }

    public void createUser(User user) {
        // TODO Auto-generated method stub
        userDao.addUser(user);
    }

    public void deleteUserById(int id) {
        // TODO Auto-generated method stub
        userDao.delete(id);
    }
    @Override
    public User updatePartially(User user, int id) {
        userDao.updateCountry(user,id);
        return userDao.findById(id);
    }

    @Override
    public User update(User user,int id) {
        // TODO Auto-generated method stub
        return userDao.update(user, id);
    }

}

Dao Interface

package com.candidjava.spring.dao;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserDao {
    public void addUser(User user);
    public List<User> getUser();
    public User findById(int id);
    public User update(User user, int id);
    public User updateCountry(User user, int id);
    public void delete(int id);
}

Dao Impl

This code contains the Dao layer to manipulate database operation

package com.candidjava.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.candidjava.spring.bean.User;
@Repository
public class UserDaoImp implements UserDao{
    @Autowired
    private SessionFactory sessionFactory;

    public void addUser(User user) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
    }

    public List<User> getUser() {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        @SuppressWarnings("unchecked")
        List<User> list= session.createCriteria(User.class).list();
        return list;
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        User user=(User) session.get(User.class,id);
        return user;
    }

    public User update(User val, int id) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        User user =(User)session.get(User.class, id);
        user.setCountry(val.getCountry());
        user.setName(val.getName());
        session.update(user);
        return user;
    }

    public void delete(int id) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        User user = findById(id);
        session.delete(user);
    }
    @Override
    public User updateCountry(User val, int id){
        Session session = sessionFactory.getCurrentSession();
        User user = (User)session.load(User.class, id);
        user.setCountry(val.getCountry());
        return user;
    }

}

Maven pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>Spring-Boot-Restfull</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-Restfull Maven Webapp</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>Spring-Boot-Restfull</finalName>
    </build>
</project>

How to run

mvn spring-boot:run

Download

Spring boot hibernate rest maven

 

References

Spring boot hibernate Official website

Spring boot rest example | Spring boot rest API

Spring boot rest:

REpresentational State Transfer is familiarly known as REST. Technically REST defines a basic set of architectural constraints. These constraints should be satisfied with the required services. Any service which satisfies these constraints is called RESTful Service. Learn here how spring boot rest API example application created with examples.

Environment used

  • Eclipse
  • Maven
  • JDK 1.8
  • Spring Boot 1.4.2
  • Spring 4.3

This tutorial shows you how to create spring boot rest service using @GetMapping, @PostMapping, @PathMapping, @PutMapping, @DeleteMapping.

Spring boot rest controller example

The @RestController and @RequestMapping annotations are Spring MVC annotations that helps to create spring boot restcontroller. (They are not specific to Spring Boot.)  Spring mvc tutorial

UserController.java

package com.candidjava.spring.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value={"/user"})
public class UserController {
    @Autowired
    UserService userService;


    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserById(@PathVariable("id") int id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @PostMapping(value="/create",headers="Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
        System.out.println("Creating User "+user.getName());
        userService.createUser(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @GetMapping(value="/get", headers="Accept=application/json")
    public List<User> getAllUser() {
        List<User> tasks=userService.getUser();
        return tasks;

    }

    @PutMapping(value="/update", headers="Accept=application/json")
    public ResponseEntity<String> updateUser(@RequestBody User currentUser)
    {
        User user = userService.findById(currentUser.getId());
        if (user==null) {
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        user.setId(currentUser.getId());
        user.setName(currentUser.getName());
        user.setCountry(currentUser.getCountry());
        userService.update(user);
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @DeleteMapping(value="/{id}", headers ="Accept=application/json")
    public ResponseEntity<User> deleteUser(@PathVariable("id") int id){
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }

    @PatchMapping(value="/{id}", headers="Accept=application/json")
    public ResponseEntity<User> updateUserPartial(@PathVariable("id") int id, @RequestBody User currentUser){
        User user = userService.findById(id);
        if(user ==null){
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        userService.updatePartially(currentUser, id);
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
}

Bean class

package com.candidjava.spring.bean;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

    private int id;
    private String country;
    private String name;
    public User(){
        id=0;
    }
    public User(int id, String name, String country){
        this.id = id;
        this.name = name;
        this.country = country;
    }
    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 getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String toString()
    {
        return"name:"+name;
    }

}

Service Interface

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
    public void createUser(User user);
    public List<User> getUser();
    public User findById(int id);
    public void update(User user);
    public void deleteUserById(int id);
    public void updatePartially(User user, int id);
}

Service Implementation with dummy data

package com.candidjava.spring.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Service;

import com.candidjava.spring.bean.User;

@Service
public class UserServiceImp implements UserService {

    private static List<User> users;

    static {
        users = dummyUsers();
    }

    public List<User> getUser() {
        // TODO Auto-generated method stub
        return users;
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        for (User user : users) {
            if (user.getId() == id) {
                return user;
            }
        }
        return null;
    }

    public void createUser(User user) {
        // TODO Auto-generated method stub
        users.add(user);
    }

    public void deleteUserById(int id) {
        // TODO Auto-generated method stub
        Iterator<User> it = users.iterator();
        while (it.hasNext()) {
            User user = (User) it.next();
            if (user.getId() == id) {
                it.remove();
            }
        }
    }

    public void updatePartially(User currentUser, int id) {
        for (User user : users) {
            if (user.getId() == id) {
                if (currentUser.getCountry() != null) {
                    user.setId(id);
                    user.setCountry(currentUser.getCountry());
                }
                user.setName(user.getName());
                update(user);
            }
        }

    }

    public void update(User user) {
        // TODO Auto-generated method stub
        int index = users.indexOf(user);
        users.set(index, user);
    }

    private static List<User> dummyUsers() {
        // TODO Auto-generated method stub
        List<User> users = new ArrayList<User>();
        users.add(new User(14221, "John", "INDIA"));
        users.add(new User(14222, "Ben", "UK"));
        users.add(new User(14223, "Andrew", "INDIA"));
        users.add(new User(14224, "Samuael", "USA"));
        return users;
    }

}

Spring Boot Application.java

Our main method delegates to Spring Boot’s SpringApplication class by calling  run. SpringApplication bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server.  Read more on Spring boot hello world.

package com.candidjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

Spring boot application.properties

logging.level.org.springframework.web=DEBUG

Maven dependencies pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>Spring-Boot-RestCrud</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-RestCrud Maven Webapp</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>Spring-Boot-RestCrud</finalName>
    </build>
</project>

 

How to run

mvn spring-boot:run

 

Rest Endpoints

GET –> http://localhost:8080/user/get

Download

Spring boot rest curd example maven

References

Spring boot rest – Official website

 

Spring boot war tomcat – creating deployable war file

Step 1:  Extend SpringBootServletInitializer

The first step in producing a deployable war file is to provide a SpringBootServletInitializer subclass and override its configure method. This makes use of Spring Framework’s Servlet 3.0 support and allows you to configure your application when it’s launched by the servlet container.

package com.candidjava.spring.configuration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@ComponentScan(basePackages = "com.candidjava")
@Import({ SpringConfiguration.class })
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}

 

Step 2 : Change packing to war

The next step is to update your build configuration so that your project produces a war file rather than a jar file.

Change pom.xml file packing type to war

 <packaging>war</packaging>

 

Step 3: Adding servlet container dependency

The final step in the process is to ensure that the embedded servlet container doesn’t interfere with the servlet container to which the war file will be deployed. To do so, you need to mark the embedded servlet container dependency as provided. spring boot without embedded tomcat, creates deployable war.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

 

To run this example use use maven goal as

mvn clean package

 

Download example spring-boot-deployable-war

spring boot web applications | xml configuration

In this spring boot web applications tutorial shows you how to create a spring web application using spring boot

Spring boot web application configuration

package com.candidjava.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource("classpath:app-config.xml")
public class SpringBootWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
}

 

Spring boot dispatcher servlet XML configuration

<?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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.candidjava.spring.controller"></context:component-scan>

    <bean id="jspViewResolver"     class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"     value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:resources location="/resources/" mapping="/resources/**"/>
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

 

Spring boot maven dependency for spring web application pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>Spring-Boot-Xml</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-Xml Maven Webapp</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <!-- web starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>



    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

 

Spring controller

package com.candidjava.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.candidjava.spring.entity.User;

@Controller
public class UserController {

    @GetMapping("/")
    public ModelAndView register(User user) {
        return new ModelAndView("register");
    }

    @PostMapping("/register")
    public ModelAndView create(@ModelAttribute("user") User user) {
        ModelAndView model = new ModelAndView("view");
        // user bean will be automatically binded to view refer @ModelAttribute
        System.out.println(user.getName());
        model.addObject("name",user.getName());
        model.addObject("gender",user.getGender());
        model.addObject("email", user.getEmail());
        model.addObject("country", user.getCountry());
        model.addObject("password", user.getPassword());
        return model;
    }

    @GetMapping("/register")
    public ModelAndView viewData(User user) {

        ModelAndView model = new ModelAndView("register");
        return model;
    }

}

 

Bean Class

package com.candidjava.spring.entity;

import java.util.List;


public class User
{
    private String name;

    private List<String> language;

    private String country;

    private String gender;

    private String password;

    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getLanguage() {
        return language;
    }

    public void setLanguage(List<String> language) {
        this.language = language;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

 

JSP — register.jsp

    <%@page import="org.springframework.validation.ObjectError"%>
<%@ page import="com.candidjava.spring.entity.User" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.err
{
color:red;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>

   <h2>Simple spring form handling</h2>
   <form action="register" method="POST" modelAttribute="user">
   Name:<input type="text"name="name"/><br>
Gender : Male<input type="radio" name="gender" value="male" path="gender"/>   Female<input type="radio"  name="gender" value="female" path="gender"/><br>
   Email : <input type="text" name="email" path="email"/><br>
   Country : <select name="country" path="country">
               <option value="">select country</option>
               <option value="india">INDIA</option>
               <option value="usa">USA</option>
               <option value="china">CHINA</option>
             </select>
             
            <br>  
            Password:<input type="password" name="password" path="password"/><br>  
            <input type="submit" value="submit" />
   </form>
</body>
</html>

 

JSP — view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="com.candidjava.spring.entity.User" %>
<!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>Insert title here</title>
</head>
<body>
<h2>User Info</h2>
<strong>User Name </strong>: ${name} <br>
<strong>Gender </strong> : ${gender}<br>
<strong>Email </strong> : ${email}<br>
<strong>Country </strong>: ${country} <br> 
<strong>Password</strong>: ${password}<br> 
   
</body>
</html>

 

Screenshot

Download

Spring boot XML @ImportResources