Spring MVC + DisplayTag + Checkbox - spring

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 ?

Related

Dynamic select list in a Liferay MVCPortlet

You can create a select list with static options in Liferay MVCPortlet JSP page like this:
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<aui:form>
<aui:select name="items">
<aui:option value="item1">Item1</aui:option>
<aui:option value="item2">Item2</aui:option>
</aui:select>
</aui:form>
What is the recommended way of creating the options dynamically for a list of objects stored in portlet session?
Use a foreach tag:
https://www.tutorialspoint.com/jsp/jstl_core_foreach_tag.htm
<%# taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<aui:form>
<aui:select name="items">
<c:forEach items="<%=yourList%>" var="yourlistItem">
<aui:option value="${yourlistItem.value}">${yourlistItem.name}</aui:option>
</c:forEach>
</aui:select>
</aui:form>

Type [java.lang.String] is not valid for option items upon migrating from Spring 3.0.6 to 3.2.3

I am working on migrating a dynamic web project from Spring 3.0.6 to 3.2.3. Prior to this migration, we had no issue with our dropdowns. However, after migrating, we get the following error:
Exception created : com.ibm.websphere.servlet.error.ServletErrorReport: javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items
I've removed all the code to isolate the issue, so below is the relevant code. Please let me know if any further information is needed. The thing that puzzles me is that the List isn't even String based. I realize that the JSP will treat the values as String for the options, but my understanding is that there is a built-in PropertyEditor that would do this translation.
Controller:
#RequestMapping("/reports-menu.html")
public String showReportsHome(#ModelAttribute("reportForm")ReportForm reportForm, Model model, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
model.addAttribute("intList", intList);
return "reports-home-int";
}
JSP:
<%# taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<%# taglib uri="/WEB-INF/tld/fmt.tld" prefix="fmt" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="/WEB-INF/tld/sbp.tld" prefix="sbp" %>
<form:form name="report_form" method="POST" modelAttribute="reportForm" action="reports-menu.html" id="report_form">
<form:hidden path="download" id="form_download"/>
<form:hidden path="sortDirection" />
<form:hidden path="sortBy"/>
<input type="hidden" name="reset"/>
<div align="left">
<table border="0">
<tr>
<td><b>Mailer Name</b></td>
<td>
<form:select path="mailerCond">
<form:options items="${intList}" />
</form:select>
</td>
</tr>
</table>
</div>
</form:form>

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

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" %>

Spring MVC: Url path appending when posting the form

i am new to spring mvc. i created a simple login application. but in my case the first time the for posting url and calling controller method correctly. in second time it's appending path with one more time of controller. first time post:
//localhost:8090/springmvc/account/login secong time in same page: //localhost:8090/springmvc/account/account/login. how do i fix this redirecting problem?
this my controller page:
#Controller
#RequestMapping("account")
public class AccountController {
AccountService service = new AccountService();
#RequestMapping(value = "account/default", method = RequestMethod.GET)
public ModelAndView RegisterUser() {
return new ModelAndView("/Account/Index","command",new User());
}
#RequestMapping(value = "/registeruser", method = RequestMethod.POST)
public ModelAndView RegisterUser(User user) {
user.setMessage(service.Register(user));
return new ModelAndView("/Account/Index", "command", user);
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView RegisterUer(User user) {
user.setMessage(service.Register(user));
return new ModelAndView("/Account/create", "command", user);
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView LoginUser(User user, ModelMap model) {
String msg = service.isAuthendicated(user) ? "Logged in" : "Failed";
user.setMessage(msg);
return new ModelAndView("/Account/Index", "command", user);
}
}
this my jsp page:
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib prefix="t" tagdir="/WEB-INF/tags"%>
<t:genericpage>
<jsp:body>
<h2>Login</h2>
<div>
${command.message} </div>
Register
<form:form action="account/login" method="post">
<div>
<form:input path="username" />
</div>
<div>
<form:input path="password" />
</div>
<input type="submit" value="Login">
</form:form>
</jsp:body>
</t:genericpage>
i used the tag library for common page:
<%#tag description="Master Page" pageEncoding="UTF-8"%>
<html>
<body>
<div id="pageheader">
<h2>WElcome</h2>
</div>
<div id="body">
<jsp:doBody />
</div>
<div id="pagefooter">
<p id="copyright">Copyright</p>
</div>
</body>
</html>
Depending on which version of Spring you're using, here are some options:
Spring 3.1 and lower OR Spring 3.2.3 and higher
You should have your urls/actions root-relative specific to your context path.
<form:form action="${pageContext.request.contextPath}/account/login" method="post">
Note: Spring 3.2.3 introduced servletRelativeAction but I've never used it.
Spring 3.2
Don't do anything, context path is prepended - this was actually a breaking change and eventually rolled back.
<form:form action="/account/login" method="post">
//will produce action="/springmvc/account/login"
Start your form action with a /.
<form:form action="/account/login" method="post">
By not doing it, you're telling the browser to append the action to the already existing URL on the address bar.
And where you have such links directly in HTML (by not using Spring's form:form), try to use c:url to properly construct the URL including the context path etc. This takes a lot of pain away from building proper relative URLs.
Register
Use ../ to get URL of your current context root:
<form:form action="../account/login" method="post">
from here
I tried with the spring tag bysetting only the relative path, it appends automatically the context path like:
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<head>
<!-- ... -->
<spring:url value="/account/login" var="loginUrl" />
<form:form action="${loginUrl}" method="post">
The context path is set in application.properties as bellow:
server.servlet.contextPath=/MyApp
In the jsp page, it produces:
<a class="nav-link" href="/MyApp/account/login"> <i class="fas fa-play"></i> <span>Click here</span></a>

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