Thursday 17 December 2020

Spring MVC login Example using Spring jdbcTemplate

Project Code Structure
Following screenshot shows the structure of the project we will create.













Create POM.xml file

<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.ramsis</groupId>

  <artifactId>springmvcjdbctemplate</artifactId>

  <packaging>war</packaging>

  <version>0.0.1-SNAPSHOT</version>

  <name>springmvcjdbctemplate Maven Webapp</name>

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

  

   <properties>

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

    <spring.version>5.2.4.RELEASE</spring.version>

    <junit.version>4.12</junit.version>

    <servlet.version>3.1.0</servlet.version>

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

    <mysql.connector.version>8.0.17</mysql.connector.version>

  </properties>

  

 <dependencies>

    <!-- Junit -->

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>${junit.version}</version>

      <scope>test</scope>

    </dependency>


    <!-- Spring Framework -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-core</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-beans</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-context</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-jdbc</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-test</artifactId>

      <version>${spring.version}</version>

      <scope>test</scope>

    </dependency>


    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-webmvc</artifactId>

      <version>${spring.version}</version>

    </dependency>


    <!-- MySQL database driver -->

    <dependency>

      <groupId>mysql</groupId>

      <artifactId>mysql-connector-java</artifactId>

      <version>${mysql.connector.version}</version>

    </dependency>


    <!-- Servlet API -->

    <dependency>

      <groupId>javax.servlet</groupId>

      <artifactId>javax.servlet-api</artifactId>

      <version>${servlet.version}</version>

    </dependency>

    

    <!-- https://mvnrepository.com/artifact/jstl/jstl -->

<dependency>

    <groupId>jstl</groupId>

    <artifactId>jstl</artifactId>

    <version>1.2</version>

</dependency>

    

  </dependencies>

  <build>

    <finalName>springmvcjdbctemplate</finalName>

  </build>

</project>




------------------------------------------------------------------------------------

user-beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

  xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="

   http://www.springframework.org/schema/beans     

   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

   http://www.springframework.org/schema/context 

   http://www.springframework.org/schema/context/spring-context-3.0.xsd">


  <context:component-scan base-package="com.ramsis.springmvcjdbctemplate" />

  <context:annotation-config />


  <bean id="userService" class="com.ramsis.springmvcjdbctemplate.service.UserServiceImpl" />

  <bean id="userDao" class="com.ramsis.springmvcjdbctemplate.dao.UserDaoImpl" />


  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

    <property name="dataSource" ref="datasource" />

  </bean>


  <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />

    <property name="url" value="jdbc:mysql://qadbserver.cqlzbbt51la6.ap-south-1.rds.amazonaws.com:3306/anjni_testing" />

    <property name="username" value="root" />

    <property name="password" value="admin" />

  </bean>


</beans>


-------------------------------------------------------------------------------------

LoginController.java



package com.ramsis.springmvcjdbctemplate.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;
import com.ramsis.springmvcjdbctemplate.service.UserService;

@Controller
public class LoginController {

  @Autowired
  UserService userService;

  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("login");
    mav.addObject("login", new Login());

    return mav;
  }

  @RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
  public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,HttpSession session,
      @ModelAttribute("login") Login login) {
    ModelAndView mav = null;

    User user = userService.validateUser(login);

    if (null != user) {
      mav = new ModelAndView("welcome");
      session.setAttribute("username", user.getFirstname());
      mav.addObject("firstname", user.getFirstname());
    } else {
      mav = new ModelAndView("login");
      mav.addObject("message", "Username or Password is wrong!!");
    }

    return mav;
  }
 
  @RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logout(HttpSession session) {
 ModelAndView mav = new ModelAndView("login");
 session.removeAttribute("username");
 mav.addObject("login", new Login());
 return mav;
}

}

--------------------------------------------------------------------------------------

RegistrationController.java


package com.ramsis.springmvcjdbctemplate.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.ramsis.springmvcjdbctemplate.modal.User;
import com.ramsis.springmvcjdbctemplate.service.UserService;

