---
# System prepended metadata

title: Untitled

---

<p><img src="https://i.imgur.com/8nLaU2i.png" alt="" title="Entre no nosso site e veja nossos cursos"></p><h1 id="-Java-WebDeveloper---Sábado-Manhã---Aula-19" data-id="-Java-WebDeveloper---Sábado-Manhã---Aula-19"><a class="anchor hidden-xs" href="#-Java-WebDeveloper---Sábado-Manhã---Aula-19" title="-Java-WebDeveloper---Sábado-Manhã---Aula-19"><span class="octicon octicon-link"></span></a><img class="emoji" alt=":coffee:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/coffee.png"><span> Java WebDeveloper - Sábado Manhã - Aula 24</span></h1><h2 id="-Tema-da-aula" data-id="-Tema-da-aula"><a class="anchor hidden-xs" href="#-Tema-da-aula" title="-Tema-da-aula"><span class="octicon octicon-link"></span></a><img class="emoji" alt=":book:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/book.png"><span> Tema da aula:</span></h2><p><li><span>Back-end de um sistema sobre saúde no formato da Wikipedia. Projeto Back Hospital. Projeto Maven, Spring Boot, Spring Security, JPA, BD em MySQL.</li></span></p>
<blockquote style="border-left-color: red;">
<p><span class="color" data-color="red"></span><span> </span><small><i class="fa fa-user"></i> Prof Edson Belém - profedsonbelem@gmail.com <i class="fa fa-clock-o"></i> Sábado, Jul 25, 2020</small></p>
</blockquote><blockquote style="border-left-color: purple;">
<p><span class="color" data-color="purple"></span><span> </span><small><i class="fa fa-user"></i> Profa Luciana Medeiros - lucianamedeiros.coti@gmail.com <i class="fa fa-clock-o"></i> Sábado, Jul 25, 2020</small></p></blockquote>

</p><hr><h2 id="-Estrutura-do-projeto-depois-de-finalizado" data-id="-Estrutura-do-projeto-depois-de-finalizado"><a class="anchor hidden-xs" href="#-Estrutura-do-projeto-depois-de-finalizado" title="-Estrutura-do-projeto-depois-de-finalizado"><span class="octicon octicon-link"></span></a><img class="emoji" alt=":eye:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/eye.png"><span> Estrutura do projeto depois de finalizado:</span></h2>

