Spring boot rabbitmq example using maven

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 recievedMessage(String msg) {
        System.out.println("Recieved 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
      Recieved 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
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid
      Recieved Message: hai candid

Download

Spring boot rabbitmq

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

spring boot Mongodb

 

Spring boot quartz scheduler example code

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>

 

Download

Servlet form example

This servlet form example shows you how to create html or jsp form and send form data to servlet. In this tutorial i have followed servlet 3 annotation based, so please make sure you have servlet 3.1 jar.

Environment used

JDK 8 or greater version

Latest Eclipse EE for web developer

Servlet 3. 1 jar or greater version

Tomcat 8.5 or greater version

Creating form in jsp or html

This file contains the form with different input types for your better understanding

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

   Welcome to servlet 3 Form example
   <br>
   <br>
   <form action="MyForm">
      Email : <input type="text" name="email"> <br> 
      User Name: <input type="text" name="uname"> <br> 
      Password: <input type="password" name="pass"> <br> 
      Gender : <input type="radio" name="gender" value="male" checked> 
      Male <input type="radio" name="gender" value="female"> 
      Female <input type="radio" name="gender" value="other"> <br>
      Course: <input type="checkbox" name="course" value="Java">
      Java <input type="checkbox" name="course" value="Dot Net"> Dot
      Net <input type="checkbox" name="course" value="PHP"> PHP <br>
      <input type="submit" value="Submit"> <input type="reset">
   </form>

</body>
</html>

Now Let’s see how to send form data to servlet

Once the form is filled and user click on submit button, a http request will be sent to our tomcat container

Tomcat container will map your action with your corresponding servlet controller and getParameter function form HttpServletRequest will retrieve field data.

Text box name should exactly match with getParameter argument.

 String em = request.getParameter("email");

Look at the below servlet controller

FormController

package com.candidjava;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/MyForm")
public class FormController extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

        String em = request.getParameter("email");
        String un = request.getParameter("uname");
        String pa = request.getParameter("pass");
        String ge = request.getParameter("gender");
        String[] co = request.getParameterValues("course");

        response.setContentType("text/html");
        PrintWriter pw=response.getWriter();
        pw.write("<h2> Following data received sucessfully.. <h2> <br>");
        pw.write("<h3> Email: "+ em +" </h3>");
        pw.write("<h3> User name: "+ un +" </h3>");
        pw.write("<h3> Password: "+ pa +" </h3>");
        pw.write("<h3> Gender: "+ ge +" </h3>");
        pw.write("<h3> Course:  ");
        for(String c:co)
        {
            pw.write(  c+"   ");
        }
        pw.write("</h3>");
    }
}

 

Output screenshot

 

Download

Servlet form data zip

Servlet form data war

 

 

 

Hello world servlet annotation example

This post shows you how to create servlet annotation example using example, servlet 3.0 has introduced a annotation based mapping instead of web.xml mapping. That makes web.xml optional in latest servlet application.

If you do not have prior knowledge in servlet 2, don’t worry you can start learning servlet 3 directly web.xml knowledge is not needed.

Requirement

JDK 8 or greater version

Latest Eclipse EE for web developer

Servlet 3. 1 jar or greater version

Tomcat 8.5 or greater version

Creating a first web application in servlet 3

Right click and create a new dynamic web project with web module version greater than 3.0.

Create a new html file – Right click on webContent –> new –> html > give file name as index.html

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

   Welcome to servlet 3.x hello world example
   <br>
   <br>

   <a href="MyAction">Click here</a>

</body>
</html>

Now create a servlet — Right click on src–>new –>servlet –> give a file name as HelloServlet. remove all methods and constructor except doGet method for our hello world example

Provide your html action name in @WebServlet annotaion.

HelloServlet.java

package com.candidjava;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/MyAction")
public class HelloServlet extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");

        PrintWriter pw=response.getWriter();
        pw.write("<h1> Welcome to Servlet <h1> <br>");
        pw.write("<h2> you have successfully received your response <h2> <br>");
    }
}

Add servlet jar

Add tomcat to server environment

