Fullstack Login App with Angular 17 and Java Spring Framework | Frontend

Posted by


In this tutorial, we will be creating a full-stack application with a login functionality using Angular 17 for the frontend and Java Spring for the backend. This project will serve as a foundation for building more complex applications with user authentication and authorization.

Before we dive into the coding part, make sure you have the following tools installed on your machine:

  1. Node.js and npm – for installing Angular CLI and managing frontend dependencies.
  2. Java Development Kit (JDK) – for compiling and running Java code.
  3. Spring Boot – for creating a RESTful API backend.
  4. IDE of your choice – I recommend using IntelliJ IDEA for Java development and Visual Studio Code for Angular development.

Now, let’s start by setting up the backend with Java Spring.

Setting up the Backend with Java Spring

  1. Create a new Spring Boot project using start.spring.io. Select the following dependencies:

    • Spring Web
    • Spring Data JPA
    • H2 Database (or any other database of your choice)
  2. Generate the project and import it into your IDE.

  3. Create a new Java package for your application (e.g., com.example.loginapp).

  4. Inside the package, create a new Java class named "User" with the following fields:

    @Entity
    public class User {
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       private Long id;
    
       private String username;
       private String password;
    
       // Getters and Setters
    }
  5. Create a UserRepository interface by extending JpaRepository:

    public interface UserRepository extends JpaRepository<User, Long> {
       User findByUsername(String username);
    }
  6. Create a UserController class for handling user authentication:

    @RestController
    @RequestMapping("/api")
    public class UserController {
       @Autowired
       private UserRepository userRepository;
    
       @PostMapping("/login")
       public ResponseEntity<User> login(@RequestBody User user) {
           User existingUser = userRepository.findByUsername(user.getUsername());
           if (existingUser != null && existingUser.getPassword().equals(user.getPassword())) {
               return ResponseEntity.ok(existingUser);
           } else {
               return ResponseEntity.badRequest().build();
           }
       }
    }
  7. Run your Spring Boot application and test the API endpoints using a tool like Postman to make sure everything is working as expected.

Setting up the Frontend with Angular 17

  1. Create a new Angular project using Angular CLI:

    ng new login-app
  2. Install Angular Material for UI components and animations:

    ng add @angular/material
  3. Create a login component using Angular CLI:

    ng generate component login
  4. Inside the login component, create a form for user input:

    <form (ngSubmit)="onSubmit()">
       <mat-form-field>
           <input matInput placeholder="Username" [(ngModel)]="username">
       </mat-form-field>
       <mat-form-field>
           <input matInput placeholder="Password" [(ngModel)]="password" type="password">
       </mat-form-field>
       <button mat-raised-button color="primary" type="submit">Login</button>
    </form>
  5. Implement the onSubmit method in the login component to call the backend API:

    export class LoginComponent {
       username: string;
       password: string;
    
       constructor(private http: HttpClient) {}
    
       onSubmit() {
           this.http.post<User>('/api/login', { username: this.username, password: this.password })
               .subscribe((user) => {
                   // Handle successful login
               }, (error) => {
                   // Handle login error
               });
       }
    }
  6. Configure HttpClientModule in your app module to enable HTTP requests:

    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
       imports: [HttpClientModule]
    })
  7. Run your Angular application using the following command:

    ng serve
  8. Open your browser and navigate to http://localhost:4200 to test the login functionality.

Congratulations! You have successfully created a full-stack application with login functionality using Angular 17 for the frontend and Java Spring for the backend. Feel free to customize and expand this project to suit your specific requirements. Happy coding!

0 0 votes
Article Rating

Leave a Reply

34 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@kipperdev
2 hours ago

⭐ Seja um membro do canal e tenha acesso à lives, vídeos e conteúdos exclusivos!
https://www.youtube.com/channel/UCpKvMmsF6QrkVr_zWaLGK-A/join

@jeffersonsantana7605
2 hours ago

vc é fera Feh eu estou aprendendo mais com vc do que na faculdade de ADS, e a Linguagem JAVA foi a que eu escolhi para trampar 🤦 kkkkkkkkkk

@Matheus_1582
2 hours ago

Não precisa instalar o angular globalmente, basta só digitar o seguinte comando
npm init @angular (nome do projeto)

@tarikraposo7799
2 hours ago

Essa gataiada no formulário me quebrou kkkk meio que tem que gravar a receita ali pra evitar o erro. Mas, top demais a aula.

@julio4826
2 hours ago

FER TO USANDO SEU PROJETO PARA FAZER O DESAFIO DE UMA VAGA DE EMPREGO! OBRIGADO PELO SEU TRABALHO NO YOUTUBE

@kevinanderson7751
2 hours ago

Estou com um erro que quando vou pro localhost:4200/login, não aparece nada. Só aparece quando escrevo algo no app.component.html, aí aparece tanto no localhost:4200/login quanto no localhost:4200

@vicenzofrusciante5996
2 hours ago

Oi, consegue tirar essa musica nos próximos vídeos? Ela me distrai bastaste, por mim poderia ser até sem música.

@aln_soares
2 hours ago

Só videos bons nesse canal, show demais

@leandroperez8157
2 hours ago

Fernanda, parabéns pelo conteudo abordado, uma pergunta a parte 2 sairá para quem ainda não é um membro também?

@mayaracaroline1557
2 hours ago

Excelente video, cade o back-end😭😭😭😁😁

@jeanc936
2 hours ago

Muito top FER, PARABÉNS. Gostaria muito que vc detalhasse mais sobre o angular, principalmente na parte que não estava dando certo a label, vc criou muito código apenas pra corriri um problema de visibilidade. Nesta parte ficou confuso pra mim… Mas muito top!!!1

@danivelardi8835
2 hours ago

Conteúdo excelente 👏👏👏

@sedentarionuncamais4659
2 hours ago

tem a parte 2 ?

@AlexSilva-fb3ol
2 hours ago

Conteúdo top. Mas infelizmente não consegui avançar devido ao seguinte erro quando injeto o serviço do toast no ts. Error: Uncaught (in promise): Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more. Caso alguem puder dar um help, agradeço demais.

@BulboGC
2 hours ago

se eu tivesse trabalhando virava membro

@lucasrosa9082
2 hours ago

não estou conseguindo utilizar o toastService, mesmo realizando o passo a passo apresentado durante a aula

@SR-vt5cp
2 hours ago

Nas versões mais recentes não existe mais a pasta assets, as imagens e ícones agora são colocados na pasta public.

@nicobonder
2 hours ago

Olá, no minuto 53:54 você verá este código: loginForm!: FormGroup<LoginForm>; mas em nenhum momento do vídeo você consegue ver quando coloca <LoginForm>. Você poderia explicar por que o adicionou e o que seria? Obrigado.

@LofiBeatsSoundsASMR
2 hours ago

Gostei muito vlww, só que alguns cortes que vc faz é mto rapido na hora de da pause e ver o codigo todo, ae tem que ficar voltando pra acompanhar kkk

@mylenav
2 hours ago

essa parte do ControlValueAcessor a gente finge que entendeu

34
0
Would love your thoughts, please comment.x
()
x