Spring Boot is an open-source, opinionated framework built on top of the Spring Framework, designed to simplify and accelerate the development of production-ready, stand-alone, and enterprise-grade applications. It provides a set of features and conventions that enable developers to quickly set up, configure, and deploy applications with minimal boilerplate code.
Overall, Spring Boot is an excellent choice for developers looking to build robust and scalable applications with minimal configuration overhead. Its opinionated nature and built-in conventions speed up development and make it a popular framework for a wide range of applications.
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=my_database
Replace the values with your MongoDB connection details.
package com.example.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "users")
public class User {
@Id
private String id;
private String username;
private String password;
// Constructors, getters, setters, and other methods
}
Create another Java class named Task:
package com.example.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "tasks")
public class Task {
@Id
private String id;
private String name;
private boolean completed;
// Constructors, getters, setters, and other methods
}
package com.example.repository;
import com.example.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository {
User findByUsername(String username);
}
package com.example.security;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
@Autowired
public SecurityConfig(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(username -> userRepository.findByUsername(username))
.passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Task Manager - Register</title>
</head>
<body>
<h1>Register</h1>
<form action="/register" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Register</button>
</form>
</body>
</html>
Create another Thymeleaf HTML file named login.html for user login:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Task Manager - Login</title>
</head>
<body>
<h1>Login</h1>
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
</body>
</html>
package com.example.controller;
import com.example.model.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
@Autowired
public UserController(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@GetMapping("/register")
public String showRegistrationForm() {
return "register";
}
@PostMapping("/register")
public String registerUser(@RequestParam String username, @RequestParam String password) {
User user = new User();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(password));
userRepository.save(user);
return "redirect:/login";
}
@GetMapping("/login")
public String showLoginForm() {
return "login";
}
}
package com.example.service;
import com.example.model.Task;
import com.example.repository.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class TaskService {
private final TaskRepository taskRepository;
@Autowired
public TaskService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public List<Task> getAllTasks() {
return taskRepository.findAll();
}
public Optional<Task> getTaskById(String id) {
return taskRepository.findById(id);
}
public Task saveTask(Task task) {
return taskRepository.save(task);
}
public void deleteTaskById(String id) {
taskRepository.deleteById(id);
}
}
package com.example.controller;
import com.example.model.Task;
import com.example.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/tasks")
public class TaskController {
private final TaskService taskService;
@Autowired
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
@GetMapping
public List<Task> getAllTasks() {
return taskService.getAllTasks();
}
@GetMapping("/{id}")
public ResponseEntity<Task> getTaskById(@PathVariable String id) {
Optional<Task> task = taskService.getTaskById(id);
return task.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
}
@PostMapping
public Task createTask(@RequestBody Task task) {
return taskService.saveTask(task);
}
@PutMapping("/{id}")
public ResponseEntity<Task> updateTask(@PathVariable String id, @RequestBody Task updatedTask) {
Optional<Task> task = taskService.getTaskById(id);
if (task.isPresent()) {
Task taskToUpdate = task.get();
taskToUpdate.setName(updatedTask.getName());
taskToUpdate.setCompleted(updatedTask.isCompleted());
return ResponseEntity.ok(taskService.saveTask(taskToUpdate));
} else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTask(@PathVariable String id) {
Optional<Task> task = taskService.getTaskById(id);
if (task.isPresent()) {
taskService.deleteTaskById(id);
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.notFound().build();
}
}
}
mvn spring-boot:run
The objective of this website is to Train the people in software field, develop them as good human resources and deploy them in meaningful employment. The high level of hands-on-training and case studies ensures that Trainee gain the optimum benefits. Online Tutorial on Technology subjects as below with Interview Questions and Answers.