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

Asked

Viewed 1,595 times

0

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>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>
</html>

Well, this is where the errors start, if I leave the event.code to be shown from 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: "evento.codigo" (index3:34)

Now I comment on the event.code and disconcerting 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 that mistake 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#detailsEvento'). Arg(0, event.codigo)). build()" (index:31)

I use XAMPP - Mysql for bd and my code for config. de 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 don’t know if the error is relative to the "id", because in my "tbl" the type and "bigint" (created automatically) and in my classes as the codes are "long" or if the error is in something else. I know that the ideal is to use a SERVICE layer where I well put all the business logic and take this responsibility from the "controller", but I prefer a help if possible in this scenario that I am going through!

3 answers

1


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

  • Yes I will try, but instead of being "id" it can be the code, like: <a th:href="@{/seuContext{code}(code = ${event.code}) }"></a>???

  • Yes. I put "id" because they usually use it to reference the key. But since you referenced it as "code", there are no problems.

  • Console error: EL1008E: Property or field 'code' cannot be found on Object of type 'local.demo.models.Event' - Maybe not public? Web error: Whitelabel Error Page This application has no Explicit Mapping for /error, so you are Seeing this as a fallback. Wed 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)

  • the getters/setters of the code were created, right? Show me your view, as it looked after the change.

  • It looks like this: <tr th:each="event : ${events}"> <td><a th:href="@{/detailsEvento{code}(code = ${event.code})}"></a></td> <td><th:text="${event.name}"></span></td>&#Xa span; <td><th:text="${event.place}"></span></td> <td><span th:text="${event.data}"></span></td> <td><span th:text="${event.horario}"></span></td> </tr>

  • Fix there: <a th:href="@{/detalhesEvento/{codigo}(codigo = ${evento.codigo})}"></a>

  • Same mistake! I don’t know what else to do, I’ve been copying the code exactly like the course I’m doing.

Show 2 more comments

0

Rafael, the error you report

Console error: EL1008E: Property or field 'code' cannot be found on Object of type 'local.demo.models.Event' - Maybe not public? Error on the web: Whitelabel Error Page This application has no Explicit Mapping for /error, so you are Seeing this as a fallback. Wed 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 lack of getter and setter country codigo of your event class.

Insert these getter and setter that will work.

  • Well that’s not it Vitor I check it, thanks for the help.

0

Oops, buddy, I managed to solve this problem by changing (@PathVariable("codigo") for (@PathVariable("evento.codigo")

and also change the @RequestMapping("/{codigo}") para @RequestMapping("/{evento.codigo}")

to display the code in the url after clicking the event.

Abs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.