Spring Boot Aplicacion Web Parte 4.

Repositorio y Servicios

Ahora es necesario crear la interfaz que se encargara de conectar y persisitir nuestras entidades(entity), ademas crearemos el servicio que retornara la lista de usuarios para nuestra tabla y la lista de roles para nuestro formulario.


Contenido

  1. Crear User y Role repositorio.
  2. Crear interfaz e implementacion del servicio de usuario.
  3. Mostrar Lista de Usuarios y Roles.
  4. Git Commit
  5. Video Paso a Paso.

Crear User y Role Repositorio.

package com.cristianruizblog.springbootApp.repository;

import java.util.Optional;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.cristianruizblog.springbootApp.entity.User;

@Repository
public interface UserRepository extends CrudRepository<User, Long>{

	public Optional findByUsername(String username);
	
	public Optional findByIdAndPassword(Long id, String password);

}
package com.cristianruizblog.springbootApp.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.cristianruizblog.springbootApp.entity.Role;

@Repository
public interface RoleRepository extends CrudRepository<Role, Long>{

}

2.Crear interfaz e implementacion del servicio de usuario.

package com.cristianruizblog.springbootApp.service;

import com.cristianruizblog.springbootApp.entity.User;

public interface UserService {

	public Iterable getAllUsers();
		
}
package com.cristianruizblog.springbootApp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cristianruizblog.springbootApp.entity.User;
import com.cristianruizblog.springbootApp.repository.UserRepository;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	UserRepository userRepository;
	
	public Iterable getAllUsers(){
		return userRepository.findAll();
	}
	
}

3.Mostrar Lista de Usuarios y Roles.

La manera de pasar valores a nuestro HTML es agregandolos al Map del modelo. En este caso agregaremos 4:

  1. userForm: Lo utilizar el formulario de creación de usuario.
  2. roles: Mostrara la lista de roles disponibles en el formulario.
  3. userList: Lo utilizaremos para mostrar la lista de usuario en el DataTable
  4. listTab: Indica que la pestaña list sera la que este activa.
package com.cristianruizblog.springbootApp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.cristianruizblog.springbootApp.entity.User;
import com.cristianruizblog.springbootApp.repository.RoleRepository;
import com.cristianruizblog.springbootApp.repository.UserRepository;
import com.cristianruizblog.springbootApp.service.UserService;


@Controller
public class UserController {

	@Autowired
	RoleRepository roleRepository;
	
	@Autowired 
	UserService userService;
	
	@GetMapping("/userForm")
	public String getUserForm(Model model) {
		model.addAttribute("userForm", new User());
		model.addAttribute("roles",roleRepository.findAll());
		model.addAttribute("userList", userService.getAllUsers());
		model.addAttribute("listTab","active");
		return "user-form/user-view";
	}
	
	@GetMapping({"/","/login"})
	public String index() {
		return "index";
	}
}

Para poder mostrar adecuadamente la lista de usuarios debemos de actualizar el archivo user-list.html para cargar el tbody dinamicamente.


<div class="table-responsive">
	<table id="userList" class="table table-bordered table-hover table-striped">
		<thead class="thead-light">
		<tr>
			<th scope="col">#</th>
			<th scope="col">First</th>
			<th scope="col">Last</th>
			<th scope="col">Username</th>
			<th scope="col">E-mail</th>
			<th></th>
		</tr>
		</thead>
		<tbody>
		<tr th:each="user: ${userList}">
			<td th:text="${user.id}"></td>
			<td th:text="${user.firstName}"></td>
			<td th:text="${user.lastName}"></td>
			<td th:text="${user.username}"></td>
			<td th:text="${user.email}"></td>
			<td>
					<a href="#" th:href="@{'/editUser/'+ ${user.id}}"><i class="fas fa-edit"></i></a>
					| <a href="#" th:onclick="'javascript:confirmDelete(\''+ ${user.id} +'\');'"><i class="fas fa-user-times"></i></a>
			</td>
		</tr>
		</tbody>
	</table>
</div>

El cambio necesario en user-form.html sera agregar el atributo th:action a la etiqueta form y ademas el atributo th:field a cada input del formulario.
Para mostrar los roles tendremos que agregar un select y observa que la etiqueta opcion tiene el atributo th:each para poder interactuar con los roles agregados en el controller.