@Controller
public class RegistrationController {
  @Autowired
  public UserService userService;

  @RequestMapping(value = "/register", method = RequestMethod.GET)
  public ModelAndView showRegister(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("register");
    mav.addObject("user", new User());

    return mav;
  }

  @RequestMapping(value = "/registerProcess", method = RequestMethod.POST)
  public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response,
      @ModelAttribute("user") User user) {
    userService.register(user);
    return new ModelAndView("welcome", "firstname", user.getFirstname());
  }
 
 
  @RequestMapping(value = "/dashBoard", method = RequestMethod.GET)
  public ModelAndView dashBoard(HttpServletRequest request, HttpServletResponse response,HttpSession session) {
    ModelAndView mav = null;

     String user = (String) session.getAttribute("username");
     System.out.println("Session User : "+user);
    if (null != user) {
      mav = new ModelAndView("welcome");
      mav.addObject("firstname", user);
    } else {
      mav = new ModelAndView("login");
      mav.addObject("message", "Username or Password is wrong!!");
    }
    return mav;
  }
 
  @RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
  public String getAllEmployees(Model model)
  {
      model.addAttribute("user", userService.getAllUsers());
      return "userListDisplay";
  }
 
}



---------------------------------------------------------------------------------------------


UserDao.java


package com.ramsis.springmvcjdbctemplate.dao;

import java.util.List;

import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;

public interface UserDao {

  int register(User user);

  User validateUser(Login login);
 
  List<User> getAllUsers();
}


----------------------------------------------------------------------------------------------


UserDaoImpl.java


package com.ramsis.springmvcjdbctemplate.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;

public class UserDaoImpl implements UserDao {

  @Autowired
  DataSource datasource;

  @Autowired
  JdbcTemplate jdbcTemplate;

  public int register(User user) {
    String sql = "insert into users(username,password,firstname,lastname,email,address,phone) values(?,?,?,?,?,?,?)";

    return jdbcTemplate.update (sql, new Object[] {user.getUsername(), user.getPassword(), user.getFirstname(),
        user.getLastname(), user.getEmail(), user.getAddress(), user.getPhone() });
  }

  public User validateUser(Login login) {
    String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()
        + "'";
    List<User> users = jdbcTemplate.query(sql, new UserMapper());

    return users.size() > 0 ? users.get(0) : null;
  }

public List<User> getAllUsers() {

String sql = "select username,password,firstname,lastname,email,address,phone from users";
    List<User> users = jdbcTemplate.query(sql, new UserMapper());

    return users;
}

}

class UserMapper implements RowMapper<User> {

  public User mapRow(ResultSet rs, int arg1) throws SQLException {
    User user = new User();

    user.setUsername(rs.getString("username"));
    user.setPassword(rs.getString("password"));
    user.setFirstname(rs.getString("firstname"));
    user.setLastname(rs.getString("lastname"));
    user.setEmail(rs.getString("email"));
    user.setAddress(rs.getString("address"));
    user.setPhone(rs.getInt("phone"));

    return user;
  }
}



--------------------------------------------------------------------------------------------


Login.java


package com.ramsis.springmvcjdbctemplate.modal;


public class Login {


  private String username;

  private String password;

  

  


  public String getUsername() {

    return username;

  }


  public void setUsername(String username) {

    this.username = username;

  }


  public String getPassword() {

    return password;

  }


  public void setPassword(String password) {

    this.password = password;

  }


}


--------------------------------------------------------------------------------------------


User.java


package com.ramsis.springmvcjdbctemplate.modal;


public class User {

  private Integer id;

  private String username;

  private String password;

  private String firstname;

  private String lastname;

  private String email;

  private String address;

  private Integer phone;

  

  public Integer getId() {

return id;

 }


  public void setId(Integer id) {

this.id = id;

 }


public String getUsername() {

    return username;

  }


  public void setUsername(String username) {

    System.out.println("username: " + username);

    this.username = username;

  }


  public String getPassword() {

    return password;

  }


  public void setPassword(String password) {

    this.password = password;

  }


