赞
踩
因为最近一直在学习前后端分离的知识 也是第一次接触前后端分离 而且angular的学习资料也难找…所以想总结一篇刚搞出来的angular+spring boot的前后端分离的整合。
首先是angular配置:
login-demo.component.html:
<div class="container"> <div class="row clearfix" style="margin: 120px 0 0 0 ;"> <div class="col-md-1 column"> </div> <div class="col-md-5 column"> <div class="jumbotron"> <h1> Hello, world! </h1> <p> This is a template for a simple marketing or informational website. It includes a large callout called the hero unit and three supporting pieces of content. Use it as a starting point to create something more unique. </p> <p> <a class="btn btn-primary btn-large" href="#">Learn more</a> </p> </div> </div> <div class="col-md-5 column"> <h3> 登录 </h3> <h6> 没有账号?点击此处 <a routerLink="/register-demo" routerLinkActive="activebutton">注册</a> </h6> <form [formGroup]="formGroup" (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="username">Username</label><input type="username" class="form-control" id="username" formControlName="username" /> </div> <div class="form-group"> <label for="password">Password</label><input type="password" class="form-control" id="password" formControlName="password" /> </div> <div class="checkbox"> <label><input type="checkbox" />记住账号</label> <label><input type="checkbox" />自动登录</label> </div> <button type="submit" class="btn btn-success">Submit</button> <div class="form-group "> <div class="col-sm-offset-2 col-sm-10 "> <!-- <button class="btn btn-default " routerLink="/register-demo">Sign up</button> --> </div> </div> </form> </div> </div> </div> <!-- <router-outlet></router-outlet> -->
login-demo.component.ts:
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { HttpClient } from "@angular/common/http" ; import { HttpHeaders } from "@angular/common/http" import { registerLocaleData } from '@angular/common'; @Component({ selector: 'app-login-demo', templateUrl: './login-demo.component.html', styleUrls: ['./login-demo.component.css'] }) export class LoginDemoComponent implements OnInit { formGroup: FormGroup; public anyList:any; constructor(private http:HttpClient){} onSubmit() { // TODO: Use EventEmitter with form value const username = this.formGroup.get('username').value; const password = this.formGroup.get('password').value; console.log("password:"+password); console.warn(this.formGroup.get('username').value); this.register(); } ngOnInit(): void { this.formGroup = new FormGroup({ username: new FormControl(''), password: new FormControl('') }); console.info(this.formGroup.value); } register (){ const headers = new HttpHeaders().set("Content-type", "application/json; charset=UTF-8"); //console.info(headers); this.http.post("http://localhost:8081/login" ,this.formGroup.value) .subscribe(res=>{ console.log(1) console.log(res) // localStorage.setItem('token',res.headers.get('Authorization')); }) } }
app.component.html
<!-- 入口标签 -->
<!-- <app-profile-editor></app-profile-editor> -->
<router-outlet></router-outlet>
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; // import { RouterModule } from '@angular/router'; import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginDemoComponent } from './login-demo/login-demo.component'; import { RegisterDemoComponent } from './register-demo/register-demo.component'; // 一定要在BrowserModule模块后面import import { HttpClientModule } from '@angular/common/http'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; const appRoutes: Routes = [ { path: 'login-demo', component: LoginDemoComponent }, { path: 'register-demo', component: RegisterDemoComponent }, { path: '', redirectTo: '/login-demo', pathMatch: 'full' }, ]; @NgModule({ declarations: [ AppComponent, LoginDemoComponent, RegisterDemoComponent, ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, // import HttpClientModule after BrowserModule. HttpClientModule, RouterModule.forRoot([ {path: 'login-demo', component: LoginDemoComponent}, {path: 'register-demo', component: RegisterDemoComponent}, { path: '', redirectTo: '/login-demo', pathMatch: 'full' }, ]), ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
前端页面+组件配置完成后效果:
虽然比较丑 但是问题不大 实现功能后再美化。
后端spring boot配置:
目录配置
跨域配置:
package com.example.demo.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @version 1.0 * @ClassName MvcConfig * @Author little * @Description TODO * @date 2020/11/1 14:55 */ @Configuration public class MvcConfig implements WebMvcConfigurer { //解决跨域问题 @Override public void addCorsMappings(CorsRegistry registry) { //所有请求都允许跨域 使用这种方法就不能在interceptor中再配置header了 registry.addMapping("/**") .allowCredentials(true) .allowedOrigins("http://localhost:4200") .allowedMethods("POST","GET","PUT","OPTIONS","DELETE") .allowedHeaders("*") .maxAge(3600); } }
控制器:
package com.example.demo.controller; import com.example.demo.entity.User; import com.example.demo.mapper.LoginMapper; import com.example.demo.service.LoginService; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.function.Supplier; import java.util.logging.Logger; /** * @version 1.0 * @ClassName LoginController * @Author little * @Description TODO * @date 2020/10/30 15:23 */ @RestController public class LoginController { @Autowired private LoginMapper loginMapper; @Autowired private LoginService loginService; // HelloWorld.class 就是你要打印的指定类的日志, // 如果你想在其它类中打印,那就把 HelloWorld.class 替换成目标类名.class 即可。 // Logger logger = (Logger) LoggerFactory.getLogger(LoginController.class); //logger.info("Hello World"); /** * 登录 * * @return */ @ResponseBody @RequestMapping(value = "/login" , consumes = "application/json") public Object Login3(@RequestBody User user) { //logger.info((Supplier<String>) user); System.out.println(user); return loginService.login(user); } }
返回结果类:
package com.example.demo.entity; import lombok.Data; import java.util.List; /** * @version 1.0 * @ClassName MyResult * @Author little * @Description 通用返回值实例 * @date 2020/11/1 13:13 */ @Data public class MyResult { private int code;//-1:参数不足,-2:权限不足,0:正常应答 private String msg;//提示信息 //private List<?> list; private Object object; private int count; }
实体类
package com.example.demo.entity; import lombok.Data; /** * @version 1.0 * @ClassName user * @Author little * @Description TODO * @date 2020/10/30 15:22 */ @Data public class User { private String id; private String username; private String password; }
mapper接口
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface LoginMapper {
@Select("select * from user where username = #{username} and password = #{password}")
List<User> login(User user);
}
service实现类
package com.example.demo.service.impl; import com.example.demo.entity.MyResult; import com.example.demo.entity.User; import com.example.demo.mapper.LoginMapper; import com.example.demo.service.LoginService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * @version 1.0 * @ClassName LoginServiceImpl * @Author little * @Description TODO * @date 2020/11/1 13:16 */ @Service public class LoginServiceImpl implements LoginService { @Autowired private LoginMapper loginMapper; @Override public MyResult login(User user) { User user1 = new User(); List<User> userList = new ArrayList<>(); userList = loginMapper.login(user); MyResult myResult = new MyResult(); if(userList.size()!=0) { myResult.setCode(0); myResult.setMsg("登录成功!"); //myResult.setList(userList); System.out.println("成功!"); myResult.setObject(userList.get(0)); }else { myResult.setCode(1); myResult.setMsg("登录失败!"); } return myResult; } }
service
package com.example.demo.service;
import com.example.demo.entity.MyResult;
import com.example.demo.entity.User;
import org.springframework.stereotype.Service;
@Service
public interface LoginService {
MyResult login(User user);
}
启动类要记得添加
@MapperScan(basePackages="com.example.demo.mapper")
这个注解
数据库配置文件就不贴了
效果图:
可以看到是返回了一个msg是登录成功的 简单Demo完成 后续可以添加其他页面再更新~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。