How to run

right click on index.html — Select RunAs–> run on server –> select tomcat and click finish

 

Output Screenshot

 Download

servlet-helloworld-3 zip

Servlet 3 hello world war

 

 

 

 

 

Servlet RequestDispatcher forward and include method

RequestDispatcher defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

RequestDispatcher dis=request.getRequestdispatcher("/action");

Requestdispatcher include vs forward

Requestdispatcher forward method

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

dis.forward(request,response);

Requestdispatcher include method

Includes the content of a resource (servlet, JSP page, HTML file) in the response.

dis.include(request,response);

Requestdispatcher vs sendredirect

Requestdispatcher

  • The browser is completely unaware that it has taken place, so its original URL remains intact
  • Any browser reload of the resulting page will simple repeat the original request, with the original URL

sendredirect

  • A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original
  • Browser reload of the second URL will not repeat the original request, but will rather fetch the second URL
  • Redirect is marginally slower than a forward, since it requires two browser requests, not one
  • Objects placed in the original request scope are not available to the second request

Servlet dispatcher example

Environment used

Java 8

Tomcat 8.5

Servlt 3.1 +

Source Code

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>RequestDispatcher</h1>
<h2> Forward </h2>
<form action="ForwardController" method="post">
   Username : <input type="text" name="uname"> <br>
   <input type="submit" value="forward">
</form> 

<br>
<h2> Include </h2>
<form action="IncludeController" method="post">
   Username : <input type="text" name="uname"> <br>
   <input type="submit" value="include">
</form> 

</body>
</html>

Request Dispatcher forward

package com.candidjava;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ForwardController")
public class ForwardController extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String name=request.getParameter("uname");

        System.out.println("Forward Controller Data received : "+ name);

        PrintWriter pw=  response.getWriter();
        pw.write("<b>Welcome to Forward Controller </b> <br>");

        RequestDispatcher dis=request.getRequestDispatcher("/SecondController");
        dis.forward(request, response);


    }

}

Request Dispatcher include

package com.candidjava;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class IncludeController
 */
@WebServlet("/IncludeController")
public class IncludeController extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("uname");

        System.out.println("Include Controller Data received : "+ name);

        PrintWriter pw=  response.getWriter();
        pw.write("<b>Welcome to Include Controller </b> <br>");

        RequestDispatcher dis=request.getRequestDispatcher("/SecondController");
        dis.include(request, response);

    }

}

SecondController

package com.candidjava;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SecondController
 */
@WebServlet("/SecondController")
public class SecondController extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name=request.getParameter("uname");

        System.out.println("Second Controller Data received : "+ name);

        PrintWriter pw=  response.getWriter();
        pw.write("<b>Welcome to Second Controller </b> <br>");


    }

}

 

Output Screenshot

Download source code

Request dispatcher war

Request dispatcher zip

 

what is servlet and JSP

This tutorial shows you what is servlet and jsp with its difference and how it works with web application

When Web began to be used for delivering services, Common Gateway Interface (CGI) server-side scripts were the main technology used to generate dynamic content.

Since CGI scripting technology had many shortcomings like platform dependence and lack of scalability.

To overcome these limitations, Java Servlet technology was created as a portable way to provide dynamic, user-oriented content.

A servlet is a Java programming language used to create request-response programming model. Although servlets can respond to any type of request, they are commonly used to HTTP-specific request.

Servlet Technology uses two main packages to handle HTTP request response
1. javax.servlet
2. javax.servlet.http

These packages provide interfaces and classes for writing servlet programming to handle GET and POST http request.

You can download the jar from http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api

what is servlet

Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.

What is JSP

JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.

Difference between jsp and servlet

  • Servlet is html in java whereas JSP is java in html.
  • JSP can be compiled into Java Servlets
  • JSP is a webpage scripting language that can generate dynamic content while Servlets are Java programs that are already compiled which also creates dynamic web content
  • In MVC, jsp acts as a view and servlet acts as a controller.

which is better jsp or servlet

JSP is preferred When you have more stuff to do with design part.

Servlet is preferred for creating communication between design and Business layer.