  public String getFirstname() {

    return firstname;

  }


  public void setFirstname(String firstname) {

    System.out.println("firstname: " + firstname);

    this.firstname = firstname;

  }


  public String getLastname() {

    return lastname;

  }


  public void setLastname(String lastname) {

    System.out.println("lastname: " + lastname);

    this.lastname = lastname;

  }


  public String getEmail() {

    return email;

  }


  public void setEmail(String email) {

    this.email = email;

  }


  public String getAddress() {

    return address;

  }


  public void setAddress(String address) {

    this.address = address;

  }


  public Integer getPhone() {

    return phone;

  }


  public void setPhone(Integer phone) {

    this.phone = phone;

  }

}


--------------------------------------------------------------------------------------------


UserService.java


package com.ramsis.springmvcjdbctemplate.service;

import java.util.List;

import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;

public interface UserService {

  int register(User user);

  User validateUser(Login login);
  public List<User> getAllUsers();
}


---------------------------------------------------------------------------------------------


UserServiceImpl.java



package com.ramsis.springmvcjdbctemplate.service;

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

import org.springframework.beans.factory.annotation.Autowired;

import com.ramsis.springmvcjdbctemplate.dao.UserDao;
import com.ramsis.springmvcjdbctemplate.modal.Login;
import com.ramsis.springmvcjdbctemplate.modal.User;

public class UserServiceImpl implements UserService {

  @Autowired
  public UserDao userDao;

  public int register(User user) {
    return userDao.register(user);
  }

  public User validateUser(Login login) {
    return userDao.validateUser(login);
  }


public List<User> getAllUsers() {

List<User> userList = new ArrayList<User>();
User user1;
  for(User user2 : userDao.getAllUsers()) {
    user1 = new User();
  user1.setPhone(user2.getPhone());
  user1.setAddress(user2.getAddress());
  user1.setEmail(user2.getEmail());
  user1.setFirstname(user2.getFirstname());
  user1.setLastname(user2.getLastname());
  user1.setUsername(user2.getUsername());
  userList.add(user1);
  }
 
return (List<User>) userList;
}

}


--------------------------------------------------------------------------------------------


Download Code





Saturday 31 October 2020

Spring Boot Rest API with ManyToMany Relationship

In this Post I am showing you how you can easily create Rest API using Hibernate and Spring Boot with ManyToMany Relationships between two Entities.

you can download source code at the end.

Project Structure



Calling Response from Postman tool













------------------------------------------------------------------------------------------------------

Sample Json to Insert Data in Employee and Projects Table by POST  request

localhost:9090/Project
{
        "projectName": "CRISA",
        "employee" : [
        "employeeName" : "Chetan Shishodia"
            },
           
        "employeeName" : "Ajay Kumar"
            }
        ]
     }


        localhost:9090/Employee

{
        "employeeName": "Chetan Shishodia",
        
          "projects" : [
       
        "projectName" : "CRISA"
            },
           
        "projectName" : "FOIS"
            }
        ]
     }

------------------------------------------------------------------------------------------------------

EmployeeController.java

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
import com.restapi.entities.Employee;
import com.restapi.services.EmployeeService;

@RestController
public class EmployeeController {
 
@Autowired
EmployeeService empService;

@GetMapping("/home")
public String home() {
return "Welcome in RestApi with ManyToMany Relation home Page";
}

@GetMapping("/Employee")
public List <Employee> getEmp() {
return this.empService.getEmployees();
}

@GetMapping("/Employee/{eid}")
public Employee getEmpById(@PathVariable("eid") Integer eid) {
return this.empService.getEmployee(eid);
}

@PostMapping("/Employee" )
public Employee addEmp(@RequestBody  Employee employee) {
return this.empService.addEmployee(employee);
}

@PutMapping("/Employee")
public Employee updateEmp(@RequestBody  Employee employee) {
return this.empService.updateEmployee(employee);
}

@DeleteMapping("/Employee/{eid}")
public Integer deleteEmp(@PathVariable("eid") Integer eid) {
return this.empService.deleteEmployee(eid);
}
}

