getAttribute causing a ClassCastException why? - servlets

I can't figure out why I am getting this Exception everywhere I look says its because you are trying to cast a String to a ItemRating however from what I see in the code it is of object ItemRating. The error is given in the JSP page.
Servlet:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package my.pack;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author Lee Howon
*/
#WebServlet(name = "ProfileController", urlPatterns = {"/ProfileController"})
public class ProfileController extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserDB users = new UserDB();
String action =request.getParameter("action");
HttpSession session = request.getSession();
itemBean item = new itemBean();
ItemRating rating = new ItemRating(item,"0","false");
UserProfile profile = new UserProfile( users.getUsers().get(0).getUserID());
collection coll = new collection();
String itemCode = request.getParameter("itemCode");
if(session.getAttribute("theUser")==null){
User user = new User();
List<User> userList = users.getUsers();
user.setUserID(userList.get(0).getUserID());
user.setFirstName(userList.get(0).getFirstName());
user.setLastName(userList.get(0).getLastName());
user.setEmail(userList.get(0).getEmail());
user.setAddr(userList.get(0).getAddr());
user.setCity(userList.get(0).getCity());
user.setState(userList.get(0).getState());
user.setPostCode(userList.get(0).getPostCode());
request.setAttribute("theUser", user);
session.setAttribute("theUser", user);
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
else{
if(action.equals("save"))
{
List<itemBean> songs= coll.getItems();
for(int i = 0; i < songs.size(); i++){
if(itemCode.equals(songs.get(i).getItemCode()))
{
item.setItemCode(songs.get(i).getItemCode());
item.setSong(songs.get(i).getSong());
item.setArtist(songs.get(i).getArtist());
item.setCategory(songs.get(i).getCategory());
item.setSongURL(songs.get(i).getSongURL());
item.setRating(songs.get(i).getRating());
item.setDesc(songs.get(i).getDesc());
//request.setAttribute("itemBean", item);
}
}
profile.addItem(rating);
session.setAttribute("currentProfile", rating);
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
else if(action.equals("updateProfile")){
String[] itemList =request.getParameterValues("itemList");
for(String list: itemList){
for(int i=0; i<itemList.length; i++){
if(!coll.getItems().get(i).getItemCode().contains(list)){
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
else {
request.setAttribute("theItem", rating);
getServletContext().getRequestDispatcher("/CatalogController?action=coll.getItems.get(i).getItemCode()").forward(request, response);
}
}
}
}
else if(action.equals("updateRating")){
String[] checkRating= request.getParameterValues("itemList");
String itemRating = request.getParameter("rating");
itemBean currItem = null;
for(String list: checkRating){
for(int i=0; i<coll.getItems().size(); i++){
if(list.equals(coll.getItems().get(i).getItemCode())){
currItem = coll.getItems().get(i);
if(currItem == null){
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
else if(itemRating.equals("")){
currItem.setRating("");
} else if(currItem.getRating().equals(itemRating)){
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}else if(!currItem.getRating().equals(itemRating)){
currItem.setRating(itemRating);
}else{
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
}
}
}
session.setAttribute("currentProfile", itemRating);
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
else if(action.equals("updateFlag")){
}
else if(action.equals("signout")){
}
else{
//getServletContext().getRequestDispatcher("/profile.jsp)").forward(request, response);
}
}
//else{
// getServletContext().getRequestDispatcher("/profile.jsp").forward(request,response);
//}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
JSP Page:
<%--
Document : bookmark
Created on : Feb 11, 2018, 1:41:26 PM
Author : Anastasia
--%>
<%#page import="my.pack.ItemRating"%>
<%#page import="my.pack.itemBean"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%#page import="my.pack.collection" %>
<%#include file="/header.jsp"%>
<%#include file="/user-navigation.jsp"%>
<%#include file="/site-navigation.jsp"%>
<div id="productList"><form action="ProfileController" method="post">
<table>
<%
//get the user bean from the request
***error here*** ItemRating itemRating = (ItemRating) session.getAttribute("currentProfile");
collection coll = (collection) session.getAttribute("itemList");
itemBean itemBean = new itemBean();
//String string = itemRating.getItem().getSong();
%>
<tr>
<th>Song Name</th>
<th>Category</th>
<th> My Rating</th>
<th> Update</th>
</tr>
<% if(session.getAttribute("currentProfile") != null )
for(int row=1; row <=1; row++) { %>
<tr>
<td><%= itemRating.getItem().getSong() %></td>
<td><%= itemRating.getItem().getCategory() %>}</td>
<td><%= itemRating.getItem().getRating() %></td>
<td><form action="ProfileController?action=updateProfile" method="post"><button type="submit" name="RateIt">
Rate</button><button type="submit" name="Update" action="ProfileController?action=itemList">
Update</button></form></td>
</tr>
<% } %>
</table>
</form>
<form action="ProfileController?action=updateProfile" method="post">
<input type="hidden" name="itemList" value="itemCode">
<input type="text" name="OST1" value="<%= itemBean.getRating() %>">
<input type="hidden" name="itemList" value="OST2">
<input type="text" name="OST2" value="<%= itemBean.getRating() %>">
<input type="hidden" name="itemList" value="OST3">
<input type="text" name="OST3" value="<%= itemBean.getRating() %>">
<input type="hidden" name="itemList" value="S1">
<input type="text" name="S1" value="<%= itemBean.getRating() %>">
<input type="hidden" name="itemList" value="S2">
<input type="text" name="S2" value="<%= itemBean.getRating() %>">
<input type="hidden" name="itemList" value="S3">
<input type="text" name="S3 " value="<%= itemBean.getRating() %>">
<button type="submit"> Update </button>
</form
<form action="ProfileController?action=deleteItem" method="POST">
<button type="button"> Delete </button>
</form>
</div>
<%#include file="/footer.jsp" %>

Looked into the code and looks like there is problem. Your flow is going to action "updateRating" where you are saving "currentProfile" named attribute having string value. Whereas in another scenario if your action is "save" then you are saving the correct object as attribute value.
Here is the correct code where you are saving the desired attribute object:
if(action.equals("save"))
{
List<itemBean> songs= coll.getItems();
for(int i = 0; i < songs.size(); i++){
if(itemCode.equals(songs.get(i).getItemCode()))
{
item.setItemCode(songs.get(i).getItemCode());
item.setSong(songs.get(i).getSong());
item.setArtist(songs.get(i).getArtist());
item.setCategory(songs.get(i).getCategory());
item.setSongURL(songs.get(i).getSongURL());
item.setRating(songs.get(i).getRating());
item.setDesc(songs.get(i).getDesc());
//request.setAttribute("itemBean", item);
}
}
profile.addItem(rating);
session.setAttribute("currentProfile", rating);
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
And here is the code where you are saving string value in the attribute which is causing the problem:
else if(action.equals("updateRating")){
String[] checkRating= request.getParameterValues("itemList");
String itemRating = request.getParameter("rating");
itemBean currItem = null;
for(String list: checkRating){
for(int i=0; i<coll.getItems().size(); i++){
if(list.equals(coll.getItems().get(i).getItemCode())){
currItem = coll.getItems().get(i);
if(currItem == null){
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
else if(itemRating.equals("")){
currItem.setRating("");
} else if(currItem.getRating().equals(itemRating)){
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}else if(!currItem.getRating().equals(itemRating)){
currItem.setRating(itemRating);
}else{
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}
}
}
}
session.setAttribute("currentProfile", itemRating);
getServletContext().getRequestDispatcher("/bookmark.jsp").forward(request,response);
}

Related

Etat HTTP 400 - Required String parameter 'color' is not present in spring mvc controller?

First the modal of team Update where Team is an entity in my spring mvc application Then The controller method and the updateTeam method implementation:
Here is the code:
<div class="modal fade" id="update-team-modal_${t.id}" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5>Modification Equipe</h5>
</div>
<div class="modal-body">
<form enctype="multipart/form-data" method="POST"
action="updateTeam" onsubmit="return validateTeamUpdate();">
<div class="form-group">
<input id="id" type="hidden" name="id" class="form-control"
value="${t.id}">
</div>
<div class="form-group">
<label for="name">Nom </label><span class="req">*</span>
<div class="input-group">
<input type="text" name="name" id="name"
class="form-control-large" value="${t.name }" autocomplete="off"
required="required" />
</div>
</div>
<div class="form-group">
<label for="color">Couleur</label><span class="req">*</span> <input
type="text" id="color" name="color" class="form-control demo"
style="width: 200px;"
data-swatches="#fff|#000|#f00|#0f0|#00f|#ff0|#0ff"
required="required" value="${t.color }">
</div>
<div class="form-group">
<label for="validateur">Validateur</label> <span class="req">*
</span> <select class="form-control-small" id="validateur"
name="validateur" required="required">
<option value="${t.validateur.matricule}">${t.validateur.firstName
} ${t.validateur.lastName }</option>
<c:forEach var="u" items="${users}">
<option value="${u.matricule}">${u.firstName}
${u.lastName}</option>
</c:forEach>
</select>
</div>
<div class="modal-footer">
<button class="btn btn-ok" type="submit"
style="background-color: #C6172E; color: white;">
<i class="glyphicon glyphicon-ok"></i>Editer
</button>
<button class="btn"
style="background-color: #5A6B80; color: white;"
data-dismiss="modal" onclick="this.form.reset();">
<i class="glyphicon glyphicon-remove"></i>Annuler
</button>
</div>
</form>
</div>
</div>
</div>
</div>
#RequestMapping(value = "/updateTeam", method = RequestMethod.POST)
public ModelAndView updateTeam(#RequestParam("id") long id,
#RequestParam("name") String name,
#RequestParam("validateur") String validateur,#RequestParam("color")String color) {
Team team = teamService.getById(id);
User validant = null;
if (!validateur.equals("null"))
validant = userService.getByMatricule(validateur);
team.setName(name);
team.setColor(color);
team.setValidateur(validant);
teamService.updateTeam(team);
return new ModelAndView(new RedirectView("gestionEquipes"));
}
#Override
public void updateTeam(Team t) {
teamRepository.saveAndFlush(t);
}
Bad Request 400
Etat HTTP 400 - Required String parameter 'color' is not present in spring mvc controller? La requête envoyée par le client était syntaxiquement incorrecte.
Can someone give me an idea how to solve this problem?
package tn.softMaint.MiniPortail.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.google.gson.annotations.Expose;
#Entity
#Table(name = "teams")
/**
*
* #author ajlassi
* Classe d'entité des équipes
* Les attributs avec l'annotation #Expose seront exposés à GSON
*/
public class Team implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "team_id")
#Expose
private long id;
#Expose
#Column(unique = true)
#NotEmpty
private String name,color;
#Expose
private boolean isActif;
#ManyToOne(optional = false,fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#NotNull
private User validateur ;
#ManyToMany(fetch=FetchType.EAGER,mappedBy = "teams")
private List<User> members = new ArrayList<User>();
public Team() {
super();
}
public Team(String name, String color) {
super();
this.name = name;
this.color = color;
setIsActif(true);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean getIsActif() {
return isActif;
}
public void setIsActif(boolean isActif) {
this.isActif = isActif;
}
public User getValidateur() {
return validateur;
}
public void setValidateur(User validateur) {
this.validateur = validateur;
}
public List<User> getMembers() {
return members;
}
public void setMembers(List<User> members) {
this.members = members;
}
#Override
public String toString() {
return "Team [id=" + id + ", name=" + name + ", color=" + color
+ ", isActif=" + isActif + ", validateur=" + validateur
+ ", members=" + members + "]";
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Team other = (Team) obj;
if (id != other.id)
return false;
return true;
}
}
#RequestMapping(value = "/addTeam", method = RequestMethod.POST)
public ModelAndView addTeam(#RequestParam("name") String name,
#RequestParam("color") String color,
#RequestParam("validateur") String validateur,
RedirectAttributes redirectAttributes) {
User validant = null;
if (!validateur.equals("null"))
validant = userService.getByMatricule(validateur);
List<Team>teams=teamService.getAll();
boolean uniqueName=true;
boolean uniqueColor=true;
for (Team team : teams){
if (name.toLowerCase().equals(team.getName().toLowerCase()))
uniqueName = false;
if(color.equals(team.getColor()))
uniqueColor=false;
}
if (uniqueName == false)
redirectAttributes.addFlashAttribute("flashMessageErrorName", "error");
else if(uniqueColor==false)
redirectAttributes.addFlashAttribute("flashMessageErrorColor", "error");
else if((uniqueName==false)&&(uniqueColor==false))
redirectAttributes.addFlashAttribute("flashMessageError", "error");
else{
Team team = new Team(name, color);
team.setValidateur(validant);
boolean test = teamService.addTeam(team);
if (test == true)
redirectAttributes.addFlashAttribute("flashMessageAdd","success");
}
return new ModelAndView(new RedirectView("gestionEquipes"));
}

Spring MVC + Spring Data JPA when the parent is updating, child was delete

When i run app in console, result is correct. Parent is updating, child not delete.
app.java
public class app {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:app-context-annotation.xml");
ctx.refresh();
ClientService clientService = ctx.getBean("jpaClientService", ClientService.class);
UserService userService = ctx.getBean("jpaUserService", UserService.class);
CustomerService customerService = ctx.getBean("jpaCustomerService", CustomerService.class);
TroubleService troubleService = ctx.getBean("jpaTroubleService", TroubleService.class);
Client newClient = clientService.findOne(8l);
String newClientName = "IP 8";
newClient.setClient(newClientName);
clientService.saveClient(newClient);
clientList("Find all:", clientService.findAll());
System.out.println(client.getUserList());*/
}
private static void clientList (String message, List<Client> clientList) {
System.out.println(message);
for (Client client : clientList) {
System.out.println(client);
}
}
private static void userList (String message, List<User> userList) {
System.out.println(message);
for (User user : userList) {
System.out.println(user);
}
}
private static void troubleList (String message, List<Trouble> troubleList) {
System.out.println(message);
for (Trouble trouble : troubleList) {
System.out.println(trouble);
}
}
}
But, when i using MVC, when the parent is updating all childs was delete from all tables.
edit.jspx
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:spring="http://www.springframework.org/tags"
xmlns:form="http://www.springframework.org/tags/form"
xmlns="http://www.w3.org/1999/xhtml" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8"/>
<jsp:output omit-xml-declaration="yes"/>
<spring:message code="label_client_info" var="labelClientInfo"/>
<spring:message code="label_client_client" var="labelClient"/>
<spring:message code="label_client_id" var="labelId"/>
<spring:message code="label_client_inn" var="labelInn"/>
<spring:message code="label_client_specific" var="labelClientSpecific"/>
<spring:message code="label_client_address" var="labelClientAddress"/>
<spring:message code="label_client_phone" var="labelClientPhone"/>
<spring:message code="label_client_update" var="labelClientUpdate"/>
<spring:message code="label_client_new" var="labelClientNew"/>
<spring:eval expression="client.id == null ? labelClientNew:labelClientUpdate" var="formTitle"/>
<html>
<head><title>${formTitle}</title></head>
<body>
<h1>${formTitle}</h1>
<div id="contactUpdate">
<form:form modelAttribute="client" id="clientUpdateForm" method="post">
<c:if test="${not empty message}">
<div id="message" class="${message.type}">"${message.message}"</div>
</c:if>
<form:label path="client">
${labelClient}
</form:label>
<form:input path="client"/>
<div>
<form:errors path="client" cssClass="error"/>
</div>
<form:label path="inn">
${labelInn}
</form:label>
<form:input path="inn"/>
<div>
<form:errors path="inn" cssClass="error"/>
</div>
<form:label path="address">
${labelClientAddress}
</form:label>
<form:input path="address"/>
<div>
<form:errors path="address" cssClass="error"/>
</div>
<form:label path="phone">
${labelClientPhone}
</form:label>
<form:input path="phone"/>
<div>
<form:errors path="phone" cssClass="error"/>
</div>
<form:label path="clientSpecific">
${labelClientSpecific}
</form:label>
<form:select path="clientSpecific">
<form:options items="${clientSpecific}"/>
</form:select>
<form:hidden path="version"/>
<br/>
<button type="submit">Save</button>
<button type="reset">Reset</button>
</form:form>
</div>
</body>
</html>
</jsp:root>
ClientController
#RequestMapping("/clients")
#Controller
public class ClientController {
private Log log = LogFactory.getLog(ClientController.class);
private ClientService clientService;
private MessageSource messageSource;
#RequestMapping(method = RequestMethod.GET)
public String list (Model uiModel) {
log.info("Listing clients");
List<Client> clients = clientService.findAll();
uiModel.addAttribute("clients", clients);
log.info("No. of Clients: " + clients.size());
for (Client client : clients) {
System.out.println(client);
}
return "clients/list";
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String show(#PathVariable("id") Long id, Model uiModel){
Client client = clientService.findOne(id);
uiModel.addAttribute("client", client);
uiModel.addAttribute("users", client.getUserList());
return "clients/show";
}
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
public String update(Client client, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale){
log.info("Updating client:");
if(bindingResult.hasErrors()){
uiModel.addAttribute("message", new Message("error", messageSource.getMessage("client_save_fail", new Object[]{}, locale)));
uiModel.addAttribute("client", client);
return "clients/update";
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("client_save_success", new Object[]{}, locale)));
clientService.saveClient(client);
return "redirect:/clients/"+ UrlUtil.encodeUrlPathSegment(client.getId().toString(), httpServletRequest);
}
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
public String updateForm(#PathVariable("id") Long id, Model uiModel){
uiModel.addAttribute("client", clientService.findOne(id));
return "clients/update";
}
#RequestMapping(params = "form", method = RequestMethod.POST)
public String create(Client client, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale){
log.info("Creating Client:");
if(bindingResult.hasErrors()){
uiModel.addAttribute("message", new Message("error", messageSource.getMessage("client_create_fail", new Object[]{}, locale)));
uiModel.addAttribute("client", client);
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("client_create_success", new Object[]{}, locale)));
clientService.saveClient(client);
log.info("Client ID: " + client.getId() + "was created success");
return "redirect:/clients/" + UrlUtil.encodeUrlPathSegment(client.getId().toString(), httpServletRequest);
}
#RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(Model uiModel){
Client client = new Client();
uiModel.addAttribute(client);
return "clients/create";
}
#Autowired
public void setClientService(#Qualifier("jpaClientService") ClientService clientService){
this.clientService = clientService;
}
#Autowired
public void setMessageSource(MessageSource messageSource){
this.messageSource = messageSource;
}
}
What am i doing wrong?
app-context == webapp-context
Solved. Deleted "orphanremoval=true" from entities.

Multiple select in thymeleaf + hibernate + spring boot

Hello guys I'm using thymeleaf 3 with spring boot and spring data jpa. But here is the problem. When I try to save I get this error from Hibernate:
Hibernate: insert into consulta (medico_id) values (?)
Hibernate: insert into consulta_pacientes (consulta_id, pacientes_id) values (?, ?)
2016-12-12 16:06:53.963 WARN 11912 --- [nio-9393-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState: HY000
2016-12-12 16:06:53.963 ERROR 11912 --- [nio-9393-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'pct_id' doesn't have a default value
2016-12-12 16:06:53.965 INFO 11912 --- [nio-9393-exec-9] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2016-12-12 16:06:53.976 ERROR 11912 --- [nio-9393-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibe
rnate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'pct_id' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526) ~[mysql-connector-java-5.1.39.jar:5.1.39]
I already tried to use converter but didn't workout properly. Tried to look in this posts* ...but didn't solve either.
*1 http://forum.thymeleaf.org/th-selected-not-working-on-lt-select-gt-lt-option-gt-td4029201.html
*2
thymeleaf multiple selected on edit
Any tips? I'm kind of lost right now.
cadastro.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
...
<form action="#" th:action="#{salvar}" th:object="${consulta}" method="POST">
<div class="form-inline">
<label for="select-medico-consulta" class="form-group">Medico</label>
<select th:field="*{medico.id}" id="select-medico-consulta" >
<div>
<option th:each="medicoEntry : ${medicos}"
th:value="${medicoEntry.id}"
th:text="${medicoEntry.nome}"></option>
</div>
</select>
<div class="form-group">
<label id="paciente-label" for="select-paciente" > Paciente</label>
<select th:field="*{pacientes}" id="select-paciente" size="5" multiple="multiple" >
<div>
<option th:each="pacienteEntry : ${listaPacientes}"
th:field="*{pacientes}"
th:value="${pacienteEntry.id}"
th:text="${pacienteEntry.nome}"></option>
</div>
</select>
</div>
</div>
<div class="form-group">
<label for="comment">Consulta</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<button type="submit" class="btn btn-default">Salvar</button>
</form>
</div>
...
consultaController.java
package
and imports...
#Controller
#RequestMapping("/medclin")
public class ConsultaController {
#Autowired
private ConsultaDao consultadao;
#Autowired
private MedicoDao medicoDao;
#Autowired
private PacienteDao pacienteDao;
#RequestMapping("/consulta")
public ModelAndView Consulta() {
ModelAndView modelAndView = new ModelAndView("consulta/consulta");
ArrayList<Medico> medicos = (ArrayList<Medico>) medicoDao.findAll();
ArrayList<Paciente> pacientes = (ArrayList<Paciente>) pacienteDao.findAll();
modelAndView.addObject("medicos", medicos);
modelAndView.addObject("listaPacientes", pacientes);
modelAndView.addObject("consulta", new Consulta());
return modelAndView;
}
#RequestMapping(value = "/salvar", method = RequestMethod.POST)
public String salvar(#ModelAttribute Consulta consulta) {
consultadao.save(consulta);
return "redirect:medclin/home";
}
}
consultaDao.java
package br.com.medclin.boot.daos;
import java.io.Serializable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import br.com.medclin.boot.models.Consulta;
#Repository
public interface ConsultaDao extends CrudRepository<Consulta , Integer>
{
}
EDIT:
as asked by #bphilipnyc
Paciente.java
#Entity
public class Paciente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String nome;
private Calendar dataNascimento;
private String endereco;
#NotNull
private String cpf;
#ManyToOne
private Plano planoDeSaude;
public Paciente(String nome, Calendar dataNascimento, String endereco, String cpf, Plano plano) {
super();
this.nome = nome;
this.dataNascimento = dataNascimento;
this.endereco = endereco;
this.cpf = cpf;
this.planoDeSaude = plano;
}
public Paciente(String nome, Calendar dataNascimento, String endereco, String cpf) {
super();
this.nome = nome;
this.dataNascimento = dataNascimento;
this.endereco = endereco;
this.cpf = cpf;
}
public Paciente(String pctCpf) {
this.cpf = pctCpf;
}
public Paciente() {
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Calendar getDataNascimento() {
return this.dataNascimento;
}
public void setDataNascimento(Calendar dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getEndereco() {
return this.endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCpf() {
return this.cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Plano getPlanoDeSaude() {
return planoDeSaude;
}
public void setPlanoDeSaude(Plano planoDeSaude) {
this.planoDeSaude = planoDeSaude;
}
public boolean equals(Paciente pct) {
if (this.id == pct.id)
return true;
else
return false;
}
#Override
public int hashCode() {
return super.hashCode();
}
#Override
public String toString() {
return "Paciente [id=" + id + ", nome=" + nome + ", dataNascimento=" + dataNascimento + ", endereco=" + endereco
+ ", cpf=" + cpf + ", planoDeSaude=" + planoDeSaude + "]";
}
}
The problem was solved. It seems that if you change your hibernate mapping, you must recreate the database. I did that and the problem was solved.

springboot + thymeelaf form handling with select and object

Hello there,
I'm facing a problem - for several days now- that is: I need to save a form with a select/option that contains a reference to another class...but when the controller tries to save it fails. The console shows me nothing...any tips?
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Dec 11 17:00:10 BRST 2016
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='consulta'. Error count: 1
The form cadastro.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<div th:replace="includes/header :: menu"></div>
<div id="consu" class="container">
<form action="#" th:action="#{salvar}" th:object="${consulta}" method="POST">
<div class="form-inline">
<label for="select-medico-consulta" class="form-group">Medico</label>
<select id="select-medico-consulta" th:field="*{medico}">
<div>
<option th:each="medico : ${medicos}" th:value="${medico}"
th:text="${medico.nome}" ></option>
</div>
</select>
<div class="form-group">
<label id="paciente-label" for="select-paciente-consulta" > Paciente</label>
</div>
</div>
<div class="form-group">
<label for="comment">Consulta</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<div class="checkbox">
<label>
<input type="checkbox"/> Internado
</label>
</div>
<button type="submit" class="btn btn-default">Salvar</button>
</form>
</div>
<div th:fragment="footer">
<p class="rodape">
<img class="img-responsive" src="/img/logo.jpg"
th:src="#{/img/logo.jpg}" alt="error" />
</p>
</div>
</body>
</html>
ConsultaController
#Controller
#RequestMapping("/medclin")
public class ConsultaController {
#Autowired
private ConsultaDao consultadao;
#Autowired
private MedicoDao medicoDao;
#Autowired
private PacienteDao pacienteDao;
#RequestMapping("/consulta")
public ModelAndView Consulta() {
ModelAndView modelAndView = new ModelAndView("consulta/consulta");
ArrayList<Medico> medicos = (ArrayList<Medico>) medicoDao.findAll();
ArrayList<Paciente> pacientes = (ArrayList<Paciente>) pacienteDao.findAll();
modelAndView.addObject("medicos", medicos);
modelAndView.addObject("pacientes", pacientes);
modelAndView.addObject("consulta", new Consulta());
return modelAndView;
}
#RequestMapping(value = "/salvar", method = RequestMethod.POST)
public String salvar(#ModelAttribute Consulta consulta) {
consultadao.save(consulta);
return "redirect:medclin/home";
}
}
the Model, consulta.java
#Entity
public class Consulta {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#ManyToOne
private Medico medico;
#ManyToMany
#JoinTable(name = "CONSULTA_PACIENTES")
private List<Paciente> pacientes = new ArrayList<>();
#ManyToMany
#JoinTable(name = "CONSULTA_RECEITA")
private List<Receita> receita = new ArrayList<>();
public Consulta(Medico med, List<Paciente> paciente) {
this.medico = med;
this.pacientes = paciente;
}
public Consulta() {
}
public Consulta(Medico medico2) {
this.medico = medico2;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Paciente> getPct() {
return pacientes;
}
public void setPct(List<Paciente> pct) {
this.pacientes = pct;
}
public Medico getMedico() {
return medico;
}
public void setMedico(Medico medico) {
this.medico = medico;
}
public List<Receita> getReceita() {
return receita;
}
public void setReceita(List<Receita> receita) {
this.receita = receita;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((medico == null) ? 0 : medico.hashCode());
result = prime * result + ((pacientes == null) ? 0 : pacientes.hashCode());
result = prime * result + ((receita == null) ? 0 : receita.hashCode());
return result;
}
//TODO corrigir esse erro
public boolean equals(Consulta cons) {
if (this.id == cons.getId())
return true;
else
return false;
}
#Override
public String toString() {
return "Consulta [id=" + id + ", medico=" + medico + ", pacientes=" + pacientes + ", receita=" + receita + "]";
}
}
Try
<select id="select-medico-consulta" th:field="*{medico.id}">
<option th:each="medicoEntry : ${medicos}" th:value="${medicoEntry.id}"
th:text="${medicoEntry.nome}" ></option>
</select>

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name

I'm getting the following error when I try to access a Spring MVC form I created:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'roomSelection' available as request attribute
Here's the controller:
#Controller
#RequestMapping("/welcome")
public class RoomSelectionListController {
final private static String WELCOME_VIEW = "welcome";
final private static String SUCCESS_VIEW = "chatroom";
// Value will be injected.
private ChatRoomRegistryService chatRoomRegistryService = null;
private RoomSelectionValidator roomSelectionValidator = null;
private static Logger logger = Logger.getLogger(RoomSelectionListController.class);
public ChatRoomRegistryService getChatRoomRegistryService() {
return chatRoomRegistryService;
}
#Autowired
public void setChatRoomRegistryService(ChatRoomRegistryService chatRoomRegistryService) {
this.chatRoomRegistryService = chatRoomRegistryService;
}
#Autowired
public RoomSelectionListController(RoomSelectionValidator roomSelectionValidator) {
this.roomSelectionValidator = roomSelectionValidator;
}
#ModelAttribute("roomSelection")
protected RoomSelection getRoomSelection() {
logger.debug("Creating a RoomSelection instance");
return new RoomSelection();
}
#ModelAttribute("chatRoomList")
protected List<ChatRoom> populateChatRoomList(HttpServletRequest request) throws Exception{
logger.debug("Creating a chatRoomList");
User user = (User) request.getSession().getAttribute("userLoggedIn");
List<ChatRoom> chatRoomsForUser = chatRoomRegistryService.getChatRoomsForUser(user);
return chatRoomsForUser;
}
#RequestMapping(method = RequestMethod.POST)
protected String processSubmit(#ModelAttribute("roomSelection") RoomSelection roomSelection, BindingResult result, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
roomSelectionValidator.validate(roomSelection, result);
if (result.hasErrors()) {
return WELCOME_VIEW;
} else {
model.addAttribute("chatroom", roomSelection.getChatRoom());
User user = (User) request.getSession().getAttribute("userLoggedIn");
model.addAttribute("userLoggedIn", user);
return SUCCESS_VIEW;
}
}
#RequestMapping(method = RequestMethod.GET)
protected String initForm(ModelMap model) throws Exception {
logger.debug("Inside RoomSelectionListController.initForm()");
RoomSelection roomSelection = new RoomSelection();
model.addAttribute("roomSelection", roomSelection);
return WELCOME_VIEW;
}
}
And here's my form section of JSP:
<form:form id="joinForm" modelAttribute="roomSelection" method="POST">
<table>
<legend><spring:message code="welcome.chatroom.list.lbl" /></legend>
<tr>
<td>
<form:select id="selectChatRoomList" path="chatRoomId" size="7" cssClass="chatRoomList">
<form:options items="${chatRoomList}" itemValue="chatRoomId"
itemLabel="chatRoomName" />
</form:select>
</td>
</tr>
<tr>
<td><form:errors path="chatRoomId" cssClass="advchatError" /></td>
</tr>
<tr>
<td>
<a id="submitJoinChatRoom" href="javascript:void(0)" class="green-button" onclick="$('#joinForm').submit();">
<span class="green-button-outer">
<span class="green-button-inner">
<div class="joinRoomButtonWidth"><spring:message code="welcome.joinchat.lbl" /></div>
</span>
</span>
</a>
</td>
</tr>
</table>
</form:form>
This seems to be a common beginner issue but I can't seem to figure out what I'm doing wrong.
Any ideas?
Thanks,
Steve
#SteveN
I just took your code and made it simple (meaning removed those service dependencies and had just a get method alone to figure out the issue). It works like charm. May be you can also make your code simple and then keep adding things once you have a working thing in place. Here is my code
Controller
#Controller
#RequestMapping("/welcome")
public class RoomSelectionListController {
final private static String WELCOME_VIEW = "welcome";
#RequestMapping(method = RequestMethod.GET)
protected String initForm(ModelMap model) throws Exception {
RoomSelection roomSelection = new RoomSelection();
roomSelection.setRoomName("MyRoom");
model.addAttribute("roomSelection", roomSelection);
return WELCOME_VIEW;
}
}
RoomSelection bean
public class RoomSelection {
private String roomName;
public void setRoomName(String roomName) {
this.roomName = roomName;
}
public String getRoomName() {
return roomName;
}
}
welcome.jsp
<form:form id="joinForm" modelAttribute="roomSelection" method="POST">
<table>
<tr>
<td>Room Name : </td>
<td>
<form:input path="roomName"/>
</td>
</tr>
</table>
</form:form>
My Output
The only place which i have a suspect in your code is in your post method, when the validation fails you are setting the model view as WELCOME_VIEW, i wonder whether during this time you #ModelAttribute will be called and will it add the roomSelection attribute or not. Again its a guess.

Resources