Spring Angular Login & Logout Application

Last updated on May 31 2022
Santosh Prakash

Table of Contents

Spring Angular Login & Logout Application

In this blog , we are going to create a login and logout web application. This application includes a signup and login form. In this integration, we are using Spring to handle the backend part and Angular to handle the frontend part.

Working of Application

  • Once we deployed our application on the server, a welcome page generates that contains two links – signup and login.
  • A new user can choose the signup and register themselves by filling up the required details.
  • However, the existing user can use their email id and password to log in.
  • Once we logged in, we can fetch the details of existing users.
  • In the end, we can exit from the current state by clicking the logout link.

Tools to be used

  • Use any IDE to develop the Spring and Hibernate project. It may be MyEclipse/Eclipse/Netbeans. Here, we are using Eclipse.
  • MySQL for the database.
  • Use any IDE to develop the Angular project. It may be Visual Studio Code/Sublime. Here, we are using Visual Studio Code.
  • Server: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.

Technologies we used

Here, we are using the following technologies:

  • Spring 5
  • Hibernate 5
  • Angular 6
  • MYSQL

Create Database

Let’s create a database loginlogoutexample. There is no need to create a table as Hibernate automatically created it.

Spring Module

Let’s see the directory structure of Spring we need to follow:

To develop a login and logout application, follow the below steps: –

  • Add dependencies to pom.xml file.
  1. <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  2.   xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd”>
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>com. tecklearn</groupId>
  5.   <artifactId>LoginLogoutExample</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>LoginLogoutExample Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.     <properties>
  11.         <springframework.version>5.0.6.RELEASE</springframework.version>
  12.         <hibernate.version>5.2.16.Final</hibernate.version>
  13.         <mysql.connector.version>5.1.45</mysql.connector.version>
  14.         <c3po.version>0.9.5.2</c3po.version>
  15.         <maven.compiler.source>1.8</maven.compiler.source>
  16.         <maven.compiler.target>1.8</maven.compiler.target>
  17.     </properties>
  18.   <dependencies>
  19.   <!– Spring –>
  20.     <dependency>
  21.         <groupId>org.springframework</groupId>
  22.         <artifactId>spring-webmvc</artifactId>
  23.         <version>${springframework.version}</version>
  24.     </dependency>
  25.     <dependency>
  26.         <groupId>org.springframework</groupId>
  27.         <artifactId>spring-tx</artifactId>
  28.         <version>${springframework.version}</version>
  29.     </dependency>
  30.     <dependency>
  31.         <groupId>org.springframework</groupId>
  32.         <artifactId>spring-orm</artifactId>
  33.         <version>${springframework.version}</version>
  34.     </dependency>
  35.     <!– Add Jackson for JSON converters –>
  36.     <dependency>
  37.         <groupId>com.fasterxml.jackson.core</groupId>
  38.         <artifactId>jackson-databind</artifactId>
  39.         <version>2.9.5</version>
  40.     </dependency>
  41.     <!– Hibernate –>
  42.     <dependency>
  43.         <groupId>org.hibernate</groupId>
  44.         <artifactId>hibernate-core</artifactId>
  45.         <version>${hibernate.version}</version>
  46.     </dependency>
  47.     <!– MySQL –>
  48.     <dependency>
  49.         <groupId>mysql</groupId>
  50.         <artifactId>mysql-connector-java</artifactId>
  51.         <version>${mysql.connector.version}</version>
  52.     </dependency>
  53.     <!– C3PO –>
  54.     <dependency>
  55.         <groupId>com.mchange</groupId>
  56.         <artifactId>c3p0</artifactId>
  57.         <version>${c3po.version}</version>
  58.     </dependency>
  59.     <!– Servlet+JSP+JSTL –>
  60.     <dependency>
  61.         <groupId>javax.servlet</groupId>
  62.         <artifactId>javax.servlet-api</artifactId>
  63.         <version>3.1.0</version>
  64.     </dependency>
  65.     <dependency>
  66.         <groupId>javax.servlet.jsp</groupId>
  67.         <artifactId>javax.servlet.jsp-api</artifactId>
  68.         <version>2.3.1</version>
  69.     </dependency>
  70.     <dependency>
  71.         <groupId>javax.servlet</groupId>
  72.         <artifactId>jstl</artifactId>
  73.         <version>1.2</version>
  74.     </dependency>
  75.     <!– to compensate for java 9 not including jaxb –>
  76.     <dependency>
  77.         <groupId>javax.xml.bind</groupId>
  78.         <artifactId>jaxb-api</artifactId>
  79.         <version>2.3.0</version>
  80.     </dependency>
  81.     <!–  Web token dependency –>
  82.     <dependency>
  83.         <groupId>io.jsonwebtoken</groupId>
  84.         <artifactId>jjwt</artifactId>
  85.         <version>0.9.1</version>
  86.     </dependency>
  87.     <!–  JUnit dependency –>
  88.     <dependency>
  89.         <groupId>junit</groupId>
  90.         <artifactId>junit</artifactId>
  91.         <version>3.8.1</version>
  92.         <scope>test</scope>
  93.     </dependency>
  94.     <!– https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 –>
  95.     <dependency>
  96.         <groupId>org.apache.commons</groupId>
  97.         <artifactId>commons-dbcp2</artifactId>
  98.         <version>2.0</version>
  99.     </dependency>
  100.   </dependencies>
  101.   <build>
  102.     <finalName>LoginLogoutExample</finalName>
  103.   </build>
  104. </project>
  • Create the configuration classes
    Instead of XML, we perform annotation-based configuration. So, we create two classes and specify the required configuration in it.