-----------------------------------------------------------------------------------------------------

ProjectControllers.java

package com.restapi.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;

import com.restapi.entities.Projects;
import com.restapi.services.ProjectService;

@RestController
public class ProjectControllers{

@Autowired
ProjectService projectService;

@GetMapping("/Project")
public List <Projects> getProjects() {
return this.projectService.getProjects();
}

@GetMapping("/Project/{pid}")
public Projects getProject(@PathVariable("pid") Integer pid) {
return this.projectService.getProject(pid);
}

@PostMapping("/Project")
public Projects addProjects(@RequestBody  Projects project) {
return this.projectService.addProject(project);
}

@PutMapping("/Project")
public Projects updateProject(@RequestBody  Projects project) {
return this.projectService.updateProject(project);
}

@DeleteMapping("/Project/{pid}")
public Integer deleteProject(@PathVariable("pid") Integer pid) {
return this.projectService.deleteProjects(pid);
}

}

-------------------------------------------------------------------------------------------------------
EmployeeDao.java

package com.restapi.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.restapi.entities.Employee;

public interface EmployeeDao extends JpaRepository<Employee, Integer>{

}

-------------------------------------------------------------------------------------------------------

ProjectDao.java

package com.restapi.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.restapi.entities.Projects;

public interface ProjectDao extends JpaRepository<Projects, Integer>{

}

-------------------------------------------------------------------------------------------------------

Employee.java

package com.restapi.entities;

import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity(name="Employee")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer eid;
private String employeeName;

@ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinTable(name="EmployeeProjectsJoin",
joinColumns = {@JoinColumn(name="eid")},
inverseJoinColumns={@JoinColumn(name="pid")})

@JsonIgnoreProperties("employee")
private List<Projects> projects;

public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}

public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public List<Projects> getProjects() {
return projects;
}
public void setProjects(List<Projects> projects) {
this.projects = projects;
}
public Employee(Integer eid, String employeeName, List<Projects> projects) {
super();
this.eid = eid;
this.employeeName = employeeName;
this.projects = projects;
}

public Employee() {
super();
}

}

--------------------------------------------------------------------------------------------------------

Projects.java

package com.restapi.entities;

import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity(name="Projects")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Projects implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer pid;
private String projectName;

@ManyToMany(mappedBy="projects",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JsonIgnoreProperties("projects")
private List<Employee> employee;

public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}

public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}

public List<Employee> getEmployee() {
return employee;
}
public void setEmployee(List<Employee> employee) {
this.employee = employee;
}
public Projects(Integer pid, String projectName, List<Employee> employee) {
super();
this.pid = pid;
this.projectName = projectName;
this.employee = employee;
}
public Projects() {
super();
}

}

-------------------------------------------------------------------------------------------------------

EmployeeImpl.java

package com.restapi.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.restapi.dao.EmployeeDao;
import com.restapi.entities.Employee;

@Service
public class EmployeeImpl implements EmployeeService{
    @Autowired
EmployeeDao empDao;

@Override
public List<Employee> getEmployees() {
// TODO Auto-generated method stub
return empDao.findAll();
}

@Override
public Employee getEmployee(Integer empId) {
// TODO Auto-generated method stub
return empDao.getOne(empId);
}

@Override
public Employee addEmployee(Employee employee) {
empDao.save(employee);
return employee;
}

@Override
public Employee updateEmployee(Employee employee) {
empDao.save(employee);
return employee;
}

@Override
public Integer deleteEmployee(Integer empId) {
int status =0;
try {
Employee emp = empDao.getOne(empId);
empDao.delete(emp);
status=1;
}catch(Exception ex) {
status=0;
ex.printStackTrace();
return status;
}
return status;
}

}

--------------------------------------------------------------------------------------------------------

EmployeeService.java

package com.restapi.services;
import java.util.List;

import com.restapi.entities.Employee;

