0
Hello guys I’m new to Spring Boot and I’m having difficulty in some things related to Spring + Bootstrap I have an application that I put http://localhost:8082/functionCast it works normal, the page comes all as I did in bootstrap but when it put http://localhost:8082/functionCast/{id} or sudo que coloco depois da segunda barra ele mostra a pagina toda desformatada com erro 404 I’ve checked everything and can not solve who can help me thank
Config
package com.farmacia;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/img/**", "/css/**", "/js/**", "/scss/**", "/vendor/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.csrf().disable().authorizeRequests()
.antMatchers("/login","/error","/funcionarioCadastrar").permitAll()
/*.antMatchers("/funcionarioCadastrar","/funcionarioExcluir","/medicamentoExcluir" ,"/clienteExcluir"
).hasRole("ADMIN")*/
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
public AuthenticationManager customAuthenticationManager() throws Exception{
return authenticationManager();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index").setViewName("index");
}
}
Main
package com.farmacia;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class FarmaciaxApplication extends SpringBootServletInitializer{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FarmaciaxApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(FarmaciaxApplication.class, args);
}
}
Controller
package com.farmacia.web;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.farmacia.model.User;
import com.farmacia.repository.UserRepository;
import com.farmacia.service.SecurityService;
import com.farmacia.service.UserService;
import com.farmacia.validator.UserValidator;
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@Autowired
private SecurityService securityService;
@Autowired
private UserValidator userValidater;
// Método logar no sistema
@GetMapping({ "/", "/login" })
public String login(Model model, String error, String logout) {
if (error != null) {
model.addAttribute("message", "Login e/ou senha invalidos");
}else {
model.addAttribute("message", "Login realizado com sucesso,Bem vindo!");
}
if (logout != null) {
model.addAttribute("message", "Logout realizado com sucesso!");
}
System.out.println(error);
return "login";
}
// Buscar Funcionarios
@GetMapping("/funcionarioBuscar")
public ModelAndView listar(ModelMap model) {
model.addAttribute("user", userRepository.findAll());
return new ModelAndView(" funcionarioBuscar", model);
}
// pré cadastra
@GetMapping("/funcionarioCadastrar")
public String funcionarioCadastrar(@ModelAttribute("user") User user) {
return "/funcionarioCadastrar";
}
// Cadastrar
@PostMapping("/funcionarioCadastrar")
public String salvar(@Valid @ModelAttribute("user") User user, BindingResult result, RedirectAttributes attr) {
if (result.hasErrors()) {
return "/funcionarioCadastrar";
}
userService.save(user);
attr.addFlashAttribute("message", "Funcionario salvo com sucesso.");
return "redirect:/funcionarioCadastrar";
}
properties
server.port:8082
spring.datasource.url=jdbc:mysql://localhost:3306/farmacia?useTimezone=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
HTML
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Farmacia XYZ</title>
<link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet">
<link href="css/sb-admin.css" rel="stylesheet">
</head>
<body id="page-top">
<nav class="navbar navbar-expand navbar-dark bg-dark static-top">
<a class="navbar-brand mr-1" th:href="@{index}">Farmacia XYZ</a>
<button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" >
<i class="fas fa-bars"></i>
</button>
<!-- Navbar pesquisar -->
<form class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0">
<div class="input-group">
<div class="input-group-append">
</div>
</div>
</form>
<!-- Navbar -->
<ul class="navbar-nav ml-auto ml-md-0">
<li class="visible-xs">
<form th:action="@{/logout}" method="post">
<button type="submit" class="log2 btn btn-default text-white" ><i class="fas fa-sign-out-alt"></i>Sair</button>
</form>
</li>
</ul>
</nav>
<div id="wrapper">
<!-- Sidebar -->
<ul class="sidebar navbar-nav">
<li class="nav-item">
<a class="nav-link" href="index.html">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span>
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="pagesDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-fw fa-folder"></i>
<span>Medicamentos</span>
</a>
<div class="dropdown-menu" aria-labelledby="pagesDropdown">
<h6 class="dropdown-header">Menu Medicamentos</h6>
<a class="dropdown-item" th:href="@{/medicamentoCadastrar}">Cadastrar</a>
<a class="dropdown-item" th:href="@{/medicamentoBuscar}">Buscar</a>
<a class="dropdown-item" th:href="@{/medicamentoAlterar}">Alterar</a>
<a class="dropdown-item" th:href="@{/medicamentoExcluir}">Deletar</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="pagesDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-fw fa-folder"></i>
<span>Funcionarios</span>
</a>
<div class="dropdown-menu" aria-labelledby="pagesDropdown">
<h6 class="dropdown-header">Menu Funcionarios</h6>
<a class="dropdown-item" th:href="@{/funcionarioCadastrar}">Cadastrar</a>
<a class="dropdown-item" th:href="@{/funcionarioBuscar}">Buscar</a>
<a class="dropdown-item" th:href="@{/funcionarioAlterar}">Alterar</a>
<a class="dropdown-item" th:href="@{/funcionarioExcluir}">Deletar</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="pagesDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-fw fa-folder"></i>
<span>Clientes</span>
</a>
<div class="dropdown-menu" aria-labelledby="pagesDropdown">
<h6 class="dropdown-header">Menu Clientes</h6>
<a class="dropdown-item" href="@{/clienteCadastrar}">Cadastrar</a>
<a class="dropdown-item" href="@{/clienteBuscar}">Buscar</a>
<a class="dropdown-item" href="@{/clienteAlterar}">Alterar</a>
<a class="dropdown-item" href="@{/clienteExcluir}">Deletar</a>
</div>
</li>
</ul>
<div id="content-wrapper">
<div class="container-fluid">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#">Dashboard</a>
</li>
<li class="breadcrumb-item active">Funcionarios</li>
</ol>
<div class="card mb-3">
<div class="card-header">
<i class="fas fa-table"></i>
Funcionarios</div>
<div th:if="${message != null}">
<div class="alert alert-success alert-dismissible fade show" role="alert">
<span th:text="${message}">message</span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<div class="card-body">
<form th:action="@{/cadastrarFuncionario}" th:method="${user.id} == null ? post : put" th:object="${user}">
<div class="form-row">
<input id="id" type="hidden" th:field="*{id}" />
<div class="form-group col-md-6">
<label for="username">Login</label>
<input type="text" class="form-control" id="username" name="username" th:field="*{username}" placeholder="Login de usuário"/>
<div th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></div>
</div>
<div class="form-group col-md-6">
<label for="password">Senha</label>
<input type="password" class="form-control" id="password" name="password" th:field="*{password}" placeholder="Senha"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="name">Nome</label>
<input type="text" class="form-control" id="name" name="name" th:field="*{name}" placeholder="Nome">
</div>
<div class="form-group col-md-6">
<label for="inputCity">Salario</label>
<input type="text" class="form-control" id="salary" name="salary" th:field="*{salary}" placeholder="Ex... 998.00" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress2">CPF</label>
<input maxlength="11" type="text" class="form-control" id="cpf" name="cpf" th:field="*{cpf}" placeholder="CPF"/>
<div th:if="${#fields.hasErrors('cpf')}" th:errors="*{cpf}" class="label label-danger"></div>
</div>
<div class="form-group col-md-6">
<label for="roles">Perfil</label>
<input maxlength="5" type="text" class="form-control" id="roles" name="name" th:field="*{roles}" placeholder="admin , user"/>
<div th:if="${#fields.hasErrors('roles')}" th:errors="*{roles}" class="label label-danger"></div>
<!--
<select th:field="*{roles}" class="form-control" id="roles" >
<option th:text="${roles.name}" th:value="${roles.id}" th:each="roles: ${roles}"></option>
</select>
-->
</div>
</div>
<button type="submit" class="btn btn-primary">Cadastrar</button>
<a th:href="@{/funcionarioCadastrar}" class="btn btn-danger">Cancelar</a>
</form>
</div>
<div class="card-footer small text-muted">Atualizado Hoje 03/05</div>
</div>
</div>
<!-- /.container-fluid --
<!-- Sticky Footer -->
<footer class="sticky-footer">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © Farmacia XYZ 2019</span>
</div>
</div>
</footer>
</div>
</div>
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Deseja realmente sair?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Selecione "Sair" abaixo se você estiver pronto para terminar sua sessão atual.</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancelar</button>
<a class="btn btn-primary">Sair</a>
</div>
</div>
</div>
</div>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/datatables/jquery.dataTables.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.js"></script>
<script src="js/sb-admin.min.js"></script>
<script src="js/demo/datatables-demo.js"></script>
</body>
</html>
I’m not sure I understand the problem, but if you want to access a route like
rota/{id}
, so in your controller you need a@RequestMapping("rota/{id}")
and then use a@PathVariable("id") int id
in the method parameter.– igventurelli
Thank you very much the problem was that same worth!
– Renato Galdino
Cool, I’ll put it in answer, all right? Then you mark it right
– igventurelli