当前位置:   article > 正文

Angular+Spring boot实现简单前后端分离登录_springboot angular 前后端分离

springboot angular 前后端分离

因为最近一直在学习前后端分离的知识 也是第一次接触前后端分离 而且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> -->
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

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'));
      })
  }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

app.component.html

<!-- 入口标签 -->
<!-- <app-profile-editor></app-profile-editor> -->
<router-outlet></router-outlet>
  • 1
  • 2
  • 3

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 { }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

前端页面+组件配置完成后效果:

在这里插入图片描述
虽然比较丑 但是问题不大 实现功能后再美化。

后端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);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

控制器:

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);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

返回结果类:

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;

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

实体类

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;


}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

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);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

启动类要记得添加

@MapperScan(basePackages="com.example.demo.mapper")
  • 1

这个注解

数据库配置文件就不贴了

效果图:
在这里插入图片描述
可以看到是返回了一个msg是登录成功的 简单Demo完成 后续可以添加其他页面再更新~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/588479
推荐阅读
相关标签