this is my user entity class
package com.example.hardware_inventory.model;
public class User {
private Long userId;
private String username;
private String passwordHash;
private String role;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
// getters and setters
}
this is my User Repository class
package com.example.hardware_inventory.repository;
import com.example.hardware_inventory.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.dao.EmptyResultDataAccessException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
private static final class UserRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUserId(rs.getLong("user_id"));
user.setUsername(rs.getString("username"));
user.setPasswordHash(rs.getString("password_hash"));
user.setRole(rs.getString("role"));
return user;
}
}
public List<User> findAll() {
String sql = "SELECT * FROM users";
return jdbcTemplate.query(sql, new UserRowMapper());
}
public Optional<User> findById(Long id) {
String sql = "SELECT * FROM users WHERE user_id = ?";
try {
return Optional.ofNullable(jdbcTemplate.queryForObject(sql, new Object[]{id}, new UserRowMapper()));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
}
public Optional<User> findByUsername(String username) {
String sql = "SELECT * FROM users WHERE username = ?";
try {
return Optional.ofNullable(jdbcTemplate.queryForObject(sql, new Object[]{username}, new UserRowMapper()));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
}
public void save(User user) {
String sql = "INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)";
jdbcTemplate.update(sql, user.getUsername(), user.getPasswordHash(), user.getRole());
}
public void update(User user) {
String sql = "UPDATE users SET username = ?, password_hash = ?, role = ? WHERE user_id = ?";
jdbcTemplate.update(sql, user.getUsername(), user.getPasswordHash(), user.getRole(), user.getUserId());
}
public void deleteById(Long id) {
String sql = "DELETE FROM users WHERE user_id = ?";
jdbcTemplate.update(sql, id);
}
public void resetPassword(Long id, String newPassword) {
String sql = "UPDATE users SET password_hash = ? WHERE user_id = ?";
jdbcTemplate.update(sql, newPassword, id);
}
public void blockUser(Long id) {
String sql = "UPDATE users SET role = 'blocked' WHERE user_id = ?";
jdbcTemplate.update(sql, id);
}
}
This is my User Service class
package com.example.hardware_inventory.service;
import com.example.hardware_inventory.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void resetPassword(Long id, String newPassword) {
userRepository.resetPassword(id, newPassword);
}
public void blockUser(Long id) {
userRepository.blockUser(id);
}
}
I have users given role as user or admin and admin can add a new user in the web page
In the add user web page I need to have a list of users already in the table along with option for admin to add user and reset password and block users
this is my HTML code for the add_new_user page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New User</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="form-container">
<h1>Add New User</h1>
<form id="add-user-form">
<input type="text" id="new-username" placeholder="Username" required>
<input type="password" id="new-password" placeholder="Password" required>
<select id="role">
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
<button type="submit">Add User</button>
</form>
</div>
<div class="table-container">
<h1>All Users</h1>
<table id="users-table">
<thead>
<tr>
<th>User ID</th>
<th>Username</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- Dynamic rows will be inserted here -->
</tbody>
</table>
</div>
<script src="scripts.js"></script>
</body>
</html>
This is the javascript I’ve used
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('add-user-form');
const usersTable = document.getElementById('users-table').getElementsByTagName('tbody')[0];
// Fetch users and display them
fetch('/api/users')
.then(response => response.json())
.then(data => {
data.forEach(user => {
addUserRow(user);
});
});
// Handle form submission
form.addEventListener('submit', function(event) {
event.preventDefault();
const newUsername = document.getElementById('new-username').value;
const newPassword = document.getElementById('new-password').value;
const role = document.getElementById('role').value;
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: newUsername,
password: newPassword,
role: role
})
})
.then(response => response.json())
.then(user => {
addUserRow(user);
form.reset();
});
});
function addUserRow(user) {
const row = usersTable.insertRow();
const cellId = row.insertCell(0);
const cellUsername = row.insertCell(1);
const cellRole = row.insertCell(2);
const cellActions = row.insertCell(3);
cellId.textContent = user.userId;
cellUsername.textContent = user.username;
cellRole.textContent = user.role;
cellActions.innerHTML = `<form action="/api/users/delete/${user.userId}" method="post">
<button type="submit">Delete</button>
</form>`;
}
});
My HTML is not getting populated and I’m struggling with this
My Database is already connected with my application I just can’t fetch data correctly from my database
N P Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.