DemoAppConfig.java

  1. package com. tecklearn.LoginLogoutExample.config;
  2. import java.beans.PropertyVetoException;
  3. import java.util.Properties;
  4. import javax.sql.DataSource;
  5. import org.hibernate.SessionFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.ComponentScan;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.context.annotation.PropertySource;
  11. import org.springframework.core.env.Environment;
  12. import org.springframework.orm.hibernate5.HibernateTransactionManager;
  13. import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
  14. import org.springframework.transaction.annotation.EnableTransactionManagement;
  15. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  16. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  17. import com.mchange.v2.c3p0.ComboPooledDataSource;
  18. @Configuration
  19. @EnableWebMvc
  20. @EnableTransactionManagement
  21. @ComponentScan(“com. tecklearn.LoginLogoutExample”)
  22. @PropertySource(value = { “classpath:persistence-mysql.properties” })
  23. @PropertySource(value = { “classpath:persistence-mysql.properties” })
  24. @PropertySource(value = { “classpath:application.properties” })
  25. public class DemoAppConfig implements WebMvcConfigurer {
  26.     @Autowired
  27.     private Environment env;
  28.     @Bean
  29.     public DataSource myDataSource() {
  30.         // create connection pool
  31.         ComboPooledDataSource myDataSource = new ComboPooledDataSource();
  32.         // set the jdbc driver
  33.         try {
  34.             myDataSource.setDriverClass(“com.mysql.jdbc.Driver”);
  35.         }
  36.         catch (PropertyVetoException exc) {
  37.             throw new RuntimeException(exc);
  38.         }
  39.         // set database connection props
  40.         myDataSource.setJdbcUrl(env.getProperty(“jdbc.url”));
  41.         myDataSource.setUser(env.getProperty(“jdbc.user”));
  42.         myDataSource.setPassword(env.getProperty(“jdbc.password”));
  43.         // set connection pool props
  44.         myDataSource.setInitialPoolSize(getIntProperty(“connection.pool.initialPoolSize”));
  45.         myDataSource.setMinPoolSize(getIntProperty(“connection.pool.minPoolSize”));
  46.         myDataSource.setMaxPoolSize(getIntProperty(“connection.pool.maxPoolSize”));
  47.         myDataSource.setMaxIdleTime(getIntProperty(“connection.pool.maxIdleTime”));
  48.         return myDataSource;
  49.     }
  50.     private Properties getHibernateProperties() {
  51.         // set hibernate properties
  52.         Properties props = new Properties();
  53.         props.setProperty(“hibernate.dialect”, env.getProperty(“hibernate.dialect”));
  54.         props.setProperty(“hibernate.show_sql”, env.getProperty(“hibernate.show_sql”));
  55.         props.setProperty(“hibernate.format_sql”, env.getProperty(“hibernate.format_sql”));
  56.         props.setProperty(“hibernate.hbm2ddl.auto”, env.getProperty(“hibernate.hbm2ddl”));
  57.         return props;
  58.     }
  59.     // need a helper method
  60.         // read environment property and convert to int
  61.         private int getIntProperty(String propName) {
  62.             String propVal = env.getProperty(propName);
  63.             // now convert to int
  64.             int intPropVal = Integer.parseInt(propVal);
  65.             return intPropVal;
  66.         }
  67.         @Bean
  68.         public LocalSessionFactoryBean sessionFactory(){
  69.             // create session factory
  70.             LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
  71.             // set the properties
  72.             sessionFactory.setDataSource(myDataSource());
  73.             sessionFactory.setPackagesToScan(env.getProperty(“hibernate.packagesToScan”));
  74.             sessionFactory.setHibernateProperties(getHibernateProperties());
  75.             return sessionFactory;
  76.         }
  77.         @Bean
  78.         @Autowired
  79.         public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
  80.             // setup transaction manager based on session factory
  81.             HibernateTransactionManager txManager = new HibernateTransactionManager();
  82.             txManager.setSessionFactory(sessionFactory);
  83.             return txManager;
  84.         }
  85. }

MySpringMvcDispatcherServletInitializer.java

  1. package com. tecklearn.LoginLogoutExample.config;
  2. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  3. public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  4.     @Override
  5.     protected Class<?>[] getRootConfigClasses() {
  6.         // TODO Auto-generated method stub
  7.         return null;
  8.     }
  9.     @Override
  10.     protected Class<?>[] getServletConfigClasses() {
  11.         return new Class[] { DemoAppConfig.class };
  12.     }
  13.     @Override
  14.     protected String[] getServletMappings() {
  15.         return new String[] { “/” };
  16.     }
  17. }
  • Create the entity classes
    Here, we are creating the following entity classes:

    1. AdminDetail.java – It is an Entity/POJO (Plain Old Java Object) class.
    2. Token.java – It is used for authentication purposes.

AdminDetail.java

  1. package com. tecklearn.LoginLogoutExample.entity;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.GenerationType;
  6. import javax.persistence.Id;
  7. import javax.persistence.Table;
  8. @Entity
  9. @Table(name=”admin_detail”)
  10. public class AdminDetail {
  11.     @Id
  12.     @GeneratedValue(strategy=GenerationType.AUTO)
  13.     @Column(name=”admin_id”)
  14.     private int adminID;
  15.     @Column(name=”email_id” , unique=true)
  16.     public String emailId;
  17.     @Column(name=”name”)
  18.     public String name;
  19.     @Column(name=”password”)
  20.     public String password;
  21.     @Column(name=”role”)
  22.     public String role;
  23.     public AdminDetail() { }
  24.     public AdminDetail(int adminID, String emailId, String name, String password, String role) {
  25.         super();
  26.         this.adminID = adminID;
  27.         this.emailId = emailId;
  28.         this.name = name;
  29.         this.password = password;
  30.         this.role = role;
  31.     }
  32.     public int getAdminID() {
  33.         return adminID;
  34.     }
  35.     public void setAdminID(int adminID) {
  36.         this.adminID = adminID;
  37.     }
  38.     public String getEmailId() {
  39.         return emailId;
  40.     }
  41.     public void setEmailId(String emailId) {
  42.         this.emailId = emailId;
  43.     }
  44.     public String getName() {
  45.         return name;
  46.     }
  47.     public void setName(String name) {
  48.         this.name = name;
  49.     }
  50.     public String getPassword() {
  51.         return password;
  52.     }
  53.     public void setPassword(String password) {
  54.         this.password = password;
  55.     }
  56.     public String getRole() {
  57.         return role;
  58.     }
  59.     public void setRole(String role) {
  60.         this.role = role;
  61.     }
  62.     @Override
  63.     public String toString() {
  64.         return “AdminDetail [adminID=” + adminID + “, emailId=” + emailId + “, name=” + name + “, password=” + password
  65.                 + “, role=” + role + “]”;
  66.     }
  67. }

