Dica: Para este roteiro, acompanhe também o conteúdo: Dicionário de anotações Java/Spring
Crie um no projeto Spring e siga as instruções abaixo:
Adicione as dependências abaixo no arquivo pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
No caso de utilizar o banco de dados MySQL
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
No caso de utilizar o banco de dados H2
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Altere o arquivo application.properties (caminho: src/main/resources) com as configurações abaixo para acesso ao banco de dados:
No caso de utilizar o banco de dados MySQL
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/bdspring
spring.datasource.username=spring
spring.datasource.password=spring
# create db mysql
# mysql> create database db_spring;
# mysql> create user 'spring'@'%' identified by 'spring';
# mysql> grant all on db_spring.* to 'spring'@'%';
Onde o username e password possuem o valor "spring" e o nome do banco de dados corresponde ao valor "bdspring". Atenção: Para o banco de dados, MySQL, é necessário a execução dos comandos em #
No caso de utilizar o banco de dados H2
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
# Datasource
spring.datasource.url=jdbc:h2:./bdspring
spring.datasource.username=spring
spring.datasource.password=spring
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
Onde o username e password possuem o valor "spring" e o nome do banco de dados corresponde ao valor "bdspring".
Acesse o banco de dados H2 através do link: http://localhost:8080/h2
No caminho src/main/java do projeto, além do pacote já existente, crie os pacotes: controller, model, repository e service, conforme exemplo abaixo:
Crie as classes abaixo, respeitando os pacotes indicados:
model/Aluno.java
@Entity
public class Aluno {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer id;
private String name;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
repository/AlunoRepository.java
@Repository("alunoRepository")
public interface AlunoRepository extends JpaRepository<Aluno, Integer> {
}
service/AlunoService.java
public interface AlunoService {
Optional<Aluno> getAlunoById(Integer id);
List<Aluno> getAllAlunos();
void deleteAllAlunos();
void deleteAlunoById(Integer id);
void updateAluno(Aluno aluno);
void insertAluno(Aluno aluno);
}
service/AlunoServiceImpl.java
@Service("alunoService")
public class AlunoServiceImpl implements AlunoService {
@Autowired
AlunoRepository alunoRepository;
@Override
public Optional<Aluno> getAlunoById(Integer id) {
return alunoRepository.findById(id);
}
@Override
public List<Aluno> getAllAlunos() {
return alunoRepository.findAll();
}
@Override
public void deleteAllAlunos() {
alunoRepository.deleteAll();
}
@Override
public void deleteAlunoById(Integer id) {
alunoRepository.deleteById(id);
}
@Override
public void updateAluno(Aluno aluno) {
if (aluno.getId() != null) {
alunoRepository.save(aluno);
}
}
@Override
public void insertAluno(Aluno aluno) {
if (aluno.getId() == null) {
alunoRepository.save(aluno);
}
}
}
controller/SpringBdRestController.java
@RestController
public class SpringBdRestController {
@Autowired
AlunoService alunoService;
@RequestMapping(value = "/alunos", method = RequestMethod.GET)
public List<Aluno> getAllAlunos() {
return alunoService.getAllAlunos();
}
@RequestMapping(value = "/alunos/{id}", method = RequestMethod.GET)
public Optional<Aluno> getAllAlunos(@PathVariable Integer id) {
return alunoService.getAlunoById(id);
}
@RequestMapping(value = "/alunos", method = RequestMethod.POST)
public void addAluno(@RequestBody Aluno aluno) {
alunoService.insertAluno(aluno);
}
@RequestMapping(value = "/alunos", method = RequestMethod.PUT)
public void updateAluno(@RequestBody Aluno aluno) {
alunoService.updateAluno(aluno);
}
@RequestMapping(value = "/alunos/{id}", method = RequestMethod.DELETE)
public void deleteAlunos(@PathVariable Integer id) {
alunoService.deleteAlunoById(id);
}
@RequestMapping(value = "/alunos", method = RequestMethod.DELETE)
public void deleteAlunos() {
alunoService.deleteAllAlunos();
}
}
controller/SpringBdController.java
@Controller
public class AlunoController {
@Autowired
AlunoService alunoService;
@RequestMapping(value = "view/alunos", method = RequestMethod.GET)
public ModelAndView getIndex(@ModelAttribute("message") final String message,
@ModelAttribute("error") final String error) {
ModelAndView mav = new ModelAndView("main");
mav.addObject("listAlunos", alunoService.getAllAlunos());
mav.addObject("message", message);
mav.addObject("error", error);
return mav;
}
@RequestMapping(value = "view/read", method = RequestMethod.GET)
public ModelAndView read() {
return new ModelAndView("read", "listAlunos", alunoService.getAllAlunos());
}
@RequestMapping(value = "view/insert", method = RequestMethod.GET)
public ModelAndView insert() {
ModelAndView mav = new ModelAndView("insert");
mav.addObject("aluno", new Aluno());
return mav;
}
@RequestMapping(value = "view/insert", method = RequestMethod.POST)
public String submitInsert(@ModelAttribute("aluno")Aluno aluno,
BindingResult result,
ModelMap model,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("error", "Houve um erro!");
} else {
alunoService.insertAluno(aluno);
redirectAttributes.addFlashAttribute("message", "Aluno inserido!");
}
return "redirect:/view/alunos";
}
@RequestMapping(value = "view/update", method = RequestMethod.GET)
public ModelAndView update(Integer id) {
ModelAndView mav = new ModelAndView("update");
mav.addObject("aluno", alunoService.getAlunoById(id).get());
return mav;
}
@RequestMapping(value = "view/update", method = RequestMethod.POST)
public String submitUpdate(@ModelAttribute("aluno")Aluno aluno,
BindingResult result,
ModelMap model,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("error", "Houve um erro!");
} else {
alunoService.updateAluno(aluno);
redirectAttributes.addFlashAttribute("message", "Aluno atualizado!");
}
return "redirect:/view/alunos";
}
@RequestMapping(value = "view/delete", method = RequestMethod.GET)
public ModelAndView delete(Integer id) {
ModelAndView mav = new ModelAndView("delete");
mav.addObject("aluno", alunoService.getAlunoById(id).get());
return mav;
}
@RequestMapping(value = "view/delete", method = RequestMethod.POST)
public String submitDelete(@ModelAttribute("aluno")Aluno aluno,
BindingResult result,
ModelMap model,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("error", "Houve um erro!");
} else {
alunoService.deleteAlunoById(aluno.getId());
redirectAttributes.addFlashAttribute("message", "Aluno Excluido!");
}
return "redirect:/view/alunos";
}
}
Para que a aplicação reflita os valores em tela (view/html) e permita a inserção dos dados através de formulários, será preciso criar telas com os principais recursos disponíveis em html. Sendo assim, crie os arquivos abaixo dentro do diretório do projeto: src/main/resources/templates
Dica: Para este conteúdo, acompanhe também o material: Thymeleaf
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Pagina de alunos</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
body {
margin:16px;
padding:0
}
</style>
</head>
<body>
<span th:if="${message != ''}">
<div class="alert alert-success" role="alert">
<span th:text="${message}" />
</div>
</span>
<span th:if="${error != ''}">
<div class="alert alert-danger" role="alert">
<span th:text="${error}" />
</div>
</span>
<a href="insert">Inserir novo</a> | <a href="read">Ver todos</a> <br> <br>
<table style="width:100%">
<tr>
<th>ID</td>
<th>Nome</td>
<th>E-mail</td>
<th>Excluir?</td>
<th>Alterar?</td>
</tr>
<tr th:each="aluno : ${listAlunos}">
<td th:text="${aluno.id}"></td>
<td th:text="${aluno.name}"></td>
<td th:text="${aluno.email}"></td>
<td><a th:href="@{/view/delete(id=${aluno.id})}">Deletar</a></td>
<td><a th:href="@{/view/update(id=${aluno.id})}">Alterar</a></td>
</tr>
</table>
</body>
</html>
insert.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Inserir aluno</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
body {
margin:16px;
padding:0
}
</style>
</head>
<body>
<form action="../view/insert" method="POST" modelAttribute="aluno">
Nome Aluno:<br>
<input type="text" name="name"><br>
<br>
Email Aluno:<br>
<input type="text" name="email"><br>
<br>
<input type="submit" value="Inserir">
</form>
</body>
</html>
read.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Ler alunos</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
body {
margin:16px;
padding:0
}
</style>
</head>
<body th:each="aluno : ${listAlunos}">
<span th:text="${'ID: ' + aluno.id}"></span><br>
<strong><span th:text="${'Nome: ' + aluno.name}"></span></strong><br>
<span th:text="${'Email: ' + aluno.email}"></span><br>
<br>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Atualizar aluno</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
body {
margin:16px;
padding:0
}
</style>
</head>
<body>
<form action="../view/update" method="POST" modelAttribute="aluno">
ID:<br>
<input type="text" name="id" th:value="${aluno.id}" readOnly="true"><br>
Nome Aluno:<br>
<input type="text" name="name" th:value="${aluno.name}"><br>
<br>
Email Aluno:<br>
<input type="text" name="email" th:value="${aluno.email}"><br>
<br>
<input type="submit" value="Atualizar">
</form>
</body>
</html>
delete.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Deletar aluno</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
body {
margin:16px;
padding:0
}
</style>
</head>
<body>
<form action="../view/delete" method="POST" modelAttribute="aluno">
ID:<br>
<input type="text" name="id" th:value="${aluno.id}" readOnly="true"><br>
Nome Aluno:<br>
<input type="text" name="name" th:value="${aluno.name}" readOnly="true"><br>
<br>
Email Aluno:<br>
<input type="text" name="email" th:value="${aluno.email}" readOnly="true"><br>
<br>
<input type="submit" value="Deletar">
</form>
</body>
</html>
Teste os resultados da Aplicação!
Acessos e serviços da aplicação:
http://localhost:8080/view/alunos = Acessa o CRUD completo da aplicação
http://localhost:8080/view/insert = Permite a inserção de um novo Aluno
http://localhost:8080/view/read = Permite ver todos os alunos cadastrados
http://localhost:8080/view/delete?id={id} Permite excluir um aluno específico
http://localhost:8080/view/update?id={id} Permite alterar um aluno específico
Serviços RESTful:
http://localhost:8080/alunos :GET = Retorna JSON com todos os alunos cadastrados
http://localhost:8080/alunos/1 :GET = Retorna JSON do id do aluno cadastrado
http://localhost:8080/alunos :DELETE = Deleta todos os alunos cadastrados
http://localhost:8080/alunos/1 :DELETE = Deleta um aluno específico pelo id
http://localhost:8080/alunos :PUT {Body} = Atualiza um aluno específico pelo id
http://localhost:8080/alunos :POST{Body} = Insere um novo aluno
Exemplo: https://github.com/proflucasscf/JavaWeb [Projeto: SpringBDController]