Servlet life cycle in java with diagram

The servlet life cycle in java is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

1. If an instance of the servlet does not exist, the web container

a. Loads the servlet class.

b. Creates an instance of the servlet class.

c. Initializes the servlet instance by calling the init method.

2. Invokes the service method, passing request and response objects.

If it needs to remove the servlet, the container finalizes the servlet by calling the servlet’s destroy method.

Servlet life cycle methods

init

 public void init(ServletConfig config) throws ServletException

Called by the servlet container to indicate to a servlet that the servlet is being placed into service. This implementation stores the ServletConfig object it receives from the servlet container for later use.

service

public abstract void service(ServletRequest req, ServletResponse res)throws ServletException, java.io.IOException

Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class.

destroy

public void destroy()

Called by the servlet container to indicate to a servlet that the servlet is being taken out of service

Servlet life cycle diagram

Java servlet tutorial and example

Introduction to Java Servlet tutorial

What is Servlet and differance between JSP and Servlet

Servlet hello world example

Servlet 3 hello world example

Servlet form data example

Servlet life cycle

doGet vs doPost

 

Servlet Redirect

Request dispatcher forward and include

 

Servlet Session management

Servlet Cookie

Url Rewriting

Hidden form fields

Servlet HttpSession

 

Servlet Filter

Servlet Listener

load-on-startup in Servlet

Hidden form field in jsp example

Hidden form field in jsp or html can be used anywhere that you want to include data the user can’t see or edit along with the form when it’s submitted to the server.

Creating hidden form field in jsp or html

<input> elements of type “hidden” let web developers include data that cannot be seen or modified by users when a form is submitted.

The <input> element’s value attribute holds a DOMString that contains the hidden data you want to include when the form is submitted to the server. This specifically can’t be edited or seen by the user via the user interface, although you could edit the value via browser developer tools.

Please see below example

<form action="anotherPage.jsp" method="GET">
 <input type="hidden" name="UserId" value="auiaat">
<input type="submit" value ="submit"> 
</form>

How to get hidden field value in java

if we are using Servlets we can retrive value of parameter by below code

Using JSP scriptlet and implicit object

<% String hidden = request.getParameter("UserId"); %>
The Hidden Value is <%=hidden %>

Using JSTL

Hidden value:<c:out value="${param.UserId}" />

Advantage of hidden form

  • Tracking edited content using their hidden userid
  • Hidden inputs are also used to store and submit security tokens or secrets, for the purposes of improving website security

Disadvantage of hidden form

  • Only textual information can be used and extra form submission is required on each page

Hidden Form Example

Registration page 1

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>Registration form Page 1</h1>


<form action="register2.jsp" method="post">
   Username: <input type="text" name="uname"> <br>
   Password: <input type="password" name="pass"> <br>
   <input type="submit" value="Next">
</form>


</body>
</html>

Registration page 2

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<%
String un=request.getParameter("uname");
String pw=request.getParameter("pass");
%>
<h1>Registration form Page 2</h1>
<h2>View source code of this page to see hidden values</h2>


<form action="RegisterController" method="post">
      <input type="hidden" name="uname" value="<%=un%>">
      <input type="hidden" name="pass" value="<%=pw%>">
   Age: <input type="text" name="age"> <br>
   Email: <input type="text" name="email"> <br>
   <input type="submit" value="Register">
</form>
</body>
</html>

Registration servlet

package com.candidjava;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RegisterController")
public class RegisterController extends HttpServlet {

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      String un=request.getParameter("uname");
      String pw=request.getParameter("pass");
      String age=request.getParameter("age");
      String email=request.getParameter("email");

      response.setContentType("text/html");
      PrintWriter out= response.getWriter();
      out.write("<h1>Hidden form data received successfully</h1> ");

      out.write("Name :  "+un + "<br>");
      out.write("Password :  "+pw + "<br>");
      out.write("Age :  "+age + "<br>");
      out.write("Email :  "+email + "<br>");

   }

}

Output Screenshot

Download Source Code

Servlet Hidden form war

Servlet Hidden form zip