Token.java

  1. package com. tecklearn.LoginLogoutExample.entity;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.GenerationType;
  6. import javax.persistence.Id;
  7. import javax.persistence.Table;
  8. @Entity
  9. @Table(name=”Token”)
  10. public class Token {
  11.     @Id
  12.     @GeneratedValue(strategy=GenerationType.AUTO)
  13.     @Column(name=”token_id”)
  14.     private int tokenID;
  15.     @Column(name=”user_id” , unique=true)
  16.     private int userID;
  17.     @Column(name=”authenticationToken”)
  18.     private String authenticationToken;
  19.     @Column(name=”secretKey”)
  20.     private String secretKey;
  21.     @Column(name=”email_id”)
  22.     private String emailId;
  23.     public Token() { }
  24.     public Token(int tokenID, int userID, String authenticationToken, String secretKey, String emailId) {
  25.         super();
  26.         this.tokenID = tokenID;
  27.         this.userID = userID;
  28.         this.authenticationToken = authenticationToken;
  29.         this.secretKey = secretKey;
  30.         this.emailId = emailId;
  31.     }
  32.     public int getTokenID() {
  33.         return tokenID;
  34.     }
  35.     public void setTokenID(int tokenID) {
  36.         this.tokenID = tokenID;
  37.     }
  38.     public int getUserID() {
  39.         return userID;
  40.     }
  41.     public void setUserID(int userID) {
  42.         this.userID = userID;
  43.     }
  44.     public String getAuthenticationToken() {
  45.         return authenticationToken;
  46.     }
  47.     public void setAuthenticationToken(String authenticationToken) {
  48.         this.authenticationToken = authenticationToken;
  49.     }
  50.     public String getSecretKey() {
  51.         return secretKey;
  52.     }
  53.     public void setSecretKey(String secretKey) {
  54.         this.secretKey = secretKey;
  55.     }
  56.     public String getEmailId() {
  57.         return emailId;
  58.     }
  59.     public void setEmailId(String emailId) {
  60.         this.emailId = emailId;
  61.     }
  62.     @Override
  63.     public String toString() {
  64.         return “Token [tokenID=” + tokenID + “, userID=” + userID + “, authenticationToken=” + authenticationToken
  65.                 + “, secretKey=” + secretKey + “, emailId=” + emailId + “]”;
  66.     }
  67. }
  • Create the DAO interfaces
    Here, we are creating two DAO interfaces to perform database related operations.

AdminDAO.java

  1. package com. tecklearn.LoginLogoutExample.DAO.interfaces;
  2. import java.util.List;
  3. import com. tecklearn.LoginLogoutExample.entity.AdminDetail;
  4. public interface AdminDAO {
  5.     public int saveAdminDetail(AdminDetail adminDetail);
  6.     public int adminLogin(String emailId , String password);
  7.     public List<AdminDetail> getAdminData();
  8. }

TokenDAO.java

  1. package com. tecklearn.LoginLogoutExample.DAO.interfaces;
  2. public interface TokenDAO {
  3.     public void saveUserEmail(String email , int adminId);
  4.     public boolean updateToken(String email , String authenticationToken , String secretKey);
  5.     public int getTokenDetail(String email );
  6.     public int tokenAuthentication(String token , int emailId);
  7. }
  • Create the DAO interface implementation classes

AdminDAOImpl.java

  1. package com. tecklearn.LoginLogoutExample.DAO.implementation;
  2. import java.util.List;
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.query.Query;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Repository;
  8. import com. tecklearn.LoginLogoutExample.DAO.interfaces.AdminDAO;
  9. import com. tecklearn.LoginLogoutExample.entity.AdminDetail;
  10. @Repository(“adminDAO”)
  11. public class AdminDAOImpl implements AdminDAO {
  12.     // Autowired SessionFactory Object So that we can get session object used for interaction with Database.
  13.     @Autowired
  14.     private SessionFactory sessionFactory;
  15.     /*
  16.      * Register Admin Details.
  17.     */
  18.     public int saveAdminDetail(AdminDetail adminDetail) {
  19.         Session session = null;
  20.         try
  21.         {
  22.             session = sessionFactory.getCurrentSession();
  23.             int id = (Integer) session.save(adminDetail);
  24.             return id;
  25.         }
  26.         catch(Exception exception)
  27.         {
  28.             System.out.println(“Excecption while saving admin Details : ” + exception.getMessage());
  29.             return 0;
  30.         }
  31.         finally
  32.         {
  33.             session.flush();
  34.         }
  35.     }
  36.     public int adminLogin(String emailId, String password) {
  37.         Session session = null;
  38.         try
  39.         {
  40.             session = sessionFactory.getCurrentSession();
  41.             Query query = session.createQuery(“from AdminDetail where emailId=:emailId and password=:password”);
  42.             query.setParameter(“emailId”, emailId);
  43.             query.setParameter(“password”, password);
  44.             List<AdminDetail> list = query.list();
  45.             int size = list.size();
  46.             if(size == 1)
  47.             {
  48.                 return list.get(0).getAdminID();
  49.             }
  50.             else
  51.             {
  52.                 return -1;
  53.             }
  54.         }
  55.         catch(Exception exception)
  56.         {
  57.             System.out.println(“Excecption while saving admin Details : ” + exception.getMessage());
  58.             return 0;
  59.         }
  60.         finally
  61.         {
  62.             session.flush();
  63.         }
  64.     }
  65.     public List<AdminDetail> getAdminData() {
  66.         Session session = null;
  67.         try
  68.         {
  69.             session = sessionFactory.getCurrentSession();
  70.             Query<AdminDetail> query = session.createQuery(“from AdminDetail”);
  71.             List<AdminDetail> list = query.list();
  72.             if(list.size() > 0)
  73.             {
  74.                 return list;
  75.             }
  76.             else
  77.             {
  78.                 return null;
  79.             }
  80.         }
  81.         catch(Exception exception)
  82.         {
  83.             System.out.println(“Excecption while saving admin Details : ” + exception.getMessage());
  84.             return null;
  85.         }
  86.         finally
  87.         {
  88.             session.flush();
  89.         }
  90.     }
  91. }

