English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
في هذا الفصل، سننشئ تطبيق الويب الخاص بالتسجيل والخروج. يشمل هذا التطبيق نماذج التسجيل وال登입. في هذه الدمج، نستخدم Spring للمعالجة الجزء الخلفي، ونستخدم Angular للمعالجة الجزء الأمامي.
بعد تثبيت التطبيق على الخادم، سيتم إنشاء صفحة ترحيب تحتوي على رابطين - التسجيل وال登입.يمكن للمستخدمين الجدد اختيار التسجيل من خلال ملء التفاصيل المطلوبة للتسجيل.لكن المستخدمين الحاليين يمكنهم تسجيل الدخول باستخدام معرف البريد الإلكتروني وكلمة المرور.بعد تسجيل الدخول، يمكننا الحصول على تفاصيل المستخدمين الحاليين.في النهاية، يمكننا الخروج من الحالة الحالية بالنقر على رابط الخروج.
استخدام أي IDE لتطوير مشاريع Spring وHibernate. قد يكون MyEclipse/Eclipse/Netbeans. في هذا السياق، نستخدم Eclipse.MySQL لقاعدة البيانات.استخدام أي IDE لتطوير مشاريع Angular. قد يكون Visual Studio Code/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> <!-- إضافة Jackson للتحويلات JSON --> <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> <!-- to compensate for java 9 not including jaxb --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <!-- Web token dependency --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- JUnit dependency --> <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.w3codebox.LoginLogoutExample.config; import java.beans.PropertyVetoException; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; إدراج 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() { // create connection pool ComboPooledDataSource myDataSource = new ComboPooledDataSource(); // set the jdbc driver try { myDataSource.setDriverClass("com.mysql.jdbc.Driver"); } catch (PropertyVetoException exc) { throw new RuntimeException(exc); } // set database connection props myDataSource.setJdbcUrl(env.getProperty("jdbc.url")); myDataSource.setUser(env.getProperty("jdbc.user")); myDataSource.setPassword(env.getProperty("jdbc.password")); // set connection pool props 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() { // set hibernate properties 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) { // setup transaction manager based on session factory HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory); return txManager; } }
MySpringMvcDispatcherServletInitializer.java
package com.w3codebox.LoginLogoutExample.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { // TODO Auto-generated method stub return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{ DemoAppConfig.class }; } @Override protected String[] getServletMappings() { return new String[]{ "/" }; } }
إنشاء فئة Entity
في هذا السياق، سنقوم بإنشاء الفئات التالية: AdminDetail.java-هذه هي فئة Entity/POJO (مثل جسم Java العادي). Token.java-للتحقق من الهوية.
AdminDetail.java
package com.w3codebox.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="admin_id") private int adminID; @Column(name="email_id", unique=true) public String emailId; @Column(name="name") public String name; @Column(name="password") public String password; @Column(name="role") public String role; public AdminDetail() { } public AdminDetail(int adminID, String emailId, String name, String password, String role) { super(); this.adminID = adminID; this.emailId = emailId; this.name = name; this.password = password; } public int getAdminID() { return adminID; } public void setAdminID(int adminID) { this.adminID = adminID; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { } @Override public String toString() { return \ + ", role=\" + role + \"]"; } }
Token.java
package com.w3codebox.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 \ + ", secretKey=" + secretKey + ", emailId=" + emailId + "]"; } }
创建DAO接口
في هذا المكان، سنقوم بإنشاء اثنين من واجهات DAO لتنفيذ العمليات المتعلقة بالقاعدة البيانات.
AdminDAO.java
package com.w3codebox.LoginLogoutExample.DAO.interfaces; إدراج java.util.List; استيراد 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.w3codebox.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.w3codebox.LoginLogoutExample.DAO.implementation; إدراج java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; إدراج org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.w3codebox.LoginLogoutExample.DAO.interfaces.AdminDAO; استيراد 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.w3codebox.LoginLogoutExample.DAO.implementation; إدراج java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; إدراج 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 { يعود false; } } catch(Exception exception) { System.out.println("Error while updating token :: " + exception.getMessage()); يعود 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.w3codebox.LoginLogoutExample.service.interfaces; إدراج java.util.List; استيراد 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.w3codebox.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.w3codebox.LoginLogoutExample.service.implementation; إدراج java.util.List; import javax.transaction.Transactional; إدراج org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.w3codebox.LoginLogoutExample.DAO.interfaces.AdminDAO; استيراد com.w3codebox.LoginLogoutExample.entity.AdminDetail; استيراد 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.w3codebox.LoginLogoutExample.service.implementation; import javax.transaction.Transactional; إدراج org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.w3codebox.LoginLogoutExample.DAO.interfaces.TokenDAO; استيراد 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); //إذا تم تحديدها، دعونا نضيف انتهاء الصلاحية إذا (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } String[] tokenInfo = {builder.compact() , secretKey}; الرجوع tokenInfo; } }
إنشاء كلاس التحكم
AdminController.java
باكاجيت com.w3codebox.LoginLogoutExample.restController; إدراج java.util.List; إدراج org.springframework.beans.factory.annotation.Autowired; استيراد org.springframework.http.HttpHeaders; استيراد org.springframework.http.HttpStatus; استيراد org.springframework.http.ResponseEntity; استيراد org.springframework.web.bind.annotation.CrossOrigin; استيراد org.springframework.web.bind.annotation.GetMapping; استيراد org.springframework.web.bind.annotation.PathVariable; استيراد org.springframework.web.bind.annotation.PostMapping; استيراد org.springframework.web.bind.annotation.RequestBody; استيراد org.springframework.web.bind.annotation.RequestHeader; استيراد org.springframework.web.bind.annotation.RequestMapping; استيراد org.springframework.web.bind.annotation.RestController; استيراد com.w3codebox.LoginLogoutExample.entity.AdminDetail; استيراد com.w3codebox.LoginLogoutExample.service.interfaces.AdminService; استيراد com.w3codebox.LoginLogoutExample.service.interfaces.TokenService; استيراد com.javavtpoint.LoginLogoutExample.Token.GenerateToken; @RestController @RequestMapping("/api") @CrossOrigin(origins = "http://localhost:4200", allowedHeaders = "*", exposedHeaders = "Authorization") 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; // Authenticate User. status = adminService.adminLogin(adminDetail.getEmailId(), adminDetail.getPassword()); /* * if User is authenticated then do Authorization Task. */ if (status > 0) { /* * Generate token. */ String tokenData[] = generateToken.createJWT(adminDetail.getEmailId(), "w3codebox", "JWT Token", adminDetail.getRole(), 43200000); // get Token. String token = tokenData[0]; System.out.println("Authorization :: " + token); // إنشاء الهدف الموضوعي httpHeader = new HttpHeaders(); // إضافة التoken إلى الرأس. httpHeader.add("Authorization", token); // التحقق من وجود التoken بالفعل. long isUserEmailExists = tokenService.getTokenDetail(adminDetail.getEmailId()); /* * إذا كان التoken موجودًا فإنه يتم تحديث التoken وإلا يتم إنشاءه وإدراجه. */ 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); } // إذا لم يتم التحقق من هوية المستخدم، عائد الحالة الذي نحصل عليه. 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 <!-- 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 \
إنشاء المكون
في Visual Studio افتح المشروع، ثم استخدم الأمر التالي لإنشاء المكونات Angular التالية:
ng gc الصفحة الرئيسية
ng gc الدخول
ng gc التسجيل
ng gc ملف التكوين
نستخدم أيضًا الأوامر التالية لإنشاء فئة الخدمة: -
ng gs services/Admin
تحرير app.module.ts ملف تنفيذ التحكم في الطرق- هنا، سنقوم باستيراد @angular/router في الحزمة RouterModule ، وقم بتحديد المسار في قائمة الاستيرادات. استيراد ReactiveFormsModule - هنا، سنقوم باستيراد ReactiveFormsModule للشكل التفاعلي، وقم بتحديد هذه في قائمة الاستيرادات. استيراد HttpModule - هنا، قمنا باستيراد HttpModule ، وقم بتحديد هذه في قائمة الاستيرادات. تسجيل فئة الخدمة- هنا، ذكرنا فئة الخدمة في قائمة المزودين.
استيراد { BrowserModule } من '@angular/platform-browser'; استيراد { NgModule } من '@angular/core'; // استيراد مكتبة Http module استيراد { HttpModule} من '@angular/http'; // استيراد مكتبة ReactiveFormsModule للشكل التفاعلي استيراد { ReactiveFormsModule } من '@angular/forms'; // استيراد مكتبة module للتحكم في الطرق. استيراد { RouterModule } من '@angular/router'; استيراد { AppComponent } من './app.component'; استيراد { LoginComponent } من './login/login.component'; استيراد { HomeComponent } من './home/home.component'; استيراد { SignupComponent } من './signup/signup.component'; استيراد { AdminService } من './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/core'; 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() { // Remove the token from the localStorage. localStorage.removeItem('token'); this.router.navigate(['']); } /* * Check whether User is loggedIn or not. */ isLoggedIn() { // create an instance of JwtHelper class. let jwtHelper = new JwtHelperService(); // الحصول على token من localStorage لأننا يجب أن نعمل على هذا token. تسمية token = localStorage.getItem('token'); // التحقق مما إذا كان token يحتوي على شيء أو أنه null. إذا (!token) { يعود false; } // الحصول على تاريخ انتهاء الصلاحية للtoken عبر استدعاء طريقة getTokenExpirationDate(String) من فئة JwtHelper. هذه الطريقة تقبل قيمة نصية هي شئ لا يختلف عن token. إذا (token) { تسمية expirationDate = jwtHelper.getTokenExpirationDate(token); // التحقق مما إذا كان token منتهي الصلاحية أو لا عبر استدعاء طريقة isTokenExpired() من فئة JwtHelper. تسمية isExpired = jwtHelper.isTokenExpired(token); يعود !isExpired; } } getAdminDetail(adminId) : Observable<any> { تسمية url = this.baseUrl + "getAdminData/" + adminId; // إنشاء نموذج من جسم Header. تسمية العناوين = new Headers(); // الحصول على token من localStorage. تسمية token = localStorage.getItem('token'); // إضافة علامة التبويب Authorization. يضيف العناوين ('Authorization', 'Bearer ' + token); // إنشاء جسم من RequestOptions وتضمين ذلك فيه. دع options = new RequestOptions({ headers: headers }); return this.http.get(url, options); } }
تحرير signup.component.ts ملف
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { AdminDetail } from '../classes/admin-detail'; import { AdminService } from '../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() { } // إنشاء objance form. 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) { دع pass = this.Password.value; دع confirmPass = this.ConfirmPassword.value; إذا (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 { تحذير("حدث خطأ أثناء تسجيل المستخدم. يرجى المحاولة لاحقا.") } }, error => { تحذير("حدث خطأ أثناء تسجيل المستخدم. يرجى المحاولة لاحقا.") } ); } else { تحذير("مقارنة كلمة المرور وبطاقة التأكيد غير متطابقة."); } } get FullName(){ return this.form.get('fullName'); } get Email(){ return this.form.get('email'); } get Password(){ return this.form.get('password'); } get ConfirmPassword(){ return this.form.get('confirmPassword'); } get Role(){ return this.form.get('role'); } }
تحرير signup.component.html ملف
<h2>SignUp form</h2> <form [formGroup]="form" #AdminInformation (ngSubmit)="AdminForm(AdminInformation)"> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="fullName"> Name </label> <input formControlName="fullName" class="form-control" type="text"> </div> </div> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="email"> Email </label> <input formControlName="email" class="form-control" type="text"> </div> </div> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="password"> Password </label> <input formControlName="password" class="form-control" type="password"> </div> </div> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="confirmPassword"> Confirm Password </label> <input formControlName="confirmPassword" class="form-control" type="password"> </div> </div> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="role"> Role </label> <input formControlName="role" class="form-control" type="text"> </div> </div> <div class="row" style="margin-top: 40px;"> <div class="col-md-offset-1 col-md-4"> <button class="btn btn-md btn-primary btn-style" >Save</button> </div> </div> </form>
تحرير login.component.ts ملف
import { Component, OnInit } from '@angular/core'; import { FormGroup, Validators, FormControl } from '@angular/forms'; import { AdminDetail } from '../classes/admin-detail'; import { AdminService } from '../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']); } } // إنشاء objance form. 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) { alert("يرجى التسجيل أولاً قبل الدخول أو التركيبة غير الصحيحة من البريد الإلكتروني وكلمة المرور"); } }, error => { console.log("خطأ في التحقق من صحة الحساب"); } ); } get Email(){ return this.form.get('email'); } get Password(){ return this.form.get('password'); } }
تحرير login.component.html ملف
<h2>Login form</h2> <form [formGroup]="form" #LoginInformation (ngSubmit)="Login(LoginInformation)"> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="email"> Email </label> <input formControlName="email" class="form-control" type="text"> </div> </div> <div class="row"> <div class=" col-md-offset-1 col-md-4"> <label for="password"> Password </label> <input formControlName="password" class="form-control" type="password"> </div> </div> <div class="row" style="margin-top: 40px;"> <div class="col-md-offset-1 col-md-4"> <button class="btn btn-md btn-primary btn-style" >Login</button> </div> </div> </form>
تحرير profile.component.ts ملف
بعد إكمال تسجيل الدخول، سيتم إعادة توجيه المستخدم إلى مكون ملف الإعدادات.
import { Component, OnInit } from '@angular/core'; import { AdminService } from '../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("خطأ أثناء الحصول على بيانات الإدارة"); } ); } }
تحرير profile.component.html ملف
<div style="text-align: right; margin-right: 40px;"> <h2> <a (click)= "adminService.logout()">Logout</a> <br> </h2> </div> <div style="text-align: center; margin-right: 40px;"> <h2> <a (click)="getAdminData()">الحصول على تفاصيل المسؤول</a> <br> </h2> </div> <div *ngIf="haveData > 0 && dataRequest"> <table class="table table-responsive table-striped"> <tr> <th معرف البريد الإلكتروني</th> <th الاسم</th> <th palavrd</th> <th>الدور</th> </tr> <ng-container *ngfor="let item of data"> <tr> <td>{{item.emailId}}</td> <td>{{item.name}}</td> <td>{{item.password}}</td> <td>{{item.role}}</td> </tr> </ng-container> </table> </div> <div *ngIf="haveData == 0 && dataRequest"> لا يوجد بيانات. </div>
يمكن للمستخدمين النقرالحصول على تفاصيل المسؤولالرابط للحصول على تفاصيل المسؤول.
الآن، يمكن للمستخدمين النقرالخروجخروج الحالة الحالية.