English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 섹션에서는 로그인 및 로그아웃 웹 애플리케이션을 생성합니다. 이 애플리케이션은 등록 및 로그인 양식을 포함하고 있습니다. 이 통합에서는 Spring이 백엔드 부분을 처리하고 Angular이 프론트엔드 부분을 처리합니다.
서버에 애플리케이션을 배포하면 환영 페이지가 생성되며 두 개의 링크가 포함됩니다-등록 및 로그인신규 사용자는 등록을 선택하고 필요한 세부 정보를 입력하여 등록할 수 있습니다.그러나 기존 사용자는 이메일 ID와 비밀번호를 사용하여 로그인할 수 있습니다.로그인 후, 기존 사용자의 상세 정보를 얻을 수 있습니다.마지막으로, 로그아웃 링크를 클릭하여 현재 상태를 탈퇴할 수 있습니다.
Spring 및 Hibernate 프로젝트를 개발하기 위해 어떤 IDE를 사용하든 상관없습니다. MyEclipse일 수도 있습니다./Eclipse/Netbeans. 여기서는 Eclipse를 사용하고 있습니다.데이터베이스에 사용되는 MySQL.Angular 프로젝트를 개발하기 위해 어떤 IDE를 사용하든 상관없습니다. Visual Studio 코드일 수도 있습니다./Sublime. 여기서는 Visual Studio Code를 사용하고 있습니다.서버: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.
여기서는 다음 기술을 사용하고 있습니다:
Spring5 Hibernate5 Angular6 MYSQL
데이터베이스를 생성하겠습니다 loginlogoutexample 표를 생성하지 않아도 됩니다. Hibernate가 자동으로 생성합니다.
우리가 따라야 할 Spring 디렉토리 구조를 확인해 보겠습니다:
로그인 및 로그아웃 애플리케이션을 개발하려면 다음 단계를 따라주세요: -
pom.xml 파일에 의존성을 추가하세요。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0/modelVersion> <groupId>com.w3codebox/groupId> <artifactId>LoginLogoutExample/artifactId> <packaging>war/packaging> <version>0.0.1-SNAPSHOT/version> <name>LoginLogoutExample Maven Webapp/name> <url>http://maven.apache.org/url> <properties> <springframework.version>5.0.6.RELEASE</springframework.version> <hibernate.version>5.2.16.Final</hibernate.version> <mysql.connector.version>5.1.45</mysql.connector.version> <c3po.version>0.9.5.2</c3po.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <!-- Add Jackson for JSON converters --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java/artifactId> <version>${mysql.connector.version}</version> </dependency> <!-- C3PO --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>${c3po.version}</version> </dependency> <!-- Servlet+JSP+JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api/artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api/artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl/artifactId> <version>1.2</version> </dependency> <!-- java를 대체하기 위해 9 jaxb를 포함하지 않음 --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api/artifactId> <version>2.3.0</version> </dependency> <!-- Web 토큰 의존성 --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- JUnit 의존성 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.0</version> </dependency> </dependencies> <build> <finalName>LoginLogoutExample</finalName> </build> </project>
구성 클래스 생성
우리는 XML 대신 주석 기반 설정을 실행합니다. 따라서, 필요한 설정을 지정하기 위해 두 개의 클래스를 생성합니다.
DemoAppConfig.java
package com.w;3codebox.LoginLogoutExample.config; import java.beans.PropertyVetoException; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.mchange.v2.c3p0.ComboPooledDataSource; @Configuration @EnableWebMvc @EnableTransactionManagement @ComponentScan("com.w3codebox.LoginLogoutExample @PropertySource(value = { "classpath:persistence-mysql.properties" }) @PropertySource(value = { "classpath:persistence-mysql.properties" }) @PropertySource(value = { "classpath:application.properties" }) public class DemoAppConfig implements WebMvcConfigurer { @Autowired private Environment env; @Bean public DataSource myDataSource() { // connection pool 생성 ComboPooledDataSource myDataSource = new ComboPooledDataSource(); // jdbc 드라이버 설정 try { myDataSource.setDriverClass("com.mysql.jdbc.Driver"); } catch (PropertyVetoException exc) { throw new RuntimeException(exc); } // database connection 속성 설정 myDataSource.setJdbcUrl(env.getProperty("jdbc.url")); myDataSource.setUser(env.getProperty("jdbc.user")); myDataSource.setPassword(env.getProperty("jdbc.password")); // connection pool 속성 설정 myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize")); myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize")); myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize")); myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime")); return myDataSource; } private Properties getHibernateProperties() { // hibernate 속성 설정 Properties props = new Properties(); props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); props.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql")); props.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl")); return props; } // need a helper method // read environment property and convert to int private int getIntProperty(String propName) { String propVal = env.getProperty(propName); // now convert to int int intPropVal = Integer.parseInt(propVal); return intPropVal; } @Bean public LocalSessionFactoryBean sessionFactory(){ // create session factory LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); // set the properties sessionFactory.setDataSource(myDataSource()); sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan")); sessionFactory.setHibernateProperties(getHibernateProperties()); return sessionFactory; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { // session factory를 기반으로 트랜잭션 관리자 설정 HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory); return txManager; } }
MySpringMvcDispatcherServletInitializer.java
package com.w;3codebox.LoginLogoutExample.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { // TOdo Auto-생성된 메서드 스탑 return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { DemoAppConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
엔티티 클래스 생성
이곳에서 다음과 같은 엔티티 클래스를 생성하겠습니다: AdminDetail.java-이것은 Entity입니다/POJO(일반적인 오래된 Java 객체) 클래스. Token.java-용도 인증.
AdminDetail.java
package com.w;3codebox.LoginLogoutExample.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="admin_detail") public class AdminDetail { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="관리자ID") private int 관리자ID; @Column(name="email_id", unique=true) public String 이메일ID; @Column(name="이름") public String 이름; @Column(name="패스워드") public String 패스워드; @Column(name="롤") public String 롤; public AdminDetail() { } public AdminDetail(int 관리자ID, String 이메일ID, String 이름, String 패스워드, String 롤) { super(); this.관리자ID = 관리자ID; this.emailId = emailId; this.이름 = 이름; this.패스워드 = 패스워드; this.롤 = 롤; } public int get관리자ID() { return 관리자ID; } public void set관리자ID(int 관리자ID) { this.관리자ID = 관리자ID; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getName() { return 이름; } public void setName(String 이름) { this.이름 = 이름; } public String get패스워드() { return 패스워드; } public void set패스워드(String 패스워드) { this.패스워드 = 패스워드; } public String get롤() { return 롤; } public void set롤(String 롤) { this.롤 = 롤; } @Override public String toString() { return "AdminDetail [관리자ID=" + 관리자ID + ", emailId=" + emailId + ", 이름=" + 이름 + ", 패스워드=" + 패스워드 + ", 롤=" + 롤 + "]"; } }
Token.java
package com.w;3codebox.LoginLogoutExample.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Token") public class Token { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="token_id") private int tokenID; @Column(name="user_id", unique=true) private int userID; @Column(name="authenticationToken") private String authenticationToken; @Column(name="secretKey") private String secretKey; @Column(name="email_id") private String emailId; public Token() { } public Token(int tokenID, int userID, String authenticationToken, String secretKey, String emailId) { super(); this.tokenID = tokenID; this.userID = userID; this.authenticationToken = authenticationToken; this.secretKey = secretKey; this.emailId = emailId; } public int getTokenID() { return tokenID; } public void setTokenID(int tokenID) { this.tokenID = tokenID; } public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public String getAuthenticationToken() { return authenticationToken; } public void setAuthenticationToken(String authenticationToken) { this.authenticationToken = authenticationToken; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } @Override public String toString() { return "Token [tokenID=" + tokenID + ", userID=" + userID + ", authenticationToken=" + authenticationToken + ", secretKey=" + secretKey + ", emailId=" + emailId + "]"; } }
创建DAO接口
在这里,我们将创建两个DAO接口以执行与数据库相关的操作。
AdminDAO.java
package com.w;3codebox.LoginLogoutExample.DAO.interfaces; import java.util.List; import com.w3codebox.LoginLogoutExample.entity.AdminDetail; public interface AdminDAO { public int saveAdminDetail(AdminDetail adminDetail); public int adminLogin(String emailId , String password); public List<AdminDetail> getAdminData(); }
TokenDAO.java
package com.w;3codebox.LoginLogoutExample.DAO.interfaces; public interface TokenDAO { public void saveUserEmail(String email , int adminId); public boolean updateToken(String email , String authenticationToken , String secretKey); public int getTokenDetail(String email ); public int tokenAuthentication(String token , int emailId); }
创建DAO接口实现类
AdminDAOImpl.java
package com.w;3codebox.LoginLogoutExample.DAO.implementation; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.w3codebox.LoginLogoutExample.DAO.interfaces.AdminDAO; import com.w3codebox.LoginLogoutExample.entity.AdminDetail; @Repository("adminDAO") public class AdminDAOImpl implements AdminDAO { // Autowired SessionFactory Object So that we can get session object used for interaction with Database. @Autowired private SessionFactory sessionFactory; /* * Register Admin Details. */ public int saveAdminDetail(AdminDetail adminDetail) { Session session = null; try { session = sessionFactory.getCurrentSession(); int id = (Integer) session.save(adminDetail); return id; } catch(Exception exception) { System.out.println("Excecption while saving admin Details : "); + exception.getMessage()); return 0; } finally { session.flush(); } } public int adminLogin(String emailId, String password) { Session session = null; try { session = sessionFactory.getCurrentSession(); Query query = session.createQuery("from AdminDetail where emailId=:emailId and password=:password"); query.setParameter("emailId", emailId); query.setParameter("password", password); List<AdminDetail> list = query.list(); int size = list.size(); if(size == 1) { return list.get(0).getAdminID(); } else { return -1; } } catch(Exception exception) { System.out.println("Excecption while saving admin Details : "); + exception.getMessage()); return 0; } finally { session.flush(); } } public List<AdminDetail> getAdminData() { Session session = null; try { session = sessionFactory.getCurrentSession(); Query<AdminDetail> query = session.createQuery("from AdminDetail"); List<AdminDetail> list = query.list(); if(list.size() > 0) { return list; } else { return null; } } catch(Exception exception) { System.out.println("Excecption while saving admin Details : "); + exception.getMessage()); return null; } finally { session.flush(); } } }
TokenDAOImpl.java
package com.w;3codebox.LoginLogoutExample.DAO.implementation; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.w3codebox.LoginLogoutExample.DAO.interfaces.TokenDAO; import com.w3codebox.LoginLogoutExample.entity.Token; @Repository("tokenDAO") public class TokenDAOImpl implements TokenDAO { @Autowired SessionFactory sessionFactory; public void saveUserEmail(String email, int adminId) { Session session = null; try { session = sessionFactory.getCurrentSession(); Token t = new Token(); t.setUserID(adminId); t.setEmailId(email); session.save(t); } catch(Exception exception) { System.out.println("Exception in saving UserEmail In Token Table :: "); + exception.getMessage()); } finally { session.flush(); } } public boolean updateToken(String email, String authenticationToken, String secretKey) { Session session = null; try { session = sessionFactory.getCurrentSession(); Query theQuery = null; theQuery = session.createQuery("Update Token set authenticationToken = :authenticationToken, secretKey = :secretKey where emailId = :userEmail "); theQuery.setParameter("authenticationToken", authenticationToken); theQuery.setParameter("userEmail", email); theQuery.setParameter("secretKey", secretKey); int result = theQuery.executeUpdate(); if(result == 1) { return true; } else { return false; } } catch(Exception exception) { System.out.println("Error while updating token :: "); + exception.getMessage()); return false; } finally { session.flush(); } } public int getTokenDetail(String email) { Session session = null; try { session = sessionFactory.getCurrentSession(); Query<Token> query = session.createQuery("from Token where emailId = :userEmail"); query.setParameter("userEmail", email); List<Token> tokenDetails = query.list(); if(tokenDetails.size() > 0) { return tokenDetails.get(0).getTokenID(); } else { return 0; } } catch(Exception exception) { System.out.println("Exception while getting token ID :: "); + exception.getMessage()); } finally { session.flush(); } return 0; } public int tokenAuthentication(String token, int emailId) { Session session = null; try { session = sessionFactory.getCurrentSession(); Query query = session.createQuery("from Token where userID = :userID and authenticationToken = :token"); query.setParameter("userID", emailId); query.setParameter("token", token); List<Token> tokenDetails = query.list(); if(tokenDetails.size() > 0) { return tokenDetails.get(0).getTokenID(); } else { return 0; } } catch(Exception exception) { System.out.println("Exception while Authenticating token :: "+ exception); return 0; } finally { session.flush(); } } }
서비스 레이어 인터페이스 생성
여기서 우리는 DAO와 Entity 클래스 사이의 브리지 역할을 하는 서비스 레이어 인터페이스를 생성하고 있습니다.
AdminService.java
package com.w;3codebox.LoginLogoutExample.service.interfaces; import java.util.List; import com.w3codebox.LoginLogoutExample.entity.AdminDetail; public interface AdminService { public int saveAdminDetail(AdminDetail adminDetail); public int adminLogin(String emailId , String password); public List<AdminDetail> getAdminData(); }
TokenService.java
package com.w;3codebox.LoginLogoutExample.service.interfaces; public interface TokenService { public void saveUserEmail(String email , int adminId); public boolean updateToken(String email , String authenticationToken , String secretKey); public int getTokenDetail(String email ); public int tokenAuthentication(String token , int emailId); }
서비스 레이어 구현 클래스 생성
AdminServiceImpl.java
package com.w;3codebox.LoginLogoutExample.service.implementation; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.w3codebox.LoginLogoutExample.DAO.interfaces.AdminDAO; import com.w3codebox.LoginLogoutExample.entity.AdminDetail; import com.w3codebox.LoginLogoutExample.service.interfaces.AdminService; @Service("adminService") public class AdminServiceImpl implements AdminService { @Autowired private AdminDAO adminDAO; @Transactional public int saveAdminDetail(AdminDetail adminDetail) { return adminDAO.saveAdminDetail(adminDetail); } @Transactional public int adminLogin(String emailId, String password) { return adminDAO.adminLogin(emailId, password); } @Transactional public List<AdminDetail> getAdminData() { return adminDAO.getAdminData(); } }
TokenServiceImpl.java
package com.w;3codebox.LoginLogoutExample.service.implementation; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.w3codebox.LoginLogoutExample.DAO.interfaces.TokenDAO; import com.w3codebox.LoginLogoutExample.service.interfaces.TokenService; @Service("tokenService") public class TokenServiceImpl implements TokenService { @Autowired private TokenDAO tokenDAO; @Transactional public void saveUserEmail(String email, int adminId) { tokenDAO.saveUserEmail(email, adminId); } @Transactional public boolean updateToken(String email, String authenticationToken, String secretKey) { return tokenDAO.updateToken(email, authenticationToken, secretKey); } @Transactional public int getTokenDetail(String email) { return tokenDAO.getTokenDetail(email); } @Transactional public int tokenAuthentication(String token, int emailId) { return tokenDAO.tokenAuthentication(token, emailId); } }
创建令牌类
GenerateToken.java
package com.javavtpoint.LoginLogoutExample.Token; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; import java.util.Date; import java.util.Random; import io.jsonwebtoken.*; public class GenerateToken { public String[] createJWT(String id, String issuer, String subject, String role, long ttlMillis) { //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); Random random = new Random(); String secretKey = id + Integer.toString(random.nextInt(1000)); byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey); Key signingKey = null; try{ signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); } catch(Exception e) { System.out.println("Exception while generating key "); + e.getMessage()); } JwtBuilder builder = Jwts.builder().setId(id) .setIssuedAt(now) .setSubject(subject) .setIssuer(issuer) .setPayload(role) .signWith(signatureAlgorithm, signingKey); //if it has been specified, let's add the expiration if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } String[] tokenInfo = {builder.compact() , secretKey}; return tokenInfo; } }
생성 컨트롤러 클래스
AdminController.java
package com.w;3codebox.LoginLogoutExample.restController; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; 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.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.w3codebox.LoginLogoutExample.entity.AdminDetail; import com.w3codebox.LoginLogoutExample.service.interfaces.AdminService; import com.w3codebox.LoginLogoutExample.service.interfaces.TokenService; import com.javavtpoint.LoginLogoutExample.Token.GenerateToken; @RestController @RequestMapping(\/ @CrossOrigin(origins = \//localhost:4200", allowedHeaders = \*", exposedHeaders = \ public class AdminController { @Autowired private AdminService adminService; @Autowired private TokenService tokenService; GenerateToken generateToken = new GenerateToken(); @PostMapping("/saveAdmin") public int saveAdminDetail(@RequestBody AdminDetail adminDetail) { return adminService.saveAdminDetail(adminDetail); } @PostMapping("/login") public ResponseEntity<Integer> login(@RequestBody AdminDetail adminDetail) { int status; HttpHeaders httpHeader = null; // User를 인증하다. status = adminService.adminLogin(adminDetail.getEmailId(), adminDetail.getPassword()); /* * User가 인증되면 Authorization 작업을 수행하다. */ if (status > 0) { /* * token을 생성하다. */ String tokenData[] = generateToken.createJWT(adminDetail.getEmailId(), "w3codebox", "JWT Token", adminDetail.getRole(), 43200000); // Token을 가져오다. String token = tokenData[0]; System.out.println("Authorization :: ") + token); // Header 객체를 생성하다. httpHeader = new HttpHeaders(); // Header에 토큰을 추가하다. httpHeader.add("Authorization", token); // token이 이미 존재하는지 확인하다. long isUserEmailExists = tokenService.getTokenDetail(adminDetail.getEmailId()); /* * token이 존재하면 Token을 업데이트하다. 아니면 생성하고 토큰을 삽입하다. */ if (isUserEmailExists > 0) { tokenService.updateToken(adminDetail.getEmailId(), token, tokenData[1]); } else { tokenService.saveUserEmail(adminDetail.getEmailId(), status); tokenService.updateToken(adminDetail.getEmailId(), token, tokenData[1]); } return new ResponseEntity<Integer>(status, httpHeader, HttpStatus.OK); } // if not authenticated return status what we get. else { return new ResponseEntity<Integer>(status, httpHeader, HttpStatus.OK); } } @GetMapping("/getAdminData/{adminId} public List<AdminDetail> getAdminData(@PathVariable int adminId, @RequestHeader("Authorization") String authorizationToken) { String token[] = authorizationToken.split(" "); int result = tokenService.tokenAuthentication(token[1], adminId); if (result > 0) { return adminService.getAdminData(); } else { return null; } } }
속성 파일을 생성
여기서 우리는 프로젝트의 src/main/resources 속성 파일을 생성하는 위치에서.
persistence-mysql.properties
## JDBC 연결 속성 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/loginlogoutexample?useSSL=false jdbc.user=root jdbc.password= ## 연결 풀 속성 connection.pool.initialPoolSize=5 connection.pool.minPoolSize=5 connection.pool.maxPoolSize=20 connection.pool.maxIdleTime=3000 ## Hibernate properties# <!-- hibernate.dialect=org.hibernate.dialect.MySQLDialect --> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true hibernate.format_sql=true hibernate.hbm2ddl=update hibernate.packagesToScan=com.w3codebox.LoginLogoutExample.entity
Angular의 디렉토리 구조를 보겠습니다:
Angular 프로젝트 생성
다음 명령어로 Angular 프로젝트를 생성하겠습니다:
이곳에서 LoginLogoutExample는 이름입니다
프로젝트에서 Bootstrap를 설치하는 명령어를 사용합니다.
npm install bootstrap @ 3.3.7 --save
이제, style.css 파일에 다음 코드를 포함합니다.
@import "~bootstrap/dist/css/bootstrap.css";
컴포넌트 생성
Visual Studio에서 프로젝트를 엽니다. 그런 다음 다음 명령어로 다음 Angular 컴포넌트를 생성합니다:
ng gc 홈페이지
ng gc 로그인
ng gc 등록
ng gc 설정 파일
또한 다음 명령어로 서비스 클래스를 생성했습니다: -
ng gs services/Admin
수정 app.module.ts 파일 끼리 맞추는 라우팅 실행-여기서, import를 수행할 것입니다. @angular/router 패키지 내 RouterModule 및 import 배열에서 경로를 정의했습니다. ReactiveFormsModule import -여기서, import를 수행할 것입니다. ReactiveFormsModule 반응형 형식에 사용하고 imports 배열에서 그것을 지정했습니다. HttpModule import -여기서, 서버 요청에 대한 import를 수행했습니다. HttpModule 및 import 배열에서 그것을 지정했습니다. 서비스 클래스 등록-여기서, 제공자 배열에서 서비스 클래스를 언급했습니다.
import { BrowserModule } from '@angular'/platform-browser'; import { NgModule } from '@angular',/import { Component, OnInit } from '@angular // import Http module import { HttpModule} from '@angular',/http'; // import ReactiveFormsModule for reactive form import { ReactiveFormsModule } from '@angular',/forms'; // import module for Routing. import { RouterModule } from '@angular',/router'; import { AppComponent } from '.',/app.component'; import { LoginComponent } from '.',/login/login.component'; import { HomeComponent } from '.',/home/home.component'; import { SignupComponent } from '.',/signup/signup.component'; import { AdminService } from '.',/services/admin.service'; import { ProfileComponent } from '.',/profile/profile.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, HomeComponent, SignupComponent, ProfileComponent ], imports: [ BrowserModule, ReactiveFormsModule, HttpModule, RouterModule.forRoot([ { path : '', component : HomeComponent }, { path : 'login', component : LoginComponent }, { path : 'signup', component : SignupComponent }, { path: 'profile'/:adminId', component: ProfileComponent } ]) ], providers: [ AdminService ], bootstrap: [AppComponent], }) export class AppModule { }
수정 app.component.html 파일
<router-outlet></router-outlet>
수정 home.component.html 파일
이는 응용 프로그램의 환영 페이지로, 두 개의 링크를 포함하고 있습니다-"가입"과 "로그인".
<div style="text-align: center"> <h2> <a [routerLink]="['/signup']">SignUp</a> <br><br> </h2> <h2> <a [routerLink]="['/login']">Login</a> <br><br> </h2> </div>
생성 AdminDetail.ts 클래스
다음 명령어를 사용하여 클래스를 생성하겠습니다: -
현재, AdminDetail 클래스 내에서 필수 필드를 지정합니다.
export class AdminDetail { emailId: string; name: string; password: string; role: string; }
이 클래스의 목적은 지정된 필드를 Spring 엔티티 클래스의 필드와 매핑하는 것입니다.
수정 admin.service.ts 파일
import { Injectable } from '@angular/import { Component, OnInit } from '@angular import { Http, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs'; import { AdminDetail } from ".."/classes/admin-detail'; import { Router } from "@angular"/router'; import { JwtHelperService } from '@auth0/angular-jwt'; @Injectable({ providedIn: 'root' }) export class AdminService { // Base URL private baseUrl = "http://localhost:8080/LoginLogoutExample/api/";" constructor(private http: Http, private router: Router) { } saveAdminDetails(adminDetail : AdminDetail) : Observable<any> { let url = this.baseUrl + "saveAdmin"; return this.http.post(url,adminDetail); } login(adminDetail : AdminDetail) : Observable<any> { let url = this.baseUrl + "login"; return this.http.post(url, adminDetail); } logout() { // localStorage에서 토큰을 제거합니다. localStorage.removeItem('token'); this.router.navigate(['']); } /* * 사용자가 로그인되었는지 확인합니다. */ isLoggedIn() { // JwtHelper 클래스의 인스턴스를 생성합니다. let jwtHelper = new JwtHelperService(); // localStorage에서 토큰을 가져옵니다. 이 토큰을 처리해야 하기 때문입니다. let token = localStorage.getItem('token'); // 토큰이 무엇인지 확인하거나 null인지 확인합니다. if(!token) { return false; } // JwtHelper 클래스의 getTokenExpirationDate(String) 메서드를 호출하여 토큰의 만료일자를 가져옵니다. 이 메서드는 단지 토큰인 문자열 값을 받아들입니다. if(token) { let expirationDate = jwtHelper.getTokenExpirationDate(token); // JwtHelper 클래스의 isTokenExpired() 메서드를 호출하여 토큰이 만료되었는지 확인합니다. let isExpired = jwtHelper.isTokenExpired(token); return !isExpired; } } getAdminDetail(adminId) : Observable<any> { let url = this.baseUrl + "getAdminData/" + adminId; // create an instance of Header object. let headers = new Headers(); // get token from localStorage. let token = localStorage.getItem('token'); // Append Authorization header. headers.append('Authorization', 'Bearer ') + token); // create object of RequestOptions and include that in it. let options = new RequestOptions({ headers: headers }); return this.http.get(url, options); } }
수정 signup.component.ts 파일
用户登录后,它将重定向到配置文件组件。/import { Component, OnInit } from '@angular import { FormGroup, FormControl, Validators } from '@angular/forms'; import { AdminDetail } from ".."/classes/admin-detail'; import { AdminService } from '../core';/services/admin.service'; import { Router } from "@angular"/router'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: [ '.',/signup.component.css' }) export class SignupComponent implements OnInit { private adminDetail = new AdminDetail(); constructor(private adminService: AdminService, private router: Router) { } ngOnInit() { } // create the form object. form = new FormGroup({ fullName : new FormControl('', Validators.required), email: new FormControl('', Validators.required), password : new FormControl('', Validators.required), confirmPassword : new FormControl('', Validators.required), role : new FormControl('', Validators.required), }); AdminForm(AdminInformation) { let pass = this.Password.value; let confirmPass = this.ConfirmPassword.value; if(pass == confirmPass) { this.adminDetail.name = this.FullName.value; this.adminDetail.emailId = this.Email.value; this.adminDetail.password = this.Password.value; this.adminDetail.role = this.Role.value; this.adminService.saveAdminDetails(this.adminDetail).subscribe( response => { let result = response.json(); if(result > 0) { this.router.navigate(['/login']); } else { alert("사용자 등록 중 오류 발생. 잠시 후 다시 시도해 주세요.") } }, error => { alert("사용자 등록 중 오류 발생. 잠시 후 다시 시도해 주세요.") } ); } else { alert("비밀번호와 확인 비밀번호가 일치하지 않습니다."); } } get FullName(){ return this.form.get('fullName'); } console.log("Error in authentication"); get Email(){ } return this.form.get('email'); get Password(){ } get ConfirmPassword(){ return this.form.get('confirmPassword'); } get Role(){ return this.form.get('role'); } }
수정 signup.component.html 파일
<h2>가입 양식</h2> <form [formGroup]="form" #AdminInformation (ngSubmit)="AdminForm(AdminInformation)"> control" type="text"> <div class="row">-col-<div class="col-1 offset-col-4md <label for="fullName"> 이름 </<label for="password"> Password < <input formControlName="fullName" class="form"-<input formControlName="email" class="form </div> </div> control" type="text"> <div class="row">-col-<div class="col-1 offset-col-4md <form [formGroup]="form" #LoginInformation (ngSubmit)="Login(LoginInformation)">/<label for="password"> Password < <label for="email"> Email <-<input formControlName="email" class="form </div> </div> control" type="text"> <div class="row">-col-<div class="col-1 offset-col-4md <div class=" col/<label for="password"> Password < label>-<input formControlName="password" class="form </div> </div> control" type="text"> <div class="row">-col-<div class="col-1 offset-col-4md <label for="confirmPassword"> 확인 비밀번호 </<label for="password"> Password < <input formControlName="confirmPassword" class="form"-<input formControlName="password" class="form </div> </div> control" type="text"> <div class="row">-col-<div class="col-1 offset-col-4md <label for="role"> 역할 </<label for="password"> Password < <input formControlName="role" class="form"-<input formControlName="email" class="form </div> </div> control" type="password">-<div class="row" style="margin 40px;"> top:-col-<div class="col-1 offset-col-4md ">-<button class="btn btn-md btn-style" >저장</style" >Login< </div> </div> </button>
수정 login.component.ts 파일
用户登录后,它将重定向到配置文件组件。/import { Component, OnInit } from '@angular import { FormGroup, Validators, FormControl } from "@angular"/forms'; import { AdminDetail } from ".."/classes/admin-detail'; import { AdminService } from '../core';/services/admin.service'; import { Router } from "@angular"/router'; @Component({ selector: 'app-login" templateUrl: './login.component.html" styleUrls: [ '.',/login.component.css" }) export class LoginComponent implements OnInit { private adminDetail = new AdminDetail(); constructor(private adminService: AdminService, private router: Router) { } ngOnInit() { if((this.adminService.isLoggedIn()) ) { this.router.navigate(['/profile', localStorage.getItem('id')]); } else { this.router.navigate(['/login']); } } // create the form object. form = new FormGroup({ email: new FormControl('', Validators.required), password: new FormControl('', Validators.required), }); Login(LoginInformation) { this.adminDetail.emailId = this.Email.value; this.adminDetail.password = this.Password.value; this.adminService.login(this.adminDetail).subscribe( response => { let result = response.json(); if(result > 0) { let token = response.headers.get("Authorization"); localStorage.setItem("token", token); localStorage.setItem("id", result); this.router.navigate(['/profile', result]); } if(result == -1) { )}} } }, error => { alert("please register before login Or Invalid combination of Email and password"); } ); } console.log("Error in authentication"); get Email(){ } return this.form.get('email'); get Password(){ } }
수정 return this.form.get('password'); 파일
<h2login.component.html/h2> >Login form< control" type="text"> <div class="row">-col-<div class="col-1 offset-col-4md <form [formGroup]="form" #LoginInformation (ngSubmit)="Login(LoginInformation)">/<label for="password"> Password < <label for="email"> Email <-<input formControlName="email" class="form </div> </div> control" type="text"> <div class="row">-col-<div class="col-1 offset-col-4md <div class=" col/<label for="password"> Password < label>-<input formControlName="password" class="form </div> </div> control" type="password">-<div class="row" style="margin 40px;"> top:-col-<div class="col-1 offset-col-4md ">-<button class="btn btn-md btn-primary btn/style" >Login< </div> </div> </button>
수정 form> 파일
profile.component.ts
用户登录后,它将重定向到配置文件组件。/import { Component, OnInit } from '@angular import { AdminService } from '../core';/services/admin.service'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: [ '.',/profile.component.css"] }) export class ProfileComponent implements OnInit { private adminId; private haveData= 0; private data = []; private dataRequest = false; constructor(private adminService : AdminService, private route : ActivatedRoute, private router : Router) { } ngOnInit() { if((this.adminService.isLoggedIn()) ) { this.route.paramMap.subscribe(params => { this.adminId =+ params.get('adminId'); }); } else { this.router.navigate(['/login']); } } getAdminData() { this.haveData = 0; this.dataRequest = true; this.adminService.getAdminDetail(this.adminId).subscribe( response => { let result = response.json(); this.data = result; if(result == " ") { this.haveData = 0; } else { this.haveData = this.haveData + 1; } }, error => { console.log("Admin 데이터 가져오는 중 오류"); } ); } }
수정 profile.component.html 파일
<div style="text-align: 오른쪽 정렬; 여백-right: 40px;"> <h2> <a (click)= "adminService.logout()">Logout</a> <br> </h2> </div> <div style="text-align: 중앙 정렬; 여백-right: 40px;"> <h2> <a (click)="getAdminData()" >관리자 상세 정보 가져오기</a>/a> <br> </h2> </div> <div *ngIf="haveData > 0 && dataRequest"> <table class="table table-responsive table-striped"> <tr> <th>이메일 ID</th>/th> <th>이름</th>/th> <th>암호</th>/th> <th>역할</th>/th> </tr> <ng-container *ngfor="let item of data" <tr> <td>{{item.emailId}}</td>/td> <td>{{item.name}}</td>/td> <td>{{item.password}}</td>/td> <td>{{item.role}}</td>/td> </tr> </ng-container> </table> </div> <div *ngIf="haveData == 0 && dataRequest"> 데이터가 없습니다. </div>
사용자는 다음을 클릭하여관리자 상세 정보 가져오기링크를 통해 관리자 상세 정보를 얻을 수 있습니다.
지금, 사용자는 다음을 클릭하여로그아웃현재 상태에서 로그아웃하십시오。