TokenDAOImpl.java

  1. package com. tecklearn.LoginLogoutExample.DAO.implementation;
  2. import java.util.List;
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.query.Query;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Repository;
  8. import com. tecklearn.LoginLogoutExample.DAO.interfaces.TokenDAO;
  9. import com. tecklearn.LoginLogoutExample.entity.Token;
  10. @Repository(“tokenDAO”)
  11. public class TokenDAOImpl implements TokenDAO  {
  12.     @Autowired
  13.     SessionFactory sessionFactory;
  14.     public void saveUserEmail(String email, int adminId) {
  15.         Session session = null;
  16.         try
  17.         {
  18.             session = sessionFactory.getCurrentSession();
  19.             Token t = new Token();
  20.             t.setUserID(adminId);
  21.             t.setEmailId(email);
  22.             session.save(t);
  23.         }
  24.         catch(Exception exception)
  25.         {
  26.             System.out.println(“Exception in saving UserEmail In Token Table :: ” + exception.getMessage());
  27.         }
  28.         finally
  29.         {
  30.             session.flush();
  31.         }
  32.     }
  33.     public boolean updateToken(String email, String authenticationToken, String secretKey) {
  34.         Session session = null;
  35.         try
  36.         {
  37.             session = sessionFactory.getCurrentSession();
  38.             Query theQuery = null;
  39.             theQuery = session.createQuery(“Update Token set authenticationToken = :authenticationToken , secretKey = :secretKey where emailId =:userEmail “);
  40.             theQuery.setParameter(“authenticationToken”, authenticationToken);
  41.             theQuery.setParameter(“userEmail”, email);
  42.             theQuery.setParameter(“secretKey”, secretKey);
  43.             int result = theQuery.executeUpdate();
  44.             if(result == 1)
  45.             {
  46.                 return true;
  47.             }
  48.             else
  49.             {
  50.                 return false;
  51.             }
  52.         }
  53.         catch(Exception exception)
  54.         {
  55.             System.out.println(“Error while updating token :: ” + exception.getMessage());
  56.             return false;
  57.         }
  58.         finally
  59.         {
  60.             session.flush();
  61.         }
  62.     }
  63.     public int getTokenDetail(String email) {
  64.         Session session = null;
  65.         try
  66.         {
  67.             session = sessionFactory.getCurrentSession();
  68.             Query<Token> query = session.createQuery(“from Token where emailId =:userEmail”);
  69.             query.setParameter(“userEmail”, email);
  70.             List<Token> tokenDetails = query.list();
  71.             if(tokenDetails.size() > 0)
  72.             {
  73.                 return tokenDetails.get(0).getTokenID();
  74.             }
  75.             else
  76.             {
  77.                 return 0;
  78.             }
  79.         }
  80.         catch(Exception exception)
  81.         {
  82.             System.out.println(“Exception while getting token ID :: ” + exception.getMessage());
  83.         }
  84.         finally
  85.         {
  86.             session.flush();
  87.         }
  88.         return 0;
  89.     }
  90.     public int tokenAuthentication(String token, int emailId) {
  91.         Session session = null;
  92.         try
  93.         {
  94.             session = sessionFactory.getCurrentSession();
  95.             Query query = session.createQuery(“from Token where userID =:userID and authenticationToken = :token”);
  96.             query.setParameter(“userID”, emailId);
  97.             query.setParameter(“token”, token);
  98.             List<Token> tokenDetails = query.list();
  99.             if(tokenDetails.size() > 0)
  100.             {
  101.                 return tokenDetails.get(0).getTokenID();
  102.             }
  103.             else
  104.             {
  105.                 return 0;
  106.             }
  107.         }
  108.         catch(Exception exception)
  109.         {
  110.             System.out.println(“Exception while Authenticating token :: “+ exception);
  111.             return 0;
  112.         }
  113.         finally
  114.         {
  115.             session.flush();
  116.         }
  117.     }
  118. }
  • Create the service layer interfaces

Here, we are creating the service layer interfaces that act as a bridge between DAO and Entity classes.

AdminService.java

  1. package com. tecklearn.LoginLogoutExample.service.interfaces;
  2. import java.util.List;
  3. import com. tecklearn.LoginLogoutExample.entity.AdminDetail;
  4. public interface AdminService {
  5.     public int saveAdminDetail(AdminDetail adminDetail);
  6.     public int adminLogin(String emailId , String password);
  7.     public List<AdminDetail> getAdminData();
  8. }

TokenService.java

  1. package com. tecklearn.LoginLogoutExample.service.interfaces;
  2. public interface TokenService {
  3.     public void saveUserEmail(String email , int adminId);
  4.     public boolean updateToken(String email , String authenticationToken , String secretKey);
  5.     public int getTokenDetail(String email );
  6.     public int tokenAuthentication(String token , int emailId);
  7. }
  • Create the service layer implementation classes

AdminServiceImpl.java

  1. package com. tecklearn.LoginLogoutExample.service.implementation;
  2. import java.util.List;
  3. import javax.transaction.Transactional;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import com. tecklearn.LoginLogoutExample.DAO.interfaces.AdminDAO;
  7. import com. tecklearn.LoginLogoutExample.entity.AdminDetail;
  8. import com. tecklearn.LoginLogoutExample.service.interfaces.AdminService;
  9. @Service(“adminService”)
  10. public class AdminServiceImpl implements AdminService {
  11.     @Autowired
  12.     private AdminDAO adminDAO;
  13.     @Transactional
  14.     public int saveAdminDetail(AdminDetail adminDetail) {
  15.         return adminDAO.saveAdminDetail(adminDetail);
  16.     }
  17.     @Transactional
  18.     public int adminLogin(String emailId, String password) {
  19.         return adminDAO.adminLogin(emailId, password);
  20.     }
  21.     @Transactional
  22.     public List<AdminDetail> getAdminData() {
  23.         return adminDAO.getAdminData();
  24.     }
  25. }

TokenServiceImpl.java

  1. package com. tecklearn.LoginLogoutExample.service.implementation;
  2. import javax.transaction.Transactional;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import com. tecklearn.LoginLogoutExample.DAO.interfaces.TokenDAO;
  6. import com. tecklearn.LoginLogoutExample.service.interfaces.TokenService;
  7. @Service(“tokenService”)
  8. public class TokenServiceImpl implements TokenService {
  9.     @Autowired
  10.     private TokenDAO tokenDAO;
  11.     @Transactional
  12.     public void saveUserEmail(String email, int adminId) {
  13.         tokenDAO.saveUserEmail(email, adminId);
  14.     }
  15.     @Transactional
  16.     public boolean updateToken(String email, String authenticationToken, String secretKey) {
  17.         return tokenDAO.updateToken(email, authenticationToken, secretKey);
  18.     }
  19.     @Transactional
  20.     public int getTokenDetail(String email) {
  21.         return tokenDAO.getTokenDetail(email);
  22.     }
  23.     @Transactional
  24.     public int tokenAuthentication(String token, int emailId) {
  25.         return tokenDAO.tokenAuthentication(token, emailId);
  26.     }
  27. }
  • Create the token class