public interface EmployeeService {
public List<Employee> getEmployees();
public Employee getEmployee(Integer empId);
public Employee addEmployee(Employee  emp);
public Employee updateEmployee(Employee emp);
public Integer deleteEmployee(Integer empId);
}

-------------------------------------------------------------------------------------------------------

ProjectImpl.java

package com.restapi.services;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.restapi.dao.ProjectDao;
import com.restapi.entities.Projects;

@Service
public class ProjectImpl implements ProjectService {

@Autowired
ProjectDao projectDao;

@Override
public List<Projects> getProjects() {
// TODO Auto-generated method stub
return projectDao.findAll();
}

@Override
public Projects getProject(Integer projectId) {
// TODO Auto-generated method stub
return projectDao.getOne(projectId);
}

@Override
public Projects addProject(Projects project) {
// TODO Auto-generated method stub
projectDao.save(project);
return project;
}

@Override
public Projects updateProject(Projects project) {
// TODO Auto-generated method stub
projectDao.save(project);
return project;
}

@Override
public Integer deleteProjects(Integer projectId) {
int status =0;
try {
Projects project = projectDao.getOne(projectId);
projectDao.delete(project);
   status=1;
}catch(Exception ex) {
status=0;
ex.printStackTrace();
return status;
}
return status;
}

}

--------------------------------------------------------------------------------------------------------

ProjectService.java

package com.restapi.services;

import java.util.List;
import com.restapi.entities.Projects;

public interface ProjectService {

public List<Projects> getProjects();
public Projects getProject(Integer projectId);
public Projects addProject(Projects  project);
public Projects updateProject(Projects project);
public Integer deleteProjects(Integer projectId);
}

-------------------------------------------------------------------------------------------------------

application.properties

# Changing the server port 
server.port=9090
# Database Configuration : Mysql
spring.datasource.url=jdbc:mysql://localhost/Test
spring.datasource.username=root
spring.datasource.password=admin123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.fail-on-empty-beans=false

-------------------------------------------------------------------------------------------------------

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.restAPI</groupId>
<artifactId>REST</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>RestAPI</name>
<description>RestAPI Spring Boot</description>

<properties>
<java.version>11</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

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

</project>

---------------------------------------------------------------------------------





Sunday 25 October 2020

Functional Interfaces in java 8

A functional interface is an interface that contains only one abstract method. 
Along with the one abstract method, they can have any number of default and static methods.

In Java 8 there are four types of Functional Interfaces.

1) Predicate
2) Consumer
3) Function
4) Supplier


----------------------------------------------------------
1) Predicate gives only boolean value on the basis of one argument,
   it has only one method called
test().
   
   class PredicateExample {

    public static void main(String[] args) {

    Predicate<String> checkLength = t->t.length()>3;
    System.out.println(checkLength.test("Aman"));

     }

  }
   
   // Result will be : true
   
-----------------------------------------------------------

2) Consumer only Consumes data and no output will be send.
   It has only one method called
accept().
   
   class Employees{

        String name;

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

  public class ConsumerExample {

    public static void main(String[] args) {

        Employees e =new Employees();
        Consumer<Employees> getNames = t->t.setName("Ajay Kumar Dargan");
        getNames.accept(e);
        System.out.println(e.getName());

     }

  }
 
  // Result will be : Ajay Kumar Dargan
 
------------------------------------------------------------

3) Function it has two arguments like Function(T , R)
   'T' represent as input and 'R' represent as output.
    It has only one method called
apply().


public class FunctionExample {

     public static void main(String[] args) {

     Function<Integer,String> multiply = m->m*10+" << Multiply by 10";
        System.out.println(multiply.apply(20));

  }

}

//Result : 200 << Multiply by 10
--------------------------------------------------------------  
 
  4) Supplier does not take any arguments, but it only gives output.
     It has only one method called
get().

    public class SupplierExample {

      public static void main(String[] args) {

      Supplier<Double> getRendumNum = ()->Math.random();
      System.out.println(getRendumNum.get());
    }

  }

Result : 0.1384031347391398
----------------------------------------------------------------
 


