Tiếp theo bài trước: Custom Security to Angular Spring Boot App.
Thêm controller class:
package com.example.springangularfrontendserver.controller;
import java.security.Principal;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("banking")
public class BankingController {
// GET /banking/transfer?account=Bob&amount=100
@GetMapping("transfer")
public Map<String, Object> transfer(
Principal user,
@RequestParam Map<String, String> params
) {
String from = user.getName();
String to = params.get("account");
Integer amount = Integer.parseInt(params.get("amount"));
System.out.printf("Sending $%d from %s to %s\n", amount, from, to);
return Map.of(
"from", from,
"to", to,
"amount", amount
);
}
// POST /banking/transfer
//
// {
// "account": "Bob",
// "amount": 100
// }
@PostMapping("transfer")
public Map<String, Object> transferPost(
Principal user,
@RequestBody Map<String, String> body
) {
String from = user.getName();
String to = body.get("account");
Integer amount = Integer.parseInt(body.get("amount"));
System.out.printf("Sending %d from %s to %s using POST request\n", amount, from, to);
return Map.of(
"from", from,
"to", to,
"amount", amount
);
}
}
Frontend code:
app.component.html
<h1>Welcome to Our Bank</h1>
<h3 style="text-align: center">Transfer Money</h3>
<hr />
Account:
<input
type="text"
[value]="transfer.to"
(change)="handleAccountChange($event)"
/>
<br />
<br />
Ammount:
<input
type="number"
[value]="transfer.amount"
(change)="handleAmountChange($event)"
/>
<br />
<br />
<button (click)="transferMoney()">Transfer money</button> <br /><br />
<button (click)="transferMoneyPost()">Transfer money - POST</button>
app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'client';
transfer = {
to: '',
amount: 0
}
constructor (private readonly http: HttpClient) {}
handleAccountChange (event: any): void {
this.transfer.to = event.target.value
}
handleAmountChange (event: any): void {
this.transfer.amount = parseInt(event.target.value)
}
transferMoney (): void {
this.http.get('/banking/transfer', {
params: {
account: this.transfer.to,
amount: this.transfer.amount
}
}).subscribe(console.log)
}
transferMoneyPost (): void {
this.http.post('/banking/transfer', {
account: this.transfer.to,
amount: this.transfer.amount
}).subscribe(console.log)
}
}
Lưu ý: Thêm import ở module cho phù hợp. GET sẽ chạy được POST không chạy được vì CSRF.