GenerateToken.java

  1. package com.tecklearn.LoginLogoutExample.Token;
  2. import javax.crypto.spec.SecretKeySpec;
  3. import javax.xml.bind.DatatypeConverter;
  4. import java.security.Key;
  5. import java.util.Date;
  6. import java.util.Random;
  7. import io.jsonwebtoken.*;
  8. public class GenerateToken {
  9. public String[] createJWT(String id, String issuer, String subject, String role , long ttlMillis) {
  10.         //The JWT signature algorithm we will be using to sign the token
  11.         SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
  12.         long nowMillis = System.currentTimeMillis();
  13.         Date now = new Date(nowMillis);
  14.         Random random = new Random();
  15.         String secretKey = id  + Integer.toString(random.nextInt(1000));
  16.         byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
  17.         Key signingKey = null;
  18.         try{
  19.             signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
  20.         }
  21.         catch(Exception e)
  22.         {
  23.             System.out.println(“Exception while generating key ” + e.getMessage() );
  24.         }
  25.         JwtBuilder builder = Jwts.builder().setId(id)
  26.                                     .setIssuedAt(now)
  27.                                     .setSubject(subject)
  28.                                     .setIssuer(issuer)
  29.                                     .setPayload(role)
  30.                                     .signWith(signatureAlgorithm, signingKey);
  31.         //if it has been specified, let’s add the expiration
  32.         if (ttlMillis >= 0) {
  33.         long expMillis = nowMillis + ttlMillis;
  34.             Date exp = new Date(expMillis);
  35.             builder.setExpiration(exp);
  36.         }
  37.         String[] tokenInfo = {builder.compact() , secretKey};
  38.         return tokenInfo;
  39.     }
  40. }
  • Create the controller class

