Property not found on java.lang.String, For Object array list in custom Tag - spring

I am trying to build a menu at runtime depending on the server call in JSP.
The model that represents the menu is given below:
import java.util.ArrayList;
import java.util.List;
public class MenuItem {
public String menuText;
public List<MenuItem> subMenuItems=new ArrayList<MenuItem>();
public MenuItem(String menuText) {
super();
this.menuText = menuText;
this.subMenuItems = new ArrayList<MenuItem>();
}
public MenuItem(){
}
public MenuItem(String menuText, List<MenuItem> subMenuItems) {
super();
this.menuText = menuText;
this.subMenuItems = subMenuItems;
}
// #Override
// public String toString() {
// // TODO Auto-generated method stub
// StringBuffer buffer = new StringBuffer();
// for (MenuItem menuItem : getSubMenuItems()) {
// buffer.append(menuItem.toString());
// }
// return (" Menu --->" + getMenuText() + buffer.toString());
//
// }
public String getMenuText() {
return menuText;
}
public void setMenuText(String menuText) {
this.menuText = menuText;
}
public List<MenuItem> getSubMenuItems() {
return subMenuItems;
}
public void setSubMenuItems(List<MenuItem> subMenuItems) {
this.subMenuItems = subMenuItems;
}
}
For the above model we pass the sample menu from the controller:
List<MenuItem> menuMainList = new ArrayList<MenuItem>();
List<MenuItem> submenus = new ArrayList<MenuItem>();
MenuItem item1= new MenuItem();
item1.setMenuText("****");
submenus.add(item1);
MenuItem item2 = new MenuItem();
item2.setMenuText("SampleMenu");
item2.setSubMenuItems(submenus);
menuMainList.add(item2);
System.out.println(menuMainList);
model.addAttribute("menuItem", menuMainList);
On the JSP Page we try to do the following:
<c:forEach items="${menuItem}" begin="0" var="menuListItem">
<c:choose>
<c:when test="${empty menuListItem.subMenuItems}">
<div>
<c:out value="${menuListItem.menuText}" />
</div>
</c:when>
<c:otherwise>
<div>
<span><c:out value="${menuListItem.menuText}" /></span>
<div style="width: 150px;">
<cobTags:menuDivItem menuList="${menuListItem.subMenuItems}"></cobTags:menuDivItem>
</div>
</div>
</c:otherwise>
</c:choose>
</c:forEach>
And the custom tag being:
<%# tag language="java" pageEncoding="ISO-8859-1"%>
<%# attribute name="menuList" required="true"%>
<%# taglib tagdir="/WEB-INF/tags" prefix="cobTags"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:forEach items="${menuList}" begin="0" var="menuListItem">
<div>
<cobTags:drawMenuItem menuItem="${menuListItem}"></cobTags:drawMenuItem>
<c:out value="${menuListItem}" />
</div>
</c:forEach>
And
<%# tag language="java" pageEncoding="ISO-8859-1"%>
<%# attribute name="menuItem" type="com.sample.bean.MenuItem"
required="true"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div style="color: red;">
<c:out value="${menuItem.menuText}" />
</div>
When I execute the following code, I am getting the error:
Cannot convert [com.sample.bean.MenuItem#547ca73] of type class
java.lang.String to class com.sample.bean.MenuItem
I am not getting why the model's toString method is getting called when I pass the object to the custom tag.?
Any pointers?

Declaring the type of the argument should fix the problem:
<%# attribute name="menuList" required="true" type="java.util.Collection" %>

Related

The object in the Controller is not filled in when calling the POST method, it gives an error

I am making a Spring MVC application, when I fill out a table in jsp and click the "save" button, the data is not saved, an error is generated: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null];
here is the output I have on the console: Pass_in_trip [key=null, trip=Trip [trip_no=0, comp=Company [id_comp=0, name=null], plane=null, town_from=null, town_to=null, time_out=null, time_in=null, passInTrips=[]], passenger=Passenger [name=null, passengerId=0, passInTrips=[]], place=6f, date=null]
and at the input to the insert method, my object is empty, tell me what I'm doing wrong?
Controller
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value = "insert", method = RequestMethod.GET)
public String insertnewform(Pass_in_trip pass_in_trip, Model uiModel) {
uiModel.addAttribute("trip",service.findallTrip());
uiModel.addAttribute("passenger",service.findallPassenger());
return "/pass_in_trip/insert";
}
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value = "insert", method = RequestMethod.POST)
public String insert(Pass_in_trip pass_in_trip, BindingResult bindingResult, Model uiModel,
HttpServletRequest httprervletrequest, RedirectAttributes redirectatributes) {
System.out.println(pass_in_trip);
if (bindingResult.hasErrors()) {
uiModel.addAttribute("pass_in_trip", pass_in_trip);
return "pass_in_trip/edit";
}
service.save(pass_in_trip);
return "redirect:/pass_in_trip/";
}
Insert.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Pass_in_trip</title>
<style>
form fieldset {
width: 40%;
}
form fieldset label {
display: block;
/*width : 50%;
float :left;*/
}
form fieldset input, form fieldset select, form fieldset textarea {
width: 100%;
}
</style>
</head>
<body>
<h1>Pass_in_trip</h1>
<form method="POST">
<fieldset>
<div>
<label>Flight:</label>
<select name="trip">
<c:forEach var="trip" items="${trip}">
<option value="${trip}" label="№ ${trip.trip_no} ${trip.town_from} ${trip.town_to}"/>
</c:forEach>
</select>
</div>
<div>
<label>Passenger:</label>
<select name="passenger">
<c:forEach var="passenger" items="${passenger}">
<option value="${passenger}" label="${passenger.passengerId} ${passenger.name}">
</c:forEach>
</select>
</div>
<div>
<label>Date: </label>
<input type="datetime" name="date" value="${pass_in_trip.date}">
</div>
<div>
<label>Place:</label>
<input type="text" name="place" value="${pass_in_trip.place}">
</div>
<div>
<input type="submit" value="Save">
</div>
</fieldset>
</form>
</body>
</html>
Pass_in_trip
#Entity
#Table (name="pass_in_trip")
public class Pass_in_trip implements Serializable {
#Override
public String toString() {
return "Pass_in_trip [key=" + key + ", trip=" + trip + ", passenger=" + passenger + ", place=" + place
+ ", date=" + date + "]";
}
#EmbeddedId
private KeysPass_in_trip key;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("tripId")
#JoinColumn(name="trip_no")
Trip trip = new Trip();
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("psgId")
#JoinColumn(name="id_psg")
Passenger passenger = new Passenger();
#Column(name="place")
private String place;
#Column(name="date")
private Timestamp date;
//Getters and setters

Spring MVC + DisplayTag + Checkbox

I have to integrate in a SpringMVC form a set of fields and a List handled by a Display:table .
In the display table I have to view a column of checkboxes where the information about if this is checked or not is passed by the controller. I have to manipulate this checkboxes and pass them to another controller to store that data inside a DB.
I'm simulating this situation creating a SpringMVC controller that set me inside the Model some data :
package it.test.displaytag.controller;
import java.util.ArrayList;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import it.test.displaytag.model.Bean;
import it.test.displaytag.model.Interno;
#org.springframework.stereotype.Controller
public class Controller {
#RequestMapping(value = "index.htm")
public String home(Model model) {
Bean bean = new Bean();
bean.setCognome("Cognome");
bean.setNome("Nome");
ArrayList<Interno> list = new ArrayList<Interno>();
for(int i=0;i<50;i++) {
Interno asd = new Interno();
asd.setIdCheck(i);
if (i%2==0) {
asd.setIsEnabled(Boolean.TRUE);
}
list.add(asd);
}
bean.setInterno(list);
model.addAttribute("displayTagForm", bean);
return "index";
}
}
The JSP is :
<%# taglib prefix="display" uri="http://displaytag.sf.net" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%
org.displaytag.decorator.CheckboxTableDecorator decorator = new org.displaytag.decorator.CheckboxTableDecorator();
decorator.setId("idCheck");
decorator.setFieldName("_chk");
pageContext.setAttribute("checkboxDecorator", decorator);
%>
<html>
<body>
<form:form name="displayTagForm" action="/salva" modelAttribute="displayTagForm" method="POST">
Form di test per testare la paginazione nelle Displaytag.
<br><br>
Nome : <form:input path="nome" />
<br><form:input path = "cognome" />
<br><br>
Tabella
<br><center>
<display:table name="displayTagForm.interno" uid="bean" decorator = "checkboxDecorator"
pagesize="10" >
<display:column property="idCheck" />
<display:column property = "checkbox" />
</display:table>
</center>
</form:form>
</body>
</html>
The JSP is correctly showing the informations inside the fields "nome" and "cognome" but is not showing if the checkbox is selected or not ( passed with a flag isEnabled in the bean ) . I've not understood how to do this trick.
After that, i Have to handle the pagination and the sort of the display:table, because I think that if I write something in that 2 textboxes nome and cognome and I click one of the link to go to another page, I lose the informations that i've written in the textboxes and I lose the information about the value of the checkbox clicked or not.
How can I handle this situation ?

Simple search in Spring MVC

I'm new to Spring MVC, and I'm trying to do a simple search.
Here's my Controller and View. How do I make the search to actually work?
The findTeamByName is already implemented from a interface and the Teams are already populated in memory.
Thank you in advance guys!
#Controller
public class SearchController {
#Autowired
SuperPlayerService sp;
#RequestMapping(value="/search")
public ModelAndView Search(#RequestParam(value = "searchTerm", required = false)
String pSearchTerm, HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
}
JSP:
<%# page contentType="text/html" pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<t:MasterTag>
<jsp:attribute name="pageTitle"><c:out value="Search"/></jsp:attribute>
<jsp:attribute name="currentMenuName"><c:out value="Search"/></jsp:attribute>
<jsp:body>
<div class="row">
<div class="small-3 columns">
<input type="text" id="txt" name="searchString">
</div>
<div class="small-5 columns end">
<button id="button-id" type="submit">Search Teams</button>
</div>
</div>
<div class="row">
<div>
${searchTerm}
</div>
</div>
you can return your values i.e in a ModelAndView
#RequestMapping(value="/search/{searchTerm}")
public ModelAndView Search(#PathVariable("searchTerm") String pSearchTerm) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
This field can be accessed in your search.jsp by ${searchTerm}
EDIT:
if you want so search like: search?searchTerm=java then you can do it with:
#RequestMapping(value="/search")
public ModelAndView Search(#RequestParam(value = "searchTerm", required = false) String pSearchTerm, HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
Spring MVC Controller method can accept a wide range of arguments and one of them is org.springframework.ui.Model.
You can add values to the Model which will become available in your JSP at requestScope.
In your case, your Java code would look like this
#RequestMapping(value = "/search")
public String Search(#RequestParam("searchString") String searchString, Model model) {
if(searchString != null){
Object searchResult = sp.findTeamByName(searchString);
model.addAttribute("searchResult", searchResult);
}
return "search";
}
In your JSP, you could then access the result as usual object in requestScope like ${searchResult}
Your JSP needs to look like:
<%# page contentType="text/html" pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:MasterTag>
<jsp:attribute name="pageTitle"><c:out value="Search"/></jsp:attribute>
<jsp:attribute name="currentMenuName"><c:out value="Search"/></jsp:attribute>
<jsp:body>
<div></div>
<div class="row">
<form method="get" action="/search">
<div class="small-3 columns">
<input type="text" id ="txt" name="searchString" >
</div>
<div class="small-5 columns end">
<button id="button-id" type="submit">Search Teams</button>
</div>
<div>
${player.superTeam}
</div>
</form>
</div>
And your controller would be:
#Controller
public class SearchController {
#Autowired
SuperPlayerService sp;
#RequestMapping(value = "/search")
public String Search(#RequestParam("searchString") String searchString) {
if(searchString != null){
sp.findTeamByName(searchString);
}
return "search";
}
}

Unable load dropdown list when the page was loading in spring mvc

I trying to populate the dropdown list when page was loaded.But it is not loaded in UserPage.jsp from Controller.on submit method and also wrote referencedata method.
Controller:-
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
log.info("onSubmit handleRequest method"
+ request.getParameter("username"));
System.out.println("onSubmit handleRequest method"
+ request.getParameter("username"));
String username = "", password = "";
username = request.getParameter("username");
password = request.getParameter("password");
UserBean ubean = null;
System.out.println("After shownform method called");
HttpSession session = request.getSession(true);
try {
ubean = userservice.chkUsername(username, password);
System.out.println("Information" + ubean.getUsername());
} catch (DataException ex) {
ex.printStackTrace();
// throw ex;
}
session.setAttribute("User", ubean);
EmpPersonalBean personalBean = new EmpPersonalBean();
return new ModelAndView("jsp/UserPage", "EmpPersonalBean", personalBean);
}
protected Map referenceData(HttpServletRequest request) throws Exception {
log.info("UserDBBoardController======================referenceData");
Map referenceData = new HashMap();
List deparementList = new ArrayList();
deparementList = userservice.getDeparmentList();
referenceData.put("deparmentList", deparementList);
return referenceData;
}
UserPage.jsp
<%# page language="java" import="com.aims.bean.*,java.util.HashMap" contentType="text/html;charset=utf-8" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%#taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<html>
<head>
<title>AAI</title>
</head>
<body>
<form:form method="post" modelAttribute="EmpPersonalBean" action="userpage.htm">
<table>
<tr>
<td>Welcome <%=((UserBean)session.getAttribute("User")).getUsername()%></td>
</tr>
<tr>
<td>Department</td>
<td><form:select path="deparment">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${deparmentList}" />
</form:select>
</td>
</tr>
</tr>
</table>
</form:form>
</body>
</html>
public class DepartmentBean {
private String deptcode,deptname;
public String getDeptcode() {
return deptcode;
}
public void setDeptcode(String deptcode) {
this.deptcode = deptcode;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
}
And also attached displaying dropdown list in the userpage.sjp
Please help me.How to resolve the issue.
You also need to specify itemLabel and itemValue attributes in <form:options/> tag.
UPDATE
Replace this line in your jsp page. I think it should resolve your problem.
<form:options items="${deparmentList}" itemLabel="deptname" itemValue="deptcode" />
Hope this helps you. Cheers.
<td>Department</td>
<td><form:select path="deparment">
<form:option value="NONE" label="--- Select ---" />
<c:forEach var="department" items="${deparmentList}">
<form:option value="${department}" label="${department}" />
</c:forEach>
</form:select>
</td>
ModelAndView mav = new ModelAndView("viewName");
mav.addObject("deparmentList", deparementList);
return mav;
return modelAndView object.

Pass selected value from a select tag to an action using Struts2 and Dojo

I'm trying to pass the selected value of a select tag to an action through ajax when the onchange event is triggered but, for some reason, the action receives the parameter as null.
Here is the code of the jsp:
<%#taglib prefix="s" uri="/struts-tags" %>
<%#taglib prefix="sx" uri="/struts-dojo-tags" %>
<div id="navegacion_proyectos">
<s:select name="id_proyecto_actual" id="proyecto_actual_select" list="proyectos" listValue="titulo_proyecto" listKey="id_proyecto"/>
<s:url id="cambiar_proyecto_actual_url" value="/cambiar_proyecto_actual.action" />
<sx:bind sources="proyecto_actual_select" events="onchange" href="%{cambiar_proyecto_actual_url}" />
</div>
And here is the code of the action:
public class BLProyecto extends ActionSupport {
private String id_proyecto_actual;
public String cambiarProyectoActual() {
Map sesion = ActionContext.getContext().getSession();
sesion.put("proyecto_actual", id_proyecto_actual);
return SUCCESS;
}
public String getId_proyecto_actual() {
return id_proyecto_actual;
}
public void setId_proyecto_actual(String id_proyecto_actual) {
this.id_proyecto_actual = id_proyecto_actual;
}
}
I'm debbuging the code and the id_proyecto_actual parameter is shown as null. What do you think is the problem?
Thank you all, i found the answer. Instead of following an url when the event is triggered, i just submit a form. Like this:
<%#taglib prefix="s" uri="/struts-tags" %>
<%#taglib prefix="sx" uri="/struts-dojo-tags" %>
<div id="navegacion_proyectos">
<s:form id="cambiar_proyecto_actual_form" action="cambiar_proyecto_actual">
<s:select name="id_proyecto_actual" id="proyecto_actual_select" list="proyectos" listValue="titulo_proyecto" listKey="id_proyecto"/>
</s:form>
<sx:bind sources="proyecto_actual_select" formId="cambiar_proyecto_actual_form" targets="pantalla_principal" events="onchange" />
</div>

Resources