import javax.servlet.*; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; @Component public class CORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; // response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET"); response.setHeader("Access-Control-Max-Age", "3700"); //response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }

JSP Servlet Mysql CRUD Application




Project Structure





Create ActionHelper

package com.ramsis;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;



public class ActionHelper
{
public boolean addEmployee(Employee objEmployee) throws Exception{
Connection con = null;
ResultSet rs = null;
Statement stmt = null;
StringBuffer sbfQuery = null;
try
{
con = DBConnection.getConnect();
con.setAutoCommit(false);
stmt = con.createStatement();
sbfQuery = new StringBuffer();

sbfQuery.append("SELECT COUNT(*) FROM EMP ");
sbfQuery.append("WHERE emp_id = '"+objEmployee.getEmpId()+"'");
rs = stmt.executeQuery(sbfQuery.toString());
rs.next();
if(rs.getInt(1) > 0){
return false;
}

sbfQuery = new StringBuffer();
sbfQuery.append("INSERT INTO EMP(emp_id, name, design, salary)");
sbfQuery.append("VALUES('");
sbfQuery.append(objEmployee.getEmpId()+"','");
sbfQuery.append(objEmployee.getName()+"','");
sbfQuery.append(objEmployee.getDesign()+"','");
sbfQuery.append(objEmployee.getSalary()+"' )");

int iRowCount = stmt.executeUpdate(sbfQuery.toString());

if(iRowCount != 1){
return false;
}
con.commit();
}catch(Exception ex){
throw ex;
}finally{
DBConnection.closeResources(con,rs,stmt,null);
}
return true;
}



public ArrayList<Employee> getAllEmployees() throws Exception{
ArrayList<Employee> aEmployeeList = null;
Connection con = null;
ResultSet rs = null;
Statement stmt = null;
StringBuffer sbfQuery = null;
Employee objEmployee = null;
try
{
con = DBConnection.getConnect();
stmt = con.createStatement();
aEmployeeList = new ArrayList();
sbfQuery = new StringBuffer();
sbfQuery.append("SELECT * FROM EMP");
rs = stmt.executeQuery(sbfQuery.toString());

while(rs.next())
{
objEmployee = new Employee();
objEmployee.setEmpID(rs.getInt("emp_id"));
objEmployee.setName(rs.getString("name"));
objEmployee.setDesign(rs.getString("design"));
objEmployee.setSalary(rs.getInt("salary"));
aEmployeeList.add(objEmployee);
}

}catch(Exception ex){
throw ex;
}finally{
DBConnection.closeResources(con,rs,stmt,null);
}
return aEmployeeList;
}


//Method for deleting a selected employee
public boolean deleteEmployee(int iEmpID) throws Exception{
Connection con = null;
ResultSet rs = null;
Statement stmt = null;
StringBuffer sbfQuery = null;
try
{
con = DBConnection.getConnect();
stmt = con.createStatement();
sbfQuery = new StringBuffer();

con.setAutoCommit(false);

sbfQuery.append("DELETE FROM EMP WHERE emp_id = " + iEmpID);

int iRowCount = stmt.executeUpdate(sbfQuery.toString());

if(iRowCount != 1){
return false;
}
con.commit();
}catch(Exception ex){
throw ex;
}finally{
DBConnection.closeResources(con,rs,stmt,null);
}
return true;
}


}//end of class


-------------------------------------------------------------------------------------

Create ActionServlet


package com.ramsis;

import java.io.IOException;

import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ActionServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{    
processsRequest(req,res);
}

public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
processsRequest(req,res);
}

