How to pass the code (id) by my viwer using thymeleaf and spring mvc for the controller?

-1

My entity:

package local.demo.models;

import java.io.Serializable;

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

@Entity
public class Evento implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long codigo;
private String nome;
private String local;
private String data;
private String horario;

//gets e sets

}

My Controller:

package local.demo.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import local.demo.models.Evento;
import local.demo.repository.EventoRepository;

@Controller
public class EventoController {

@Autowired
private EventoRepository er;

@RequestMapping(value = "/cadastrarEvento", method = RequestMethod.GET)
public String form() {
    return "evento/formEvento";
}

@RequestMapping(value = "/cadastrarEvento", method = RequestMethod.POST)
public String form(Evento evento) {
    er.save(evento);
    return "redirect:/cadastrarEvento";
}

@RequestMapping("/eventos")
public ModelAndView listaEventos() {
    ModelAndView mav = new ModelAndView("index");       
    Iterable<Evento> eventos = er.findAll();
    mav.addObject("eventos", eventos);
    return mav;
}

@RequestMapping("/{codigo}")
public ModelAndView detalhesEvento(@PathVariable("codigo") long codigo) {
    Evento evento = er.findByCodigo(codigo);
    ModelAndView mv = new ModelAndView("evento/detalhesEvento");
    mv.addObject("evento", evento);     
    return mv;
}
}

My repository (interface):

package local.demo.repository;

import org.springframework.data.repository.CrudRepository;
import local.demo.models.Evento;

public interface EventoRepository extends CrudRepository<Evento, String> {
Evento findByCodigo(long codigo);
}

My viwer (index):

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>Cria Eventos Facil</title>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" 
rel="stylesheet"/>
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" 
media="screen,projection"/>

<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<h1>Lista de Eventos</h1>
<h3>
    <a href="/cadastrarEvento">Cadastrar Evento</a>
</h3>
<table class="container">
    <thead>
        <tr>        
            <th>Id</th>  
            <th>Nome</th>
            <th>Local</th>
            <th>Data</th>
            <th>Horario</th>                
        </tr>
    </thead>
    <tbody>
        <tr th:each="evento : ${eventos}">                      
            <!--<td><a th:href="${(#mvc.url('EC#detalhesEvento').arg(0, evento.codigo)).build()}"><span th:text="${evento.nome}"></span></a></td>-->
            <td><span th:text="${evento.codigo}"></span></td>
            <td><span th:text="${evento.nome}"></span></td>
            <td><span th:text="${evento.local}"></span></td>
            <td><span th:text="${evento.data}"></span></td>
            <td><span th:text="${evento.horario}"></span></td>              
        </tr>
    </tbody>    
</table>
<!--Import jQuery before materialize.js-->
<script type="text/javascript"
    src="https://code.jquery.com/jquery-3.2.1.min.js"></script><scripttype="text/javascript" src="js/materialize.min.js"></script>
</body>
</html>

Well, this is where the errors begin, if I leave the event.Code to be shown of this error:

Whitelabel Error Page This application has no explicit mapping for / error, so you are seeing this as a fallback.

Wed Mar 14 10:31:16 BRT 2018 There was an unexpected error (type = Internal Server Error, status = 500). Exception evaluating SpringEL expression: "event.code" (index3: 34)

Now the event is commented. I code and uncomment the line that was commented on in the code which is what I really need:

<tbody>
        <tr th:each="evento : ${eventos}">                      
            <td><a th:href="${(#mvc.url('EC#detalhesEvento').arg(0, evento.codigo)).build()}"><span th:text="${evento.nome}"></span></a></td>
            <!--<td><span th:text="${evento.codigo}"></span></td>-->
            <td><span th:text="${evento.nome}"></span></td>
            <td><span th:text="${evento.local}"></span></td>
            <td><span th:text="${evento.data}"></span></td>
            <td><span th:text="${evento.horario}"></span></td>              
        </tr>
    </tbody>

Give this error here:

Whitelabel Error Page This application has no explicit mapping for / error, so you are seeing this as a fallback.

Wed Mar 14 11:36:04 BRT 2018 There was an unexpected error (type = Internal Server Error, status = 500). Exception evaluating SpringEL expression: "(# mvc.url ('EC #Event details'). Arg (0, event.code)) build ()" (index: 31)

I use XAMPP - MySQL for bd and my code for config. of bd is this:

package local.demo.data;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

@Configuration
@Profile("dev")
public class DataConfiguration {

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/demoteste");
    dataSource.setUsername("root");
    dataSource.setPassword("");
    return dataSource;
}

@Bean
public JpaVendorAdapter jpaVendorAdapter(){
    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.MYSQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(true);
    adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
    adapter.setPrepareConnection(true);
    return adapter;
}
}
Well, now I do not know if the error is relative to the "id", because in my "tbl" type and "bigint" (created automatically) and in my classes as the codes are "long" or if the error it is something else. I know the ideal is to use a SERVICE layer where I can put all the business logic and take this responsibility from the controller, but I prefer a help if possible in this scenario I'm going through!

    
asked by anonymous 14.03.2018 / 15:49

2 answers

1

Rafael, you could remove the comment where you show the "{event.id}" and replace this with <a th:href="${(#mvc.url('EC#detalhesEvento').arg(0, evento.codigo)).build()}"> so: <a th:href="@{/seuContexto{id}(id = ${evento.id}) }"></a>

    
14.03.2018 / 17:18
0

Rafael, the error you report

  

Console error: EL1008E: Property or field 'code' can not be found   on object of type 'local.demo.models.Event' - maybe not public? Error   Whitelabel Error Page This application has no explicit mapping   for / error, you are seeing this as a fallback. Tue Mar 14 13:47:42   BRT 2018 There was an unexpected error (type = Internal Server Error,   status = 500). Exception evaluating SpringEL expression: "evento.codigo"   (index: 33)

is due to the lack of getter and setter of the codigo field of your event class.

Enter these getter and setter that will work.

    
11.05.2018 / 00:46