<form id="userForm" th:object="${userForm}" method="post" class="form" role="form">
	<input class="form-control" type="hidden" th:field="${userForm.id}">
	<div class="form-group row">
		<label class="col-lg-3 col-form-label form-control-label">First name</label>
		<div class="col-lg-9">
			<input class="form-control" type="text" th:field="${userForm.firstName}">
		</div>
	</div>
	<div class="form-group row">
		<label class="col-lg-3 col-form-label form-control-label">Last
			name</label>
		<div class="col-lg-9">
			<input class="form-control" type="text" th:field="${userForm.lastName}">
		</div>
	</div>
	<div class="form-group row">
		<label class="col-lg-3 col-form-label form-control-label">Email</label>
		<div class="col-lg-9">
			<input class="form-control" type="email" th:field="${userForm.email}">
		</div>
	</div>
	<div class="form-group row">
		<label class="col-lg-3 col-form-label form-control-label">Username</label>
		<div class="col-lg-9">
			<input class="form-control" type="text" th:field="${userForm.username}">
		</div>
	</div>
	<div class="form-group row">
		<label th:text="Roles" class="col-lg-3 col-form-label form-control-label"></label>
		<div class="col-lg-9">
			<select th:field="${userForm.roles}" class="form-control" size="3">
				<option th:each="role :${roles}" th:value="${role.id}" th:text="${role.name}">
				</option>
			</select>
		</div>
	</div>
	<div class="form-group row">
		<label class="col-lg-3 col-form-label form-control-label">Password</label>
		<div class="col-lg-9">
			<input class="form-control" type="password" th:field="${userForm.password}">
		</div>
	</div>
	<div class="form-group row">
		<label class="col-lg-3 col-form-label form-control-label">Confirm</label>
		<div class="col-lg-9">
			<input class="form-control" type="password" th:field="${userForm.confirmPassword}">
		</div>
	</div>
	<div class="form-group row">
		<div class="col-lg-12 text-center">
			<input type="reset" class="btn btn-secondary" value="Cancel">
			<input type="button" class="btn btn-primary"
				value="Save Changes">
		</div>
	</div>
</form>

En el modelo también agregamos el atributo <strong>listTab,</strong>este es necesario para mostrar dinamicamente la pestaña deseada. Asegurate de agregar th:classappend=” ${listTab}” al link de cada pestaña.

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>nav-link<span class="token punctuation">"</span></span> <span class="token attr-name"><span class="token namespace">th:</span>classappend</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span> ${listTab}<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>list-tab<span class="token punctuation">"</span></span> <span class="token attr-name">data-toggle</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>tab<span class="token punctuation">"</span></span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>#list<span class="token punctuation">"</span></span> <span class="token attr-name">role</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>tab<span class="token punctuation">"</span></span> <span class="token attr-name">aria-controls</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>list<span class="token punctuation">"</span></span> <span class="token attr-name">aria-selected</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>List<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>a</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>nav-link<span class="token punctuation">"</span></span> <span class="token attr-name"><span class="token namespace">th:</span>classappend</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span> ${formTab}<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>form-tab<span class="token punctuation">"</span></span> <span class="token attr-name">data-toggle</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>tab<span class="token punctuation">"</span></span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>#form<span class="token punctuation">"</span></span> <span class="token attr-name">role</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>tab<span class="token punctuation">"</span></span> <span class="token attr-name">aria-controls</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>form<span class="token punctuation">"</span></span> <span class="token attr-name">aria-selected</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Form<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>a</span><span class="token punctuation">></span></span>
Markup

<div class="tab-pane fade show" th:classappend=" ${listTab}" id="list" role="tabpanel" aria-labelledby="list-tab">
<div class="tab-pane fade show" th:classappend=" ${formTab}" id="form" role="tabpanel" aria-labelledby="form-tab">

Para finalizar inicia la aplicacion y asegurate que en la lista se muestre el usuario admin y en el formulario se muestren los roles disponibles.

4.Git Commit

Repository Commit
Repository Commit

Github Commit:
https://github.com/cruizg93/Spring-Boot-Aplicacion/commit/b16732880a9d348fe613635eb4e31659a47294fd

5.Video Paso a Paso


Menu

  1. Setup
  2. Entidades y POJOS
  3. Basic HTML
  4. Lista de Usuarios
  5. Crear Usuario y Validar Campos
  6. Editar Usuario
  7. Eliminar Usuario
  8. Cambiar Contraseña
  9. Spring Security
  10. Paginas de Error
  11. Bonus, Arreglando Cositas
  12. Formulario de registro
  13. Despliegue en Heroku

Gracias por llegar al final de este post.
No se te olvide dejar tus comentario o preguntas aca abajo o en mi twitter @Cruizg93

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *