在本节中,我们将创建一个登录和注销web应用程序。该应用程序包括注册和登录表单。在这种集成中,我们使用spring处理后端部分,使用angular处理前端部分。
一旦我们在服务器上部署了应用程序,就会生成一个欢迎页面,其中包含两个链接-注册和登录。新用户可以选择注册并通过填写所需的详细信息进行注册。但是,现有用户可以使用其电子邮件id和密码登录。登录后,我们可以获取现有用户的详细信息。最后,我们可以通过单击注销链接退出当前状态。
使用任何ide来开发spring和hibernate项目。可能是myeclipse/eclipse/netbeans。在这里,我们正在使用eclipse。用于数据库的mysql。使用任何ide来开发angular项目。它可能是visual studio代码/sublime。在这里,我们正在使用visual studio code。服务器: apache tomcat/jboss/glassfish/weblogic/websphere。
在这里,我们正在使用以下技术:
spring5 hibernate5 angular6 mysql
让我们创建数据库 loginlogoutexample 。无需创建表,因为hibernate会自动创建它。
让我们看看我们需要遵循的spring目录结构:
要开发一个登录和注销应用程序,请遵循以下步骤: -
将依赖项添加到pom.xml文件。
4.0.0 com.nhooo loginlogoutexample war 0.0.1-snapshot loginlogoutexample maven webapp http://maven.apache.org 5.0.6.release 5.2.16.final 5.1.45 0.9.5.2 1.8 1.8 org.springframework spring-webmvc ${springframework.version} org.springframework spring-tx ${springframework.version} org.springframework spring-orm ${springframework.version} com.fasterxml.jackson.core jackson-databind 2.9.5 org.hibernate hibernate-core ${hibernate.version} mysql mysql-connector-java ${mysql.connector.version} com.mchange c3p0 ${c3po.version} javax.servlet javax.servlet-api 3.1.0 javax.servlet.jsp javax.servlet.jsp-api 2.3.1 javax.servlet jstl 1.2 javax.xml.bind jaxb-api 2.3.0 io.jsonwebtoken jjwt 0.9.1 junit junit 3.8.1 test org.apache.commons commons-dbcp2 2.0 loginlogoutexample
创建配置类
我们执行基于注释的配置,而不是xml。因此,我们创建两个类并在其中指定所需的配置。
demoappconfig.java
package com.nhooo.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.nhooo.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.setjdbc); 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.nhooo.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[] { "/" }; } }
创建实体类
在这里,我们将创建以下实体类: admindetail.java-这是一个entity/pojo(普通的旧java对象)类。 token.java-用于身份验证。
admindetail.java
package com.nhooo.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; this.role = role; } 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) { this.role = role; } @override public string tostring() { return "admindetail [adminid=" adminid ", emailid=" emailid ", name=" name ", password=" password ", role=" role "]"; } }
token.java
package com.nhooo.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.nhooo.loginlogoutexample.dao.interfaces; import java.util.list; import com.nhooo.loginlogoutexample.entity.admindetail; public interface admindao { public int saveadmindetail(admindetail admindetail); public int adminlogin(string emailid , string password); public listgetadmindata(); }
tokendao.java
package com.nhooo.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.nhooo.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.nhooo.loginlogoutexample.dao.interfaces.admindao; import com.nhooo.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); listlist = 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 getadmindata() { session session = null; try { session = sessionfactory.getcurrentsession(); query query = session.createquery("from admindetail"); list 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.nhooo.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.nhooo.loginlogoutexample.dao.interfaces.tokendao; import com.nhooo.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(); queryquery = session.createquery("from token where emailid =:useremail"); query.setparameter("useremail", email); list 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 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.nhooo.loginlogoutexample.service.interfaces; import java.util.list; import com.nhooo.loginlogoutexample.entity.admindetail; public interface adminservice { public int saveadmindetail(admindetail admindetail); public int adminlogin(string emailid , string password); public listgetadmindata(); }
tokenservice.java
package com.nhooo.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.nhooo.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.nhooo.loginlogoutexample.dao.interfaces.admindao; import com.nhooo.loginlogoutexample.entity.admindetail; import com.nhooo.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 listgetadmindata() { return admindao.getadmindata(); } }
tokenserviceimpl.java
package com.nhooo.loginlogoutexample.service.implementation; import javax.transaction.transactional; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import com.nhooo.loginlogoutexample.dao.interfaces.tokendao; import com.nhooo.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.nhooo.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.nhooo.loginlogoutexample.entity.admindetail; import com.nhooo.loginlogoutexample.service.interfaces.adminservice; import com.nhooo.loginlogoutexample.service.interfaces.tokenservice; import 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 responseentitylogin(@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(), "nhooo", "jwt token", admindetail.getrole(), 43200000); // get token. string token = tokendata[0]; system.out.println("authorization :: " token); // create the header object httpheader = new httpheaders(); // add token to the header. httpheader.add("authorization", token); // check if token is already exist. long isuseremailexists = tokenservice.gettokendetail(admindetail.getemailid()); /* * if token exist then update token else create and insert the 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 (status, httpheader, httpstatus.ok); } // if not authenticated return status what we get. else { return new responseentity (status, httpheader, httpstatus.ok); } } @getmapping("/getadmindata/{adminid}") public list 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 connection properties# jdbc.driver=com.mysql.jdbc.driver jdbc.url=jdbc:mysql://localhost:3306/loginlogoutexample?usessl=false jdbc.user=root jdbc.password= ## connection pool properties# connection.pool.initialpoolsize=5 connection.pool.minpoolsize=5 connection.pool.maxpoolsize=20 connection.pool.maxidletime=3000 ## hibernate properties# hibernate.dialect=org.hibernate.dialect.mysql5dialect hibernate.show_sql=true hibernate.format_sql=true hibernate.hbm2ddl=update hibernate.packagestoscan=com.nhooo.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 文件 实施路由-在这里,我们要导入 @ angular/router 包中的 routermodule ,并在导入数组中定义路径。 导入reactiveformsmodule -在这里,我们将导入 reactiveformsmodule 用于反应形式,并在imports数组中指定它。 导入httpmodule -在这里,我们为服务器请求导入 httpmodule ,并在import数组中指定它。 注册服务类-在这里,我们在提供者数组中提到了服务类。
import { browsermodule } from '@angular/platform-browser'; import { ngmodule } from '@angular/core'; // 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 文件
编辑 home.component.html 文件
这是应用程序的欢迎页面,其中包括两个链接-"注册"和"登录"。
创建 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{ let url = this.baseurl "saveadmin"; return this.http.post(url,admindetail); } login(admindetail : admindetail) : observable { 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(); // get the token from the localstorage as we have to work on this token. let token = localstorage.getitem('token'); // check whether if token have something or it is null. if(!token) { return false; } // 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. if(token) { let expirationdate = jwthelper.gettokenexpirationdate(token); // check whether the token is expired or not by calling istokenexpired() method of jwthelper class. let isexpired = jwthelper.istokenexpired(token); return !isexpired; } } getadmindetail(adminid) : observable { 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/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() { } // 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 occur while registring user. please try after sometime.") } }, error => { alert("error occur while registring user. please try after sometime.") } ); } else { alert("password and confirm password not match."); } } 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 文件
signup form