public void processsRequest(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{    
String action = null;
int iAction = 0;
ActionHelper objActionHelper= null;
Employee objEmployee = null;
ArrayList aEmployeeList = null;
String sForwardJSP = null;


try
{
action = req.getParameter("action");
objActionHelper =  new ActionHelper();
if(action != null && action.trim().length() > 0){
iAction = Integer.parseInt(action);
}

switch(iAction)
{

case 1 : // ADD_EMPLOYEE :
sForwardJSP = "/jsp/addEmployees.jsp";
break;

case 2 : // SAVE_EMPLOYEE :

objEmployee = new Employee();

objEmployee.setEmpID(Integer.parseInt(req.getParameter("emp_id").trim()));
objEmployee.setName(req.getParameter("name"));
objEmployee.setDesign(req.getParameter("design"));
objEmployee.setSalary(Integer.parseInt(req.getParameter("salary")));

if(!objActionHelper.addEmployee(objEmployee)){
req.setAttribute("Message","This Emp ID already exists.");
sForwardJSP = "/jsp/addEmployees.jsp";
}
else
{
req.setAttribute("Message","Employee is added successfully.");

aEmployeeList = objActionHelper.getAllEmployees();
req.setAttribute("EmployeeList",aEmployeeList);


sForwardJSP = "/jsp/displayEmployees.jsp";
}
break;

case 3 : // Delete an employee

String sEmpID = req.getParameter("empID");
int iEmpID = Integer.parseInt(sEmpID);

if(objActionHelper.deleteEmployee(iEmpID)){
req.setAttribute("Message","Employee is deleted successfully.");
}else{
req.setAttribute("Message","No employee matches search criteria");
}

case 4 : // get all employees

aEmployeeList = objActionHelper.getAllEmployees();
if(aEmployeeList != null && aEmployeeList.size() > 0){
req.setAttribute("EmployeeList",aEmployeeList);
}else{
req.setAttribute("Message","No employees in the system");
}
sForwardJSP = "/jsp/displayEmployees.jsp";
break;


}// end of switch

}
catch(Exception ex)
{
ex.printStackTrace();
req.setAttribute("Message",ex);
sForwardJSP = "/jsp/error.jsp";
}

// getServletConfig().getServletContext().getRequestDispatcher(sForwardJSP).forward(req,res);
RequestDispatcher dispatcher = req.getRequestDispatcher(sForwardJSP);
dispatcher.forward(req,res);


}// end of processRequest


}//end of class

-------------------------------------------------------------------------------------

Create DBConnection


package com.ramsis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBConnection
{
public static Connection getConnect() {

Connection con = null;

try {
   Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=admin123");

            InitialContext initialContext = new InitialContext();
            Context context = (Context) initialContext.lookup("java:comp/env");
            DataSource ds = (DataSource) context.lookup("test");
            con = ds.getConnection();
} catch(Exception e) {
e.printStackTrace();
}
return con;
}

public static void closeResources(Connection con,ResultSet rs, Statement stmt, PreparedStatement p_stmt) {
try {
if(rs != null){ rs.close(); }
if(p_stmt!=null){ p_stmt.close();}
if(stmt != null){ stmt.close(); }
if(con != null){ con.close(); }
} catch(Exception e) {
System.out.println("Exception in Finally block");
e.printStackTrace();
}
}
}

-------------------------------------------------------------------------------------

Create Employee

package com.ramsis;
public class Employee
{
private int empID = 0;
private String name = null;
private String design = null;
private int salary = 0;

public void setEmpID(int empID){
this.empID= empID;
}
public int getEmpId(){
return this.empID;
}


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

public void setDesign(String design){
this.design= design;
}
public String getDesign(){
return this.design;
}

public void setSalary(int salary){
this.salary= salary;
}
public int getSalary(){
return this.salary;
}

}//end of class

------------------------------------------------------------------------------------

Create addEmployees.jsp


<%
String sMessage = (String)request.getAttribute("Message");
%>


<html><head><title> Add Employee</title>
<link rel="stylesheet" href="style.css" media="screen" type="text/css">

<script>
function validate()
{
if (document.employeeform.emp_id.value=="")
{
alert("Please enter Emp ID"); return false;
}
return true;
}

function saveEmployee()
{
if(validate())
{
 document.employeeform.action.value = 2;
 document.employeeform.submit();
}
}

function viewAll(){
document.viewAllForm.action.value=4;
document.viewAllForm.submit();
}

</script>

</head>
<body>