AdminController.java

  1. package com. tecklearn.LoginLogoutExample.restController;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.http.HttpHeaders;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.CrossOrigin;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.PathVariable;
  10. import org.springframework.web.bind.annotation.PostMapping;
  11. import org.springframework.web.bind.annotation.RequestBody;
  12. import org.springframework.web.bind.annotation.RequestHeader;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RestController;
  15. import com. tecklearn.LoginLogoutExample.entity.AdminDetail;
  16. import com. tecklearn.LoginLogoutExample.service.interfaces.AdminService;
  17. import com. tecklearn.LoginLogoutExample.service.interfaces.TokenService;
  18. import com.tecklearn.LoginLogoutExample.Token.GenerateToken;
  19. @RestController
  20. @RequestMapping(“/api”)
  21. @CrossOrigin(origins = “http://localhost:4200”, allowedHeaders = “*”, exposedHeaders = “Authorization”)
  22. public class AdminController {
  23.     @Autowired
  24.     private AdminService adminService;
  25.     @Autowired
  26.     private TokenService tokenService;
  27.     GenerateToken generateToken = new GenerateToken();
  28.     @PostMapping(“/saveAdmin”)
  29.     public int saveAdminDetail(@RequestBody AdminDetail adminDetail) {
  30.         return adminService.saveAdminDetail(adminDetail);
  31.     }
  32.     @PostMapping(“/login”)
  33.     public ResponseEntity<Integer> login(@RequestBody AdminDetail adminDetail)
  34.     {
  35.         int status;
  36.         HttpHeaders httpHeader = null;
  37.         // Authenticate User.
  38.         status = adminService.adminLogin(adminDetail.getEmailId(), adminDetail.getPassword());
  39.         /*
  40.          * If User is authenticated then Do Authorization Task.
  41.          */
  42.         if (status > 0)
  43.         {
  44.             /*
  45.              * Generate token.
  46.              */
  47.             String tokenData[] = generateToken.createJWT(adminDetail.getEmailId(), ” tecklearn”, “JWT Token”,
  48.                     adminDetail.getRole(), 43200000);
  49.             // get Token.
  50.             String token = tokenData[0];
  51.             System.out.println(“Authorization :: ” + token);
  52.             // Create the Header Object
  53.             httpHeader = new HttpHeaders();
  54.             // Add token to the Header.
  55.             httpHeader.add(“Authorization”, token);
  56.             // Check if token is already exist.
  57.             long isUserEmailExists = tokenService.getTokenDetail(adminDetail.getEmailId());
  58.             /*
  59.              * If token exist then update Token else create and insert the token.
  60.              */
  61.             if (isUserEmailExists > 0)
  62.             {
  63.                 tokenService.updateToken(adminDetail.getEmailId(), token, tokenData[1]);
  64.             }
  65.             else
  66.             {
  67.                 tokenService.saveUserEmail(adminDetail.getEmailId(), status);
  68.                 tokenService.updateToken(adminDetail.getEmailId(), token, tokenData[1]);
  69.             }
  70.             return new ResponseEntity<Integer>(status, httpHeader, HttpStatus.OK);
  71.         }
  72.         // if not authenticated return  status what we get.
  73.         else
  74.         {
  75.             return new ResponseEntity<Integer>(status, httpHeader, HttpStatus.OK);
  76.         }
  77.     }
  78.     @GetMapping(“/getAdminData/{adminId}”)
  79.     public List<AdminDetail> getAdminData(@PathVariable int adminId, @RequestHeader(“Authorization”) String authorizationToken)
  80.     {
  81.         String token[] = authorizationToken.split(” “);
  82.         int result = tokenService.tokenAuthentication(token[1], adminId);
  83.         if (result > 0) {
  84.             return adminService.getAdminData();
  85.         } else {
  86.             return null;
  87.         }
  88.     }
  89. }
  • reate the properties file

Here, we are creating the properties file inside the src/main/resources in the project. The following file contains the hibernate connection configuration.

persistence-mysql.properties

  1. #
  2. # JDBC connection properties
  3. #
  4. jdbc.driver=com.mysql.jdbc.Driver
  5. jdbc.url=jdbc:mysql://localhost:3306/loginlogoutexample?useSSL=false
  6. jdbc.user=root
  7. jdbc.password=
  8. #
  9. # Connection pool properties
  10. #
  11. connection.pool.initialPoolSize=5
  12. connection.pool.minPoolSize=5
  13. connection.pool.maxPoolSize=20
  14. connection.pool.maxIdleTime=3000
  15. #
  16. # Hibernate properties
  17. #
  18. <!– hibernate.dialect=org.hibernate.dialect.MySQLDialect –>
  19. hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
  20. hibernate.show_sql=true
  21. hibernate.format_sql=true
  22. hibernate.hbm2ddl=update
  23. hibernate.packagesToScan=com. tecklearn.LoginLogoutExample.entity

Angular Module

Let’s see the directory structure of Angular we need to follow:

image002 10
Angular
  • Create an Angular project

Let’s create an Angular project by using the following command:

ng new LoginLogoutExample

Here, LoginLogoutExample is the name of the project.

Install Bootstrap CSS framework

Use the following command to install bootstrap in the project.

npm install bootstrap@3.3.7 –save

Now, include the following code in the style.css file.

  1. @import “~bootstrap/dist/css/bootstrap.css”;
  • Generate Components
    Open the project in visual studio and then use the following command to generate the following Angular components:
    ng g c Home
    ng g c Login
    ng g c Signup
    ng g c Profile
image004 9
include

Let’s also create a service class by using the following command: –

ng g s services/Admin

image006 8
service
  • Edit app.module.ts file
    • Implement Routing – Here, we are importing RouterModule present inside @angular/router package and define path in the import array.
    • Import ReactiveFormsModule – Here, we are importing ReactiveFormsModule for reactive forms and specify it in imports array.
    • Import HttpModule – Here, we are importing HttpModule for server requests and specify it in imports array.
    • Register Service class – Here, we are mentioning the service class in providers array.
  1. import { BrowserModule } from ‘@angular/platform-browser’;
  2. import { NgModule } from ‘@angular/core’;
  3. // import Http module
  4. import { HttpModule} from ‘@angular/http’;
  5. // import ReactiveFormsModule for reactive form
  6. import { ReactiveFormsModule } from ‘@angular/forms’;
  7. // import module for Routing.
  8. import { RouterModule } from ‘@angular/router’;
  9. import { AppComponent } from ‘./app.component’;
  10. import { LoginComponent } from ‘./login/login.component’;
  11. import { HomeComponent } from ‘./home/home.component’;
  12. import { SignupComponent } from ‘./signup/signup.component’;
  13. import { AdminService } from ‘./services/admin.service’;
  14. import { ProfileComponent } from ‘./profile/profile.component’;
  15. @NgModule({
  16.   declarations: [
  17.     AppComponent,
  18.     LoginComponent,
  19.     HomeComponent,
  20.     SignupComponent,
  21.     ProfileComponent
  22.   ],
  23.   imports: [
  24.     BrowserModule,
  25.     ReactiveFormsModule,
  26.     HttpModule,
  27.     RouterModule.forRoot([
  28.       {
  29.         path : ”,
  30.         component : HomeComponent
  31.       },
  32.       {
  33.         path : ‘login’,
  34.         component : LoginComponent
  35.       },
  36.       {
  37.         path : ‘signup’,
  38.         component : SignupComponent
  39.       },
  40.       {
  41.         path : ‘profile/:adminId’,
  42.         component : ProfileComponent
  43.       }
  44.     ])
  45.   ],
  46.   providers: [
  47.     AdminService
  48.   ],
  49.   bootstrap: [AppComponent]
  50. })
  51. export class AppModule { }
  • Edit the app.component.html file
  1. <router-outlet></router-outlet>
  • Edit the home.component.html file
    This is a welcome page of the application that includes two links – SignUp and Login.
  1. <div style=”text-align: center”>
  2.     <h2>  <a [routerLink]=”[‘/signup’]”>SignUp</a> <br><br> </h2>
  3.     <h2>  <a [routerLink]=”[‘/login’]”>Login</a> <br><br> </h2>
  4. </div>
image007 7
welcome page
  • Create the AdminDetail.ts class

Let’s create a class by using the following command: –

ng g class classes/AdminDetail

image008 9
class

Now, specify the required fields within AdminDetail class.

  1. export class AdminDetail {
  2.     emailId : string;
  3.     name : string;
  4.     password : string ;
  5.     role : string;
  6. }

The purpose of this class is to map the specified fields with the fields of Spring entity class.

  • Edit the admin.service.ts file
  1. import { Injectable } from ‘@angular/core’;
  2. import { Http, RequestOptions , Headers } from ‘@angular/http’;
  3. import { Observable } from ‘rxjs’;
  4. import { AdminDetail } from ‘../classes/admin-detail’;
  5. import { Router } from ‘@angular/router’;
  6. import { JwtHelperService } from ‘@auth0/angular-jwt’;
  7. @Injectable({
  8.   providedIn: ‘root’
  9. })
  10. export class AdminService {
  11.   // Base URL
  12.   private  baseUrl = “http://localhost:8080/LoginLogoutExample/api/”;
  13.   constructor(private http: Http, private router : Router) { }
  14.   saveAdminDetails(adminDetail : AdminDetail) : Observable<any>
  15.   {
  16.       let url = this.baseUrl + “saveAdmin”;
  17.       return this.http.post(url,adminDetail);
  18.   }
  19.   login(adminDetail : AdminDetail) : Observable<any>
  20.   {
  21.       let url = this.baseUrl + “login”;
  22.       return this.http.post(url, adminDetail);
  23.   }
  24.   logout()
  25.   {
  26.     // Remove the token from the localStorage.
  27.     localStorage.removeItem(‘token’);
  28.     this.router.navigate([”]);
  29.   }
  30.   /*
  31.   * Check whether User is loggedIn or not.
  32.   */
  33.   isLoggedIn() {
  34.     // create an instance of JwtHelper class.
  35.     let jwtHelper = new JwtHelperService();
  36.     // get the token from the localStorage as we have to work on this token.
  37.     let token = localStorage.getItem(‘token’);
  38.     // check whether if token have something or it is null.
  39.     if(!token)
  40.     {
  41.       return false;
  42.     }
  43.     // get the Expiration date of the token by calling getTokenExpirationDate(String) method of JwtHelper class. this method accepts a string value which is nothing but a token.
  44.     if(token)
  45.     {
  46.       let expirationDate = jwtHelper.getTokenExpirationDate(token);
  47.       // check whether the token is expired or not by calling isTokenExpired() method of JwtHelper class.
  48.       let isExpired = jwtHelper.isTokenExpired(token);
  49.       return !isExpired;
  50.     }
  51.   }
  52.   getAdminDetail(adminId) : Observable<any>
  53.   {
  54.       let url = this.baseUrl + “getAdminData/” + adminId;
  55.        // create an instance of Header object.
  56.       let headers = new Headers();
  57.       // get token from localStorage.
  58.       let token = localStorage.getItem(‘token’);
  59.       // Append Authorization header.
  60.       headers.append(‘Authorization’ , ‘Bearer ‘ + token);
  61.       // create object of RequestOptions and include that in it.
  62.       let options = new RequestOptions( { headers : headers } );
  63.       return this.http.get(url , options);
  64.   }
  65. }
  • Edit the signup.component.ts file
  1. import { Component, OnInit } from ‘@angular/core’;
  2. import { FormGroup, FormControl, Validators } from ‘@angular/forms’;
  3. import { AdminDetail } from ‘../classes/admin-detail’;
  4. import { AdminService } from ‘../services/admin.service’;
  5. import { Router } from ‘@angular/router’;
  6. @Component({
  7.   selector: ‘app-signup’,
  8.   templateUrl: ‘./signup.component.html’,
  9.   styleUrls: [‘./signup.component.css’]
  10. })
  11. export class SignupComponent implements OnInit {
  12.   private adminDetail = new AdminDetail();
  13.   constructor(private adminService : AdminService, private router : Router) { }
  14.   ngOnInit() {
  15.   }
  16.   // create the form object.
  17.   form = new FormGroup({
  18.       fullName : new FormControl(” , Validators.required),
  19.       email : new FormControl(” , Validators.required),
  20.       password : new FormControl(” , Validators.required),
  21.       confirmPassword : new FormControl(” , Validators.required),
  22.       role : new FormControl(” , Validators.required),
  23.   });
  24.   AdminForm(AdminInformation)
  25.   {
  26.      let pass = this.Password.value;
  27.      let confirmPass = this.ConfirmPassword.value;
  28.      if(pass == confirmPass)
  29.      {
  30.         this.adminDetail.name = this.FullName.value;
  31.         this.adminDetail.emailId = this.Email.value;
  32.         this.adminDetail.password = this.Password.value;
  33.         this.adminDetail.role = this.Role.value;
  34.         this.adminService.saveAdminDetails(this.adminDetail).subscribe(
  35.           response => {
  36.               let result = response.json();
  37.               if(result > 0)
  38.               {
  39.                 this.router.navigate([‘/login’]);
  40.               }
  41.               else
  42.               {
  43.                   alert(“error occur while registring User. please try after sometime.”)
  44.               }
  45.           },
  46.           error => {
  47.             alert(“error occur while registring User. please try after sometime.”)
  48.           }
  49.         );
  50.      }
  51.      else
  52.      {
  53.         alert(“Password and confirm password not match.”);
  54.      }
  55.   }
  56.   get FullName(){
  57.     return this.form.get(‘fullName’);
  58.   }
  59.   get Email(){
  60.       return this.form.get(’email’);
  61.   }
  62.   get Password(){
  63.       return this.form.get(‘password’);
  64.   }
  65.   get ConfirmPassword(){
  66.       return this.form.get(‘confirmPassword’);
  67.   }
  68.   get Role(){
  69.       return this.form.get(‘role’);
  70.   }
  71. }
  • Edit the signup.component.html file
  1. <h2>SignUp form</h2>
  2. <form [formGroup]=”form” #AdminInformation (ngSubmit)=”AdminForm(AdminInformation)”>
  3.   <div class=”row”>
  4.     <div class=” col-md-offset-1 col-md-4″>
  5.         <label for=”fullName”> Name </label>
  6.         <input formControlName=”fullName” class=”form-control” type=”text”>
  7.     </div>
  8.   </div>
  9.   <div class=”row”>
  10.     <div class=” col-md-offset-1 col-md-4″>
  11.         <label for=”email”> Email </label>
  12.         <input formControlName=”email” class=”form-control” type=”text”>
  13.     </div>
  14.   </div>
  15.   <div class=”row”>
  16.     <div class=” col-md-offset-1 col-md-4″>
  17.         <label for=”password”> Password </label>
  18.         <input formControlName=”password” class=”form-control” type=”password”>
  19.     </div>
  20.   </div>
  21.   <div class=”row”>
  22.     <div class=” col-md-offset-1 col-md-4″>
  23.         <label for=”confirmPassword”> Confirm Password </label>
  24.         <input formControlName=”confirmPassword” class=”form-control” type=”password”>
  25.     </div>
  26.   </div>
  27.   <div class=”row”>
  28.     <div class=” col-md-offset-1 col-md-4″>
  29.         <label for=”role”> Role </label>
  30.         <input formControlName=”role” class=”form-control” type=”text”>
  31.     </div>
  32.   </div>
  33.   <div class=”row” style=”margin-top: 40px;”>
  34.     <div class=”col-md-offset-1 col-md-4″>
  35.         <button class=”btn btn-md btn-primary btn-style”  >Save</button>
  36.     </div>
  37.   </div>
  38. </form>
image009 4
Confirm
  • Edit the login.component.ts file
  1. import { Component, OnInit } from ‘@angular/core’;
  2. import { FormGroup, Validators, FormControl } from ‘@angular/forms’;
  3. import { AdminDetail } from ‘../classes/admin-detail’;
  4. import { AdminService } from ‘../services/admin.service’;
  5. import { Router } from ‘@angular/router’;
  6. @Component({
  7.   selector: ‘app-login’,
  8.   templateUrl: ‘./login.component.html’,
  9.   styleUrls: [‘./login.component.css’]
  10. })
  11. export class LoginComponent implements OnInit {
  12.   private adminDetail = new AdminDetail();
  13.   constructor(private adminService : AdminService, private router : Router) { }
  14.   ngOnInit() {
  15.     if((this.adminService.isLoggedIn()) )
  16.     {
  17.         this.router.navigate([‘/profile’ , localStorage.getItem(‘id’)]);
  18.     }
  19.     else
  20.     {
  21.         this.router.navigate([‘/login’]);
  22.     }
  23.   }
  24.   // create the form object.
  25.   form = new FormGroup({
  26.     email : new FormControl(” , Validators.required),
  27.     password : new FormControl(” , Validators.required)
  28.   });
  29.   Login(LoginInformation)
  30.   {
  31.       this.adminDetail.emailId = this.Email.value;
  32.       this.adminDetail.password = this.Password.value;
  33.       this.adminService.login(this.adminDetail).subscribe(
  34.         response => {
  35.             let result =  response.json();
  36.             if(result > 0)
  37.             {
  38.               let token = response.headers.get(“Authorization”);
  39.               localStorage.setItem(“token” , token);
  40.               localStorage.setItem(“id” , result);
  41.               this.router.navigate([‘/profile’, result]);
  42.             }
  43.             if(result == -1)
  44.             {
  45.               alert(“please register before login Or Invalid combination of Email and password”);
  46.             }
  47.         },
  48.         error => {
  49.             console.log(“Error in authentication”);
  50.         }
  51.       );
  52.   }
  53.   get Email(){
  54.       return this.form.get(’email’);
  55.   }
  56.   get Password(){
  57.       return this.form.get(‘password’);
  58.   }
  59. }
  • Edit the login.component.html file
  1. <h2>Login form</h2>
  2. <form [formGroup]=”form” #LoginInformation (ngSubmit)=”Login(LoginInformation)”>
  3.   <div class=”row”>
  4.     <div class=” col-md-offset-1 col-md-4″>
  5.         <label for=”email”> Email </label>
  6.         <input formControlName=”email” class=”form-control” type=”text”>
  7.     </div>
  8.   </div>
  9.   <div class=”row”>
  10.     <div class=” col-md-offset-1 col-md-4″>
  11.         <label for=”password”> Password </label>
  12.         <input formControlName=”password” class=”form-control” type=”password”>
  13.     </div>
  14.   </div>
  15.   <div class=”row” style=”margin-top: 40px;”>
  16.     <div class=”col-md-offset-1 col-md-4″>
  17.         <button class=”btn btn-md btn-primary btn-style”  >Login</button>
  18.     </div>
  19.   </div>
  20. </form>
image011 5
Login form
  • Edit the profile.component.ts file
    Once the user logged in, it will redirected to the profile component.
  1. import { Component, OnInit } from ‘@angular/core’;
  2. import { AdminService } from ‘../services/admin.service’;
  3. import { ActivatedRoute, Router } from ‘@angular/router’;
  4. @Component({
  5.   selector: ‘app-profile’,
  6.   templateUrl: ‘./profile.component.html’,
  7.   styleUrls: [‘./profile.component.css’]
  8. })
  9. export class ProfileComponent implements OnInit {
  10.   private adminId;
  11.   private haveData= 0;
  12.   private data = [];
  13.   private dataRequest = false;
  14.   constructor(private adminService  : AdminService, private route : ActivatedRoute, private router : Router) { }
  15.   ngOnInit() {
  16.     if((this.adminService.isLoggedIn()) )
  17.     {
  18.       this.route.paramMap.subscribe(params => {
  19.         this.adminId =+ params.get(‘adminId’);
  20.       });
  21.     }
  22.     else
  23.     {
  24.         this.router.navigate([‘/login’]);
  25.     }
  26.   }
  27.   getAdminData()
  28.   {
  29.       this.haveData = 0;
  30.       this.dataRequest = true;
  31.       this.adminService.getAdminDetail(this.adminId).subscribe(
  32.           response => {
  33.               let result = response.json();
  34.               this.data = result;
  35.               if(result == ” “)
  36.               {
  37.                   this.haveData = 0;
  38.               }
  39.               else
  40.               {
  41.                 this.haveData = this.haveData + 1;
  42.               }
  43.           },
  44.           error => {
  45.               console.log(“error while getting Admin Data”);
  46.           }
  47.       );
  48.   }
  49. }
  • Edit the profile.component.html file
  1. <div style=”text-align: right ; margin-right: 40px;”>
  2.   <h2>  <a (click)= “adminService.logout()”>Logout</a> <br> </h2>
  3. </div>
  4. <div style=”text-align: center ; margin-right: 40px;”>
  5.   <h2>  <a (click)=”getAdminData()” >Get Admin Details</a> <br> </h2>
  6. </div>
  7. <div *ngIf=”haveData > 0 && dataRequest”>
  8.     <table class=”table table-responsive table-striped”>
  9.         <tr>
  10.           <th>Email ID</th>
  11.           <th>Name</th>
  12.           <th>Password</th>
  13.           <th>Role</th>
  14.         </tr>
  15.         <ng-container *ngFor = “let item of data”>
  16.             <tr>
  17.               <td>{{item.emailId}}</td>
  18.               <td>{{item.name}}</td>
  19.               <td>{{item.password}}</td>
  20.               <td>{{item.role}}</td>
  21.             </tr>
  22.         </ng-container>
  23.       </table>
  24. </div>
  25. <div *ngIf=”haveData == 0 && dataRequest”>
  26.     Don’t have Data.
  27. </div>

User can fetch the admin details by clicking on the Get Admin Details link.

image014
Logout

Now, the user can exit the current state by clicking Logout.

So, this brings us to the end of blog. This Tecklearn ‘Spring Angular Login & Logout Application’ blog helps you with commonly asked questions if you are looking out for a job in Angular JS and Front-End Development. If you wish to learn Angular JS and build a career in Front-End Development domain, then check out our interactive, Angular JS Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/angular-js-training/

Angular JS Training

About the Course

Angular JS certification training is designed for developers who are responsible for building applications using AngularJS. Through a combination of presentations and hands-on practices, participants will explore Angular comprehensively and learn to build components, directives, template-driven forms, routing, etc. for complex data-centric (enterprise) applications. This Angular online training will update your knowledge and skills with the current Angular version to lift your career.

Why Should you take Angular JS Training?

  • The average salary for “Angular Developer” ranges from approximately $92,814 per year for a Developer to $113,069 per year for a Full Stack Developer (Indeed.com).
  • YouTube, Google, Cisco, Nike, Samsung, Microsoft, Forbes, BMW and many Fortune 500 companies are using Angular as their front-end development framework to deliver an engaging user experience.
  • Angular’s powerful cross-platform feature allows developers to build progressive web applications and native mobile applications.

What you will Learn in this Course?

Introduction to Angular

  • Introduction to Angular
  • Comparison between front-end tools
  • Angular Architecture
  • Building blocks of Angular
  • Angular Installation
  • Angular CLI
  • Angular CLI commands
  • Angular Modules

Angular Components and Data Binding

  • Working of Angular Applications
  • Angular App Bootstrapping
  • Angular Components
  • Creating A Component Through Angular CLI
  • Ways to specify selectors
  • Template and styles
  • Installing bootstrap to design application
  • Data Binding
  • Types of Data Binding
  • Component Interaction using @Input and @Output decorator
  • Angular Animations

TypeScript

  • What is TypeScript
  • Need of TypeScript
  • How to install TypeScript
  • Nodemon for monitoring changes
  • Interfaces in Class, String Templates, Maps,
  • Sets and Object Restructuring

Directives and Pipes in Angular

  • Angular Directives
  • @Component Directive
  • Structural Directives
  • Attribute Directives
  • Custom Directives
  • Pipes
  • Built-in Pipes
  • Chaining pipes
  • Custom pipes
  • Pipe Transform Interface & Transform Function
  • Pure and Impure pipes

Angular Services and Dependency Injection

  • Angular service
  • Need for a service
  • Dependency Injection
  • Creating a service
  • Hierarchical Injector
  • Injecting A Service into Another Service
  • Observables
  • RxJS Library
  • Angular’s Interaction with Backend
  • Parts of an Http Request
  • HttpClient

Forms in Angular

  • Forms in Angular
  • What are their functions
  • Advantages of Forms
  • Various Types of Forms
  • What is Angular Validation and Model driven approach

Angular Routing

  • Angular Routing
  • Angular Routing benefits and features
  • Building a single page application and updating it dynamically with Angular Routing
  • What is Parameter Routing
  • Router Lifecycle Hooks and Child Routes

Authentication and Security in Angular

  • What is Authentication?
  • Authentication and authorization
  • Types of Authentication
  • Where to store tokens?
  • JSON Web Tokens (JWT)
  • Authentication in Angular application
  • Security threats in web application

Testing Angular applications

  • Testing of Angular applications
  • Deployment of Angular Test Bed for testing on Angular framework
  • Setup of various tools for testing
  • Testing services in Angular Framework
  • E2E and Document Object Model testing

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Spring Angular Login & Logout Application"

Leave a Message

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