![](https://i.imgur.com/WWM2XqB.jpg)
<hr>
<h3><img class="emoji" alt=":coffee:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/coffee.png"><span> pom.xml</span></h3>

``` xml=
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/xsd/maven-4.0.0.xsd">

	
	<modelVersion>4.0</modelVersion>
	<groupId>br.com.coti</groupId>
	<artifactId>projetoBackHospital</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.2.RELEASE</version>
	</parent>


	<properties>
		<java.version>1.8</java.version>
		<downloadSources>true</downloadSources>
		<downloadJavadocs>true</downloadJavadocs>
	</properties>

	<dependencies>



		<!-- security rest -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.datatype</groupId>
			<artifactId>jackson-datatype-jsr310</artifactId>
		</dependency>


		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<!-- mysql ultima configuracao -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>


		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.7</version>
			<scope>test</scope>
		</dependency>


		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>

	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<addResources>true</addResources>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.22.0</version>
			</plugin>

		</plugins>

	</build>




</project>
```


<h3><img class="emoji" alt=":coffee:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/coffee.png"><span> Application.java</span></h3>

``` java=
package br.com.coti.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EntityScan(basePackages = "br.com.coti.entity")
@EnableJpaRepositories(basePackages = "br.com.coti.repository")
@ComponentScan(basePackages = "br.com.coti.controller")
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

```
<h3><img class="emoji" alt=":coffee:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/coffee.png"><span> UsuarioController.java</span></h3>

``` java=
package br.com.coti.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import br.com.coti.entity.Usuario;
import br.coti.coti.repository.UsuarioRepository;

@CrossOrigin()
@RestController
@ResponseBody
@Validated
public class UsuarioController {

	@Autowired
	UsuarioRepository dao;

	@GetMapping("/usuario")
	public ResponseEntity<?> listagem() {
		List<Usuario> lista = dao.findAll();
		return ResponseEntity.status(200).body(lista);
	}

	@PostMapping("/register")
	public ResponseEntity<?> registrar(@RequestBody Usuario usuario) {
		try {

			Usuario resp = dao.save(usuario);
			if (resp.getIdUsuario() == null) {
				throw new Exception("Usuario nao Gravado");
			}
			return ResponseEntity.status(200).body(resp);
		} catch (Exception ex) {
			Map<String, String> mapa = new HashMap<String, String>();
			mapa.put("erro", "Mensagem ..." + ex.getMessage());
			return ResponseEntity.status(500).body(mapa);
		}

	}

	@PostMapping("/login")
	public ResponseEntity<?> registrador(@RequestBody Usuario usuario) {
		try {

			Usuario resp = dao.findByEmailAndSenha
(usuario.getEmail(), usuario.getSenha());

			if (resp == null) {
				throw new Exception("Nao Logado");
			}
			return ResponseEntity.status(200).body(resp);
		} catch (Exception ex) {
			Map<String, String> mapa = new HashMap<String, String>();
			mapa.put("erro", ex.getMessage());
			return ResponseEntity.status(500).body(mapa);
		}
	}

}

```
<h3><img class="emoji" alt=":coffee:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/coffee.png"><span> UsuarioSecurity.java</span></h3>

```java=
package br.com.coti.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.WebSecurityConfigurerAdapter;

@Configuration
public class UsuarioSecurity extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(AuthenticationManagerBuilder auth) 
        throws Exception {
		auth.inMemoryAuthentication().withUser("medico")
                .password("{noop}password").roles("USER").and()
		.withUser("paciente").password("{noop}password")
                .roles("USER").and().withUser("administrador")
		.password("{noop}admin").roles("USER", "ADMIN");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.httpBasic().and().authorizeRequests()
                .antMatchers(HttpMethod.GET, "/usuario/**").hasRole("ADMIN")
		.antMatchers(HttpMethod.POST, "/register/**").hasRole("ADMIN")
                .antMatchers(HttpMethod.POST, "/login/**")
		.hasRole("USER").antMatchers(HttpMethod.POST, "/login/**")
                .hasRole("ADMIN").and().csrf().disable()
		.formLogin().disable();
	}

}

```
<h3><img class="emoji" alt=":coffee:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/coffee.png"><span> Usuario.java</span></h3>

```java=
package br.com.coti.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name = "tblusuario")
public class Usuario implements Serializable {

	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long idUsuario;
	@Column(length = 50)
	private String nome;
	@Column(length = 50, unique = true)
	private String email;
	@Column(columnDefinition = " enum ('medico','paciente','administrador') ")
	private String perfil;
	@Column(length = 250)
	private String senha;
	@Column
	private Integer latitude;
	@Column
   private String longitude;

	public Usuario() {
	}

 

	public Usuario(Long idUsuario, String nome, 
        String email, String perfil, String senha, Integer latitude,
			String longitude) {
		super();
		this.idUsuario = idUsuario;
		this.nome = nome;
		this.email = email;
		this.perfil = perfil;
		this.senha = senha;
		this.latitude = latitude;
		this.longitude = longitude;
	}



	@Override
	public String toString() {
		return "Usuario [idUsuario=" + idUsuario + ", nome=" + nome 
                + ", email=" + email + ", perfil=" + perfil
		+ ", senha=" + senha + "]";
	}

	public Long getIdUsuario() {
		return idUsuario;
	}

	public void setIdUsuario(Long idUsuario) {
		this.idUsuario = idUsuario;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPerfil() {
		return perfil;
	}

	public void setPerfil(String perfil) {
		this.perfil = perfil;
	}

	public String getSenha() {
		return senha;
	}

	public void setSenha(String senha) {
		this.senha = senha;
	}

	public Integer getLatitude() {
		return latitude;
	}

	public void setLatitude(Integer latitude) {
		this.latitude = latitude;
	}

	public String getLongitude() {
		return longitude;
	}

	public void setLongitude(String longitude) {
		this.longitude = longitude;
	}

}

```
<h3><img class="emoji" alt=":coffee:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/coffee.png"><span> UsuarioRepository.java</span></h3>

```java=
package br.coti.coti.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import br.com.coti.entity.Usuario;

@Repository
public interface UsuarioRepository extends JpaRepository<Usuario, Long> {

	public Usuario findByEmailAndSenha(String login, String senha);

}

```
<h3><img class="emoji" alt=":coffee:" src="https://cdn.jsdelivr.net/npm/@hackmd/emojify.js@2.1.0/dist/images/basic/coffee.png"><span> application.properties</span></h3>

```java=
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.datasource.url=
jdbc:mysql://localhost:3306/BDEND?createDatabaseIfNotExist=true
&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=coti
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.format-sql=true
spring.thymeleaf.enabled=false
server.port=4545
```
<br>
<blockquote style="border-left-color: blue;">
<p><span class="color" data-color="red"></span><span> </span><small><i class="fa fa-user"></i> Prof Edson Belém - profedsonbelem@gmail.com <i class="fa fa-clock-o"></i> Sábado, Jul 25, 2020</small></p>
</blockquote><blockquote style="border-left-color: green;">
<p><span class="color" data-color="purple"></span><span> </span><small><i class="fa fa-user"></i> Profa Luciana Medeiros - lucianamedeiros.coti@gmail.com <i class="fa fa-clock-o"></i> Sábado, Jul 25, 2020</small></p></blockquote>