<form name="viewAllForm" action="/CRUDOnJspServlet/ActionServlet" method="post">
<input type="hidden" name="action">
</form>


<form name="employeeform" action="/CRUDOnJspServlet/ActionServlet" method="post">
<input type="hidden" name="action">

<table border="0" align="center" cellspacing="2" cellpadding="2">

<tr><td colspan=2>
<table width="100%" border="0">
<tr><td align="left" height="40" width="30%">
<a href="javascript:viewAll()"><b>View All Emplyee</b></a>
</td></tr>
</table>
</td></tr>

<tr>
<td align="left" height="20">Emp Id</td>
<td><input type="text" name="emp_id"></td>
</tr>
<tr>
<td align="left" height="20">Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td align="left" height="20">Designation</td>
<td><input type="text" name="design"></td>
</tr>
<tr>
<td align="left" height="20">Salary</td>
<td><input type="text" name="salary"></td>
</tr>

<tr>
<td align="center" colspan="2">
<input type="button" value="Add Employee" onClick="javascript:saveEmployee();"> &nbsp;&nbsp;
<input type="reset" value="Reset">
</td>
</tr>

</table>

</form>

</body>
</html>

-------------------------------------------------------------------------------------

Create displayEmployees.jsp


<%@ page import="java.util.ArrayList,com.ramsis.Employee"%>
<html>
<head>
<title> Employee Listing</title>
<link rel="stylesheet" href="style.css" media="screen" type="text/css">
</head>
<%
String sMessage = (String)request.getAttribute("Message");
Employee objEmployee = null;
ArrayList aEmployeeList = (ArrayList)request.getAttribute("EmployeeList");
%>

<script>
function addEmployee(){
document.employeeform.action.value=1;
document.employeeform.submit();
}

function deleteEmployee(empID){
if(confirm("Do you want to delete this user ? ")){
document.employeeform.empID.value  = empID;
document.employeeform.action.value = 3;
document.employeeform.submit();
}
}
</script>


<body>

<form name="employeeform" action="/CRUDOnJspServlet/ActionServlet" method="post">
<input type="hidden" name="action">
<input type="hidden" name="empID">
</form>


<table border="0" align="center" cellspacing="2" cellpadding="2" width="50%">
<tr><td colspan="2" align="left" height="20">
<%if(sMessage != null){%>
<font color="red"><%=sMessage%></font>
<%}%>
</td></tr>

<tr><td align="left">
<table width="100%" border="0">
<tr><td align="left" height="40" width="30%">
<a href="javascript:addEmployee()"><b>Add New Emplyee</b></a>
</td></tr>
</table>
<td></tr>


<%
if(aEmployeeList != null && aEmployeeList.size() > 0){
%>

<tr><td>
<!-- Employee Listing -->
<table cellspacing="0" cellpadding="2" border="1" bgcolor="lightgrey" bordercolor="blue" width="100%">
<tr>
<td align="center"><b>Emp ID</b></td>
<td align="center"><b>Name</b></td>
<td align="center"><b>Desigation</b></td>
<td align="center"><b>Salary</b></td>
<td align="center"><b>Delete</b></td>
</tr>
<%
for(int i = 0; i <aEmployeeList.size() ; i++){
objEmployee = (Employee)aEmployeeList.get(i);
%>

<tr>
<td align="center"><%=objEmployee.getEmpId()%></a></td>
<td><%=objEmployee.getName()%></td>
<td><%=objEmployee.getDesign()%></td>
<td><%=objEmployee.getSalary()%></td>
   <td align="center"><a href="javascript:deleteEmployee('<%=objEmployee.getEmpId()%>')"><p style="color:red;">Delete</p></a></td>
   
</tr>
<%
}//end of for loop
%>
</table><!- ends here -->
</td></tr>

<%
}// end of if condition
%>


</table>


</body>
</html>

-------------------------------------------------------------------------------------

create web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>CRUDOnJspServlet</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>com.ramsis.ActionServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>/ActionServlet</url-pattern>
</servlet-mapping>
 
</web-app>

-------------------------------------------------------------------------------------