UPDATE:
This is my index.scala.html which displays a dropdown box:
#(helloForm: Form[Hello], dpts: List[Hello])
#import helper._
#main("InteractionService", "newsimulation") {
#form(action = routes.Application.sayHello(), args = 'id -> "helloform") {
<select class="selectpicker" data-size="auto" data-live-search="true" data-container="body" >
#for(dpt <- dpts){
<option value="#dpt.id">#dpt.name</option>
}
</select>
<p class="buttons">
<input type="submit">
<p>
}
}
This is my Hello object:
#Entity
public class Hello extends Model {
private static final long serialVersionUID = 1L;
#Id
#Constraints.Required
#Formats.NonEmpty
public Long id;
#Constraints.Required
public String name;
}
This is my controller:
public static Result sayHello() {
Form<Hello> dptForm = form(Hello.class).bindFromRequest();
DomainPracticeTemplate currentDPT = dptForm.get();
Logger.info("dptForm content = " + dptForm.toString());
}
When hitting the submit button, it returns:
[IllegalStateException: No value]
I need the id or the whole object, how?
Related
I'm using enum for select options in thymeleaf and I can't see them or insert them in the database. There is nothing in the dropdown list.
<div class="form-group">
<label for="roomType">Rooms</label>
<select class="form-select selectpicker show-tick" th:field="*{property.roomType}" id="rooms">
<option value="">Nothing selected</option>
<option th:each="property.roomType : ${T(com.realestate.petfriendly.entity.RoomType).values()}"
th:value="${property.roomType}"
th:text="${property.roomType}">
</option>
</select>
</div>
class
#Enumerated(EnumType.STRING)
#Column(name = "RoomType")
private RoomType roomType;
and enum
public enum RoomType {
GARSONJERA("garsonjera"), JEDNOIPOSOBAN("jednoiposoban"), DVOSOBAN("dvosoban"),
DVOIPOSOBAN("dvoiposoban"), TROSOBAN("trosoban"), TROIPOSOBAN("troiposoban"),
CERVOROSOBAN("cetvorosoban"), CETVOROIPOSOBAN("cetvoroiposoban"), VISESOBAN("visesoban");
private String roomType;
private RoomType(String roomType) {
this.roomType = roomType;
}
public String getRoomType() {
return this.roomType;
}
}
I'm not sure why it doesn't show me anything
that is available for me.
class
#Setter
#Getter
public class Demo {
private RoomType roomType;
}
enum
public enum RoomType {
GARSONJERA("garsonjera"), JEDNOIPOSOBAN("jednoiposoban"), DVOSOBAN("dvosoban"),
DVOIPOSOBAN("dvoiposoban"), TROSOBAN("trosoban"), TROIPOSOBAN("troiposoban"),
CERVOROSOBAN("cetvorosoban"), CETVOROIPOSOBAN("cetvoroiposoban"), VISESOBAN("visesoban");
private final String roomType;
private RoomType(String roomType) {
this.roomType = roomType;
}
public String getRoomType() {
return this.roomType;
}
}
controller:
#Controller
#RequestMapping( "test")
public class TestController {
#GetMapping("demo")
public String demo(Model model){
Demo demo = new Demo();
demo.setRoomType(RoomType.CERVOROSOBAN);
model.addAttribute(demo);
return "test/demo";
}
}
HTML:
<div class="form-group">
<label for="rooms">Rooms</label>
<select class="form-select selectpicker show-tick" th:field="*{demo.roomType}" id="rooms">
<option value="">Nothing selected</option>
<option th:each="value : ${T(com.bluray.boot.business.test.RoomType).values()}"
th:value="${value}"
th:text="${value}">
</option>
</select>
</div>
I use spring-boot 2.3.6.release
I have a cinema reservation system where user can add movies and then they can add date to each movie. It works fine, but when a user adds a date, there is no error, but it saves to the database with movie_id = null.
How can I solve it?
Movie.java
#Data
#Entity
public class Movie {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id")
private Long id;
#Column(unique = true)
private String title;
private String category;
#Column( columnDefinition = "TEXT")
private String description;
private Integer lenght;
private Integer minAge;
#Column(columnDefinition = "TEXT")
private String imageUrl;
#OneToMany(mappedBy = "movie", orphanRemoval = true)
private List<Repertoire> repertoires;
public Movie() {
}
}
Repertoire.java
#Data
#Entity
public class Repertoire {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id")
private Long id;
#DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
private LocalDateTime date;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "movie_id")
private Movie movie;
}
MovieController.java
#Controller
#RequestMapping("/movies")
public class MovieController {
private MovieRepo movieRepo;
private RepertoireRepo repertoireRepo;
#Autowired
public MovieController(MovieRepo movieRepo, RepertoireRepo repertoireRepo) {
this.movieRepo = movieRepo;
this.repertoireRepo = repertoireRepo;
}
#GetMapping("showForm")
public String showStudentForm(Movie movie) {
return "add-movie";
}
#GetMapping("list")
public String getMovies(Model model) {
model.addAttribute("movies", movieRepo.findAll());
return "movieIndex";
}
#PostMapping("add")
public String movies(#Validated Movie movie, BindingResult result, Model model) {
if(result.hasErrors()) {
return "add-movie";
}
movieRepo.save(movie);
return "redirect:/movies/list";
}
#GetMapping("edit/{id}")
public String showUpdateForm(#PathVariable ("id") long id, Model model) {
Movie movie = movieRepo.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Nieprawidłowe ID: " + id));
model.addAttribute("movie", movie);
return "update-movie";
}
#PostMapping("update/{id}")
public String updateMovie(#PathVariable("id") long id, #Validated Movie movie, BindingResult result, Model model) {
if(result.hasErrors()) {
movie.setId(id);
return "update-movie";
}
movieRepo.save(movie);
model.addAttribute("movies", movieRepo.findAll());
return "movieIndex";
}
#GetMapping("delete/{id}")
public String deleteMovie(#PathVariable ("id") long id, Model model) {
List<Repertoire> repertoires = repertoireRepo.findByMovieId(id);
repertoires.forEach(r -> repertoireRepo.deleteById(r.getId()));
Movie movie = movieRepo.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Nieprawidłowe ID : " + id));
movieRepo.delete(movie);
model.addAttribute("movies", movieRepo.findAll());
return "movieIndex";
}
// HERE'S WHERE I ADD THE TIME:
#GetMapping("/admin/{movieName}/newRepertoire")
public String showRepertoireForm(Model model, #PathVariable ("movieName") String movieName) {
Movie movieRepertoire = movieRepo.findByTitle(movieName);
model.addAttribute("movieRepertoire", movieRepertoire);
model.addAttribute("repertoire", new Repertoire());
return "repertoire";
}
#PostMapping("/admin/newRepertoire")
#Transactional
public String addRepertoire(#ModelAttribute ("repertoire") Repertoire repertoire,
#ModelAttribute("movieRepertoire") Movie movie, BindingResult result) {
// if(result.hasErrors()) {
// return "repertoire";
// }
repertoire.setMovie(movieRepo.findByTitle(movie.getTitle()));
repertoireRepo.save(repertoire);
return "redirect:/movies/list";
}
}
RepertoireRepo.java
#Repository
public interface RepertoireRepo extends JpaRepository<Repertoire, Long> {
List<Repertoire> findByMovieId(Long movieId);
}
MovieRepo.java
#Repository
public interface MovieRepo extends JpaRepository<Movie, Long> {
Movie findByTitle(String title);
}
repertoire.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>c</title>
</head>
<body>
<div class="container my-5">
<div class="card">
<div class="card-body">
<div class="col-md-10">
<h1 th:text="${movieRepertoire.title}"> MovieName</h1>
<form action="#" th:action="#{/movies/admin/newRepertoire}" th:object="${repertoire}" method="post">
<div class="row">
<div class="form-group col-md-8">
<label for="date" class="col-form-label">Date</label>
<input type="datetime-local" th:field="*{date}" class="form-control" id="date" value="2021-01-20T13:01">
<span th:if="${#fields.hasErrors('date')}" th:errors="*{date}" class="text-danger"></span>
</div>
<div class="col-md-6">
<input type="submit" class="btn btn-primary" value="Add">
</div>
<div class="form-group col-md-8"></div>
</div>
<!-- <input type = "hidden" th:value="${movieRepertoire}">-->
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Movie structure:
id | category | description | imageurl| lenght| minage| title
-------------------------
36 | Action | Simple desc. | photo.jpg | 137 | 7 | Iron Man |
Repertoire structure:
id | date | movie_id
-------------------------
37 | 2021-01-01 14:00:00 | null |
Both sides of the relationship must be updated and you should cascade save from the parent. Your code:
repertoire.setMovie(movieRepo.findByTitle(movie.getTitle()));
repertoireRepo.save(repertoire);
Should become:
Movie movie = movieRepo.findByTitle(movie.getTitle());
movie.getRepertoires().add(repertoire);
repertoire.setMovie(movie);
session.saveOrUpdate(movie);
In fact really you should add a helper method to Movie that performs both actions to ensure both sides of the relationship are always in sync:
public void addRepertoire(Repertoire repertoire) {
repertoires.add(repertoire);
repertoire.setMovie(this);
}
I have this exception andd i can't find a solution
COntroller :
#RequestMapping(value="/sujet")
public String detail(Model model, HttpServletRequest request, Long idSujet) {
Utilisateur user = (Utilisateur) request.getSession().getAttribute("user");
model.addAttribute("nbrMails", metierUtilisateur.listDesEmailsRecuNonLu(user.getIdUtilisateur()).size());
SujetForum sujet = metierSujetForum.findById(idSujet);
sujet.setMessagesForums(metierSujetForum.getListMessageForum(idSujet));
model.addAttribute("sujet", sujet);
model.addAttribute("messages", metierSujetForum.getListMessageForum(idSujet));
return "/coordinateur/detailSujetForum";
}
this is my Bean definition :
i defined all the getters and setters for all attributes but is till get the same exception
#Entity
public class MessagesForum implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idMessage;
private String message;
private Date dateDepotMessage;
private boolean messageCorrecte;
#ManyToOne
#JoinColumn(name = "idSujet")
private SujetForum sujetForum;
#ManyToOne
#JoinColumn(name = "idUtilisateur")
private Utilisateur utilisateur;
#OneToMany(mappedBy = "messageForum")
private Collection<PieceJointeForum> pieceJointeForums;
public MessagesForum(String message, Date dateDepotMessage, boolean messageCorrecte) {
super();
this.message = message;
this.dateDepotMessage = dateDepotMessage;
this.messageCorrecte = messageCorrecte;
}
public MessagesForum() {
super();
}
public Long getIdMessage() {
return idMessage;
}
public void setIdMessage(Long idMessage) {
this.idMessage = idMessage;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getDateDepotMessage() {
return dateDepotMessage;
}
public void setDateDepotMessage(Date dateDepotMessage) {
this.dateDepotMessage = dateDepotMessage;
}
public boolean isMessageCorrecte() {
return messageCorrecte;
}
public void setMessageCorrecte(boolean messageCorrecte) {
this.messageCorrecte = messageCorrecte;
}
public SujetForum getSujetForum() {
return sujetForum;
}
public void setSujetForum(SujetForum sujetForum) {
this.sujetForum = sujetForum;
}
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
public Collection<PieceJointeForum> getPieceJointeForums() {
return pieceJointeForums;
}
public void setPieceJointeForums(Collection<PieceJointeForum> pieceJointeForums) {
this.pieceJointeForums = pieceJointeForums;
}
}
this is the output of the exception
615: <div class="media-body">
616: <div class="media-text">
617: <h5 class="semibold mt0 mb5 text-accent"></h5>
618: <p class="mb5">${msg.getIdMessage() }.</p>
619: <!-- meta icon -->
620: <p class="mb0">
621: <span class="media-meta"></span> <span class="mr5 ml5 text-muted">*</span> <a href="javascript:void(0);" class="media-meta text-default" data-t
oggle="tooltip" title="" data-original-title="Reply"><i class="ico-reply"></i></a>
Stacktrace:] with root cause
javax.el.MethodNotFoundException: Method not found: class java.lang.String.getIdMessage()
at javax.el.Util.findWrapper(Util.java:352)
at javax.el.Util.findMethod(Util.java:214)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:174)
at org.apache.jasper.el.JasperELResolver.invoke(JasperELResolver.java:139)
at org.apache.el.parser.AstValue.getValue(AstValue.java:173)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:967)
at org.apache.jsp.WEB_002dINF.views.coordinateur.detailSujetForum_jsp._jspx_meth_c_005fforEach_005f0(detailSujetForum_jsp.java:1242)
at org.apache.jsp.WEB_002dINF.views.coordinateur.detailSujetForum_jsp._jspService(detailSujetForum_jsp.java:832)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
<c:forEach items="=${messages }" var="msg">
<div class="media-list media-list-bubble">
<div class="media">
<a href="javascript:void(0);" class="media-object pull-left"> <img src="" class="img-circle" alt="">
</a>
<div class="media-body">
<div class="media-text">
<h5 class="semibold mt0 mb5 text-accent"></h5>
<p class="mb5">${msg.idMessage }.</p>
<!-- meta icon -->
<p class="mb0">
<span class="media-meta"></span> <span class="mr5 ml5 text-muted">*</span> <i class="ico-reply"></i>
</p>
<!--/ meta icon -->
</div>
</div>
</div>
</div>
</c:forEach>
msg in JSP here seems to be coming as String and You are expecting your bean Class type .
After you get the bean also
${msg.getIdMessage() }.
This seems to be issue in your JSP. just try with
${msg.idMessage() }.
send me your jsp and don't call with get method u should call directly with property values. like amit.rk3 said. and where you are using this msg in your jsp
use like this
<c:forEach var="msg" items="${messages}">
I have following entities:
#Entity
#Table(name="APLICACAO")
public class Aplicacao implements Serializable, Entidade {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="CD_APLICACAO")
private Long codigo;
#Column(name="NM_APLICACAO")
#NotNull
private String nome;
#ManyToOne
#JoinColumn(name="CD_GRUPO")
private GrupoAplicacao grupoAplicacao;
....
}
And also:
#Entity
#Table(name = "GRUPO_APLICACAO")
public class GrupoAplicacao implements Serializable, Entidade {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "CD_GRUPO")
private Long codigo;
#Column(name = "NM_GRUPO")
#NotNull
private String nome;
#OneToMany(mappedBy = "grupoAplicacao",fetch=FetchType.EAGER)
private List<Aplicacao> listaAplicacao;
#OneToMany(mappedBy = "grupoAplicacao",fetch=FetchType.EAGER)
private List<GrupoAplicacaoUsuario> listaGrupoAplicacaoUsuario;
....
}
My HTML call controller "aplicacoesCreateController", like code bellow:
<div class="col-xs-12" ng-controller="aplicacoesCreateController">
<form class="form-horizontal form-medium center" role="form" name="form" ng-submit="save()">
<div class="form-group">
<label for="nome" class="col-xs-4 control-label">Nome</label>
<div class="col-xs-8">
<input type="text" class="form-control input-sm" id="nome" placeholder="Nome" required ng-model="aplicacao.nome">
</div>
</div>
<div class="form-group">
<label for="nome" class="col-xs-4 control-label">Nome</label>
<div class="col-xs-8">
<select class="form-control" required ng-model="aplicacao.grupoAplicacao">
<option ng-repeat="grupo in grupos" value="{{ grupo }}">
{{ grupo.nome }}
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-4 col-xs-8">
<button type="submit" class="btn btn-lg btn-size-md">Salvar</button>
</div>
</div>
</form>
</div>
And my Controller JavaScript:
app.controller('aplicacoesCreateController', ['$scope','aplicacoesService','$location','reloadService','gruposService',
function ($scope,aplicacoesService,$location,reloadService,gruposService) {
$scope.grupos = gruposService.list();
$scope.save = function () {
aplicacoesService.create($scope.aplicacao);
reloadService.on('#/aplicacoes');
};
}]);
And Services JavaScript:
app.factory('gruposService', ['$resource', function ($resource) {
return $resource('resources/grupo-aplicacao', {}, {
'list': { method: 'GET', isArray: true }
});
}]);
And other service:
app.factory('aplicacoesService', ['$resource', function ($resource) {
return $resource('resources/aplicacao', {}, {
'list': { method: 'GET', isArray: true },
'create': { method: 'POST' }
});
}]);
When insert aplicacao entity, is show me the following error:
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class br.com.techpeople.grape.entity.GrupoAplicacao] from JSON String; no single-String constructor/factory method (through reference chain: br.com.techpeople.grape.entity.Aplicacao["grupoAplicacao"])
Could you help me with this error?
The error is telling you that you need a constructor method in your GrupoAplicacao class which accepts a string.
#Entity
#Table(name = "GRUPO_APLICACAO")
public class GrupoAplicacao implements Serializable, Entidade {
....
GrupoAplicacao(String stringJSON){
setters;
}
}
Thank you #BoatCode!
I did the following in my constructor:
public GrupoAplicacao(String grupoAplicacaoJSON) {
Gson gson = new Gson();
GrupoAplicacao grupoAplicacao = gson.fromJson(grupoAplicacaoJSON, GrupoAplicacao.class);
this.codigo = grupoAplicacao.getCodigo();
this.nome = grupoAplicacao.getNome();
this.listaAplicacao = grupoAplicacao.getListaAplicacao();
this.listaGrupoAplicacaoUsuario = grupoAplicacao.getListaGrupoAplicacaoUsuario();
}
Add the lib Gson and set the variables of GrupoAplicacao class.
=)
Once the task and the same issue was in scope of:
+limited time, +ee: +jax-rs && +persistence, +gson; I have solved it then as:
#Entity
#XmlRootElement
#Table(name="element")
public class Element implements Serializable {
public Element(String stringJSON){
Gson g = new Gson();
Element a = g.fromJson(stringJSON, this.getClass());
this.setId(a.getId());
this.setProperty(a.getProperty());
}
public Element() {}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
...
}
It's pretty close to Gustavo's Bitencourt solution, with maybe a bit different scope.
It seems that, from javascript, you are sending a string instead of an object. You can try by sending JSON.parse(stringGrupoAplicacao).
That way, on the server side the object should be deserialized automatically with no needs of creating a special constructor.
I am trying to set a predefined value in Shop.email field in a form but it storing every field except one field i.e. email.
Shop.java
package models;
#Entity
public class Shop extends Model {
#Id
#SequenceGenerator(name="shop_gen", sequenceName="shop_id_seq", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="shop_gen")
#Column(name="id")
public Long id;
#Required
public String name;
#Required
public String addressLine1;
public String addressLine2;
public String addressLine3;
#Required
public String city;
#Required
public String town;
#Required
public String phoneNumber;
#ManyToOne
#JoinColumn(name="email",insertable=false, updatable=false,nullable=false)
public Member email;
public static Model.Finder<Long,Shop> find = new Model.Finder(Long.class, Shop.class);
}
ShopController.java
package controllers;
public class ShopController extends Controller {
static Form<Shop> shopForm = Form.form(Shop.class);
public static Result blank() {
String loggedInUserEmail = session("email");
Shop shop = new Shop();
shop.email = Member.get(loggedInUserEmail);
shopForm.fill(shop);
return ok(views.html.shop.create.render(shopForm, loggedInUserEmail));
}
public static Result submit() {
Form<Shop> filledForm = shopForm.bindFromRequest();
if (filledForm.hasErrors()) {
String loggedInUserEmail = session("email");
return badRequest(views.html.shop.create.render(filledForm,
loggedInUserEmail));
} else {
Shop shop = filledForm.get();
Shop.create(shop);
return redirect(routes.ProductController.blank());
}
}
}
createShop.scala.html
#(userForm: Form[models.Shop], user: String)
#import helper._
#import helper.twitterBootstrap._
#main(Html("Create Shop")) {
<fieldset>
<legend>Add a new shop</legend>
<p>To add a shop to this website fill in the form given below.Add as much information about your shop so the customer may know abot your shop more.</p>
#form(action = routes.ShopController.submit(), 'id -> "shopCreationForm", 'class -> "form-horizontal", 'role->"form") {
#inputText(userForm("name"), '_label -> "Shop Name",'class -> "form-control")
#inputText(userForm("addressLine1"), '_label -> "Address Line 1",'class -> "form-control")
#inputText(userForm("addressLine2"), '_label -> "Address Line 2",'class -> "form-control")
#inputText(userForm("addressLine3"), '_label -> "Address Line 3",'class -> "form-control")
#inputText(userForm("city"), '_label -> "City",'class -> "form-control")
#inputText(userForm("town"), '_label -> "Town",'class -> "form-control")
#inputText(userForm("phoneNumber"), '_label -> "Phone",'class -> "form-control")
<div class="form-group">
<label for="exampleInputEmail1">Owner Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="#user" readonly>
</div>
<div class="actions">
<input type="submit" class="btn btn-primary" value="Create">
Cancel
</div>
</fieldset>
}
}
When i am submitting this form it saves every value in database except the value of email field.I am unable to understand what i am doing wrong
Thanks in advance.
The email input field does not include a name attribute. Therefore, your browser can't send data correctly to the server.
You need to either use the form helper to render this input or add the name="email" in your <input> :
<input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="#user" readonly>