Rendering Parent child view causes StackOverflow exception - java

I can not render a nested parent child tree structure in jsp page. Due to stackover flow error which is caused by
<code><jsp:include page=""/></code>
My DB:
Id || Name || Parentid ||
1 || animal|| 0 ||
2 || Dog || 1 || etc.
Model class:
public class Node {
private int id;
private String name;
private int parentId;
private List<Node> children;
public Node() {
}
public Node(String name, int parentId, List<Node> children) {
this.name = name;
this.parentId = parentId;
this.children = children;
}
DAO Class:
#Override
public List<Node> nodelist() {
String sql = "select * from tree";
List<Node> listNode = jdbcTemplate.query(sql, new RowMapper<Node>() {
#Override
public Node mapRow(ResultSet rs, int rowNum) throws SQLException {
Node node = new Node();
node.setId(rs.getInt("id"));
node.setName(rs.getString("name"));
node.setParentId(rs.getInt("parent_id"));
return node;
}
});
return listNode;
}
In the controller i bind the object as below:
List<Node> rootNodes;
#Autowired
TreeDao treeDao;
#RequestMapping(value = "/node", method = RequestMethod.GET)
public ModelAndView getallnodes(ModelAndView model) throws IOException {
//menuObj = menuDao.listCategory();
List<Node> listnode = treeDao.nodelist();
getInfiniteTree(listnode);
model.addObject("rootNodes",rootNodes);
model.setViewName("tree");
return model;
}
public List<Node> getInfiniteTree(List<Node> nodes) {
return findRootNodes(nodes);
}
private List<Node> findRootNodes(List<Node> nodes) {
rootNodes = new ArrayList<Node>();
for (Node node : nodes) {
if (node.getParentId() == 0) {
rootNodes.add(node);
findChildNodes(node, nodes);
}
}
System.out.println("rootnodes "+rootNodes);
Gson gson = new Gson();
System.out.println(gson.toJson(rootNodes));
//I got the correct json format data here.
//Collections.sort(rootNodes);
return rootNodes;
}
private void findChildNodes(Node parentNode, List<Node> nodes) {
List<Node> children = new ArrayList<Node>();
parentNode.setChildren(children);
for (Node node : nodes) {
if (node.getParentId() == parentNode.getId()) {
children.add(node);
findChildNodes(node, nodes);
}
}
//Collections.sort(children);
}
In another java swing project i test the similar code and got follwing String result:
nodes [Node{id=1, name=供应链部, parentId=0, sort=3, children=[Node{id=5, name=物流部, parentId=1, sort=1, children=[]}, Node{id=6, name=采购部, parentId=1, sort=2, children=[]}]}, Node{id=2, name=技术部, parentId=0, sort=1, children=[Node{id=7, name=开发部, parentId=2, sort=2, children=[Node{id=12, name=后端部, parentId=7, sort=2, children=[]}, Node{id=13, name=前端部, parentId=7, sort=2, children=[Node{id=14, name=diee, parentId=13, sort=2, children=[]}, Node{id=15, name=diee, parentId=13, sort=2, children=[]}]}]}, Node{id=8, name=测试部, parentId=2, sort=1, children=[]}, Node{id=9, name=运维部, parentId=2, sort=3, children=[]}]}, Node{id=3, name=行政部, parentId=0, sort=2, children=[Node{id=10, name=招聘部, parentId=3, sort=1, children=[]}, Node{id=11, name=人事部, parentId=3, sort=2, children=[]}]}, Node{id=4, name=公关部, parentId=0, sort=4, children=[]}]
The problem is i can not display it using jsp recursion, i tried below code:
tree.jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<c:set var="menuitem" value="${rootNodes}" scope="request" />
<jsp:include page="menuitem.jsp" />
</body>
</html>
menuitem.jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<ul>
<c:forEach var ="menuitems" items="${menuitem}">
<li>${menuitems.name}</li>
<ul>
<c:if test="${fn:length(menuitems.children) gt 0}">
<li class="droprightMenu">
<c:out value="Has children"></c:out>
<c:forEach var="menuitemc" items="${menuitems.children}">
<c:set var="menuitem" value="${menuitemc}" scope="request" />
<%--<jsp:include page="menuitem.jsp" />--%>
</c:forEach>
</li>
</c:if>
</ul>
</c:forEach>
</ul>
It is not including page through infinite children and as I am a new in JSP recursion please ignore my faults. I stuck here for couple of days.
Exception:
Don't know how to iterate over supplied "items" in <forEach>
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/views/menuitem.jsp at line 14
11:
12:
13: <ul>
14: <c:forEach var ="menuitems" items="${menuitem}">
15: <li>${menuitems.name}</li>
16: <ul>
17: <c:if test="${fn:length(menuitems.children) gt 0}">

menuitem.jsp
<c:forEach var="menuitem" items="${menuitem.children}">
<li><i class="fa fa-circle-o"></i> <span>${menuitem.name} </span></li>
<c:set var="menuitem" value="${menuitem}" scope="request" />
<jsp:include page="/WEB-INF/views/menuitem.jsp" />
</c:forEach>
I think the problem lies in here. Try renameing var="menuitem" to var="childmenuitem.
I believe that you currently keep passing the same object to your submenu, causing an infinite loop.

Finally I solved it in this way:
tree.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<c:set var="menuitem" value="${rootNodes}" scope="request" />
<jsp:include page="menuitem.jsp" />
</body>
</html>
And in menuitem.jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<ul>
<c:forEach var ="menuitems" items="${menuitem}">
<li>${menuitems.name}</li>
<ul>
<c:if test="${fn:length(menuitems.children) gt 0}">
<li class="droprightMenu">
<c:out value="Has children"></c:out>
<%--<c:forEach var="menuitemc" items="${menuitems.children}">--%>
<c:set var="menuitem" value="${menuitems.children}" scope="request" />
<jsp:include page="menuitem.jsp" />
<%--</c:forEach>--%>
</li>
</c:if>
</ul>
</c:forEach>
</ul>
Hope it will help somebody.

Related

How to display List results in JSP Page?

I Have a class that find Google search results. And i have a JSP page that i want to show the results in. But i can't do it.
Heres my UrlOku class :
public static void GetUrl() {
final String keyword = "emre varol";
final String url = "https://www.google.com/search?q="+keyword;
try {
final Document document = Jsoup.connect(url).get();
List<String> myList = new ArrayList<String>();
for(Element row: document.select("div[class=g]")) {
final String title = row.select("div[class=TbwUpd NJjxre]").text();
myList.add(title);
}
}
And heres my JSP page :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="urlpaket.Urloku" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="menu.jsp"></jsp:include>
<%
if(session.getAttribute("username")==null){
response.sendRedirect("login.jsp");
}
%>
WELCOME ${username}
<%
Urloku oku = new Urloku();
oku.GetUrl();
%>
<c:forEach items="${myList}" var="item">
<tr>
<td><c:out value="${item.title}" /></td>
</tr>
</br>
</c:forEach>
And there is nothing in the welcome.jsp file.
Any help would be appreciated!
How is myList variable available in you JSP? This needs to be set in pageContext before accessing it using ${myList}.
You can change the signature to public static List GetUrl()
and do something like this
Urloku oku = new Urloku();
List<String> myList = oku.GetUrl();
pageContext.setAttribute("myList ",myList );
Now it should be available.

spring:mvcUrl mapping wrong id

I am trying to map productId to URL in my jsp page, but the value is wrong.
The URL is returning Título 1 but the response is returning the right value:
HTML Mapping
My jsp code:
<%# page language="java" contentType="text/html; charset=iso-8859-1" pageEncoding="iso-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
${success}
</div>
<table>
<tr>
<td>Id</td>
<td>Titulo</td>
<td>Valores</td>
</tr>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td>${product.title}</td>
<td>
<c:forEach items="${product.prices}" var="price">
[${price.value} - ${price.bookType}]
</c:forEach>
</td>
</tr>
</c:forEach>
</table>
My Java Controller Code:
#RequestMapping(method=RequestMethod.GET)
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("products/list");
modelAndView.addObject("products", productDAO.list());
return modelAndView;
}
My Java DAO Code:
public List<Product> list() {
return manager.createQuery("select distinct(p) from Product p join fetch p.prices", Product.class).getResultList();
}
Unfortunately I cannot see your method 'show'.
I guess you have a misprint in the path:
#RequestMapping("/show{/id}")
//--------------------^^ WRONG
public String show(#PathVariable("id") long id) {
...
}
instead
#RequestMapping("/show/{id}")
//--------------------^^ RIGHT

Model Data is not getting transferred to the jsp page

I have designed a Login page using Spring MVC,JPA(Hibernate) and Jsp.
Please find the login.jsp :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<h2>Login page</h2>
<form:form method="POST" modelAttribute="loginBean" action="showProfile">
<table>
<tr>
<td>UserName :<form:input path="userName"/></td>
</tr>
<tr>
<td>Organization Id :<form:input path="OrgId" /></td>
</tr>
<tr>
<td>Password : <form:input path="password" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
profilePage.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table border="2" width="70%" cellpadding="2">
<tr>
<th>UserName</th>
<th>Password</th>
</tr>
<c:forEach var="staff" items="${staffData}">
<tr>
<td>${staff.userName}</td>
<td>${staff.password}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
LoginController.java:-
#Controller
public class LoginController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showLoginPage(Model model) {
model.addAttribute("loginBean", new LoginBean());
return "login";
}
#RequestMapping(value = "/showProfile", method = RequestMethod.POST)
public ModelAndView redirectToprofile(#ModelAttribute("loginBean") LoginBean loginBean) {
StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
Staff staff = staffServiceImpl.authenticateStaff(loginBean);
if (null != staff) {
return new ModelAndView("redirect:/profilePage","staffData",staff);
}
return new ModelAndView("profileNotFound");
}
#RequestMapping(value = "/profilePage", method = RequestMethod.GET)
public String showProfilePage() {
return "profilePage";
}
After giving the valid details in the Login.jsp page it is redirecting to profilePage.jsp but the data in profilePage.jsp is not correct. Please help me to understand where i am doing the mistake.
The profilePage.jsp is displayed a below:-
UserName Password
${staff.userName} ${staff.password}
The Value of this variable is not getting displayed.
profilePage.jsp : Add isELIgnored="false" in page directive.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
Update your controller with the following :
#Controller
public class LoginController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showLoginPage(Model model) {
model.addAttribute("loginBean", new LoginBean());
return "login";
}
#RequestMapping(value = "/showProfile", method = RequestMethod.POST)
public String redirectToprofile(#ModelAttribute("loginBean") LoginBean loginBean , Model model) {
StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
Staff staff = staffServiceImpl.authenticateStaff(loginBean);
if (null != staff) {
model.addAttribute("staffData",staff);
return "profilePage";
}
return "profileNotFound";
}
the above answer is correct, and this is an explination:
The isELIgnored attribute gives you the ability to disable the evaluation of Expression Language (EL) expressions which has been introduced in JSP 2.0.
The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.
Source :enter link description here

How to get values from array in jsp

I want to show the data from an array using JSP.
I have three files:
index.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World! </h1>
<form name="Input Name Form" action="response.jsp"/>
<p> Enter your name:</p>
<input type="text" name="name"/>
<input type="submit" value="ok" />
</form>
</body>
</html>
response.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1> <br>
<jsp:useBean id="aaa" scope="page" class="A.a" />
<jsp:setProperty name="aaa" property="name" value="<%= request.getParameter("name")%>" />
<jsp:getProperty name="aaa" property="name" />
</body>
</html>
a.java:
public class a {
public a ()
{}
private String name;
ArrayList() array_list = new ArrayList();
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
//some magic to fill array_list with values
}
}
My question is:
What statement should I use in jsp to get values from array_list in a.java?
I know that there is statement
<c:forEach> </c:forEach>
but I am not sure how to use it.
<c:forEach items="${dataDetail}" var="data" varStatus="item">
<c:out value="${data.id}"/>
</c:forEach>
Here "dataDetail" is name of the key where you have set your list in controller.
(session or request ).setAttribute("dataDetail",---List of Data of type Class Data---);
Above code is similar to
for(Data data : dataDetail){
System.out.println(data.getId());
}
A similar question has been asked here: Iterate ArrayList in JSP
Long story short:
<c:forEach items="${aaa.array_list}" var="item">
${item}
</c:forEach>
use JSTL.
Try this out:
Have this at top of your JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
And code for displaying data
<c:forEach begin="0" end="${fn:length(array_list) - 1}" var="index">
<tr>
<td><c:out value="${array_list[index]}"/></td>
</tr>
</c:forEach>

Displaying tree on JSP page

I need to display tree on JSP page. How can I do that? I have following object:
public class Node {
private Long id;
private Long parentId;
private String name;
private List<Node> children;
// Getters & setters
}
Roll your own with jsp recursion
In Controller.java
Node root = getTreeRootNode();
request.setAttribute("node", root);
In main.jsp page
<jsp:include page="node.jsp"/>
In node.jsp
<c:forEach var="node" items="${node.children}">
<!-- TODO: print the node here -->
<c:set var="node" value="${node}" scope="request"/>
<jsp:include page="node.jsp"/>
</c:forEach>
Based on http://web.archive.org/web/20130509135219/http://blog.boyandi.net/2007/11/21/jsp-recursion/
You may want to try http://www.soft82.com/download/windows/tree4jsp/
It is also downloadable from http://www.einnovates.com/jsptools/tree4jsp/tree4jsp_v1.2.zip
Jsp tree Project can help you.
I'd recommend you to use one of the available tag libraries.
For example:
http://beehive.apache.org/docs/1.0/netui/tagsTree.html
The following discussion can help too.
http://www.jguru.com/faq/view.jsp?EID=46659
Just check this JSP tree. It is simple and has minimum Java Scripts. I used velocity templates and JSP Tag class.
simple JSP tree
Compilation from the other answers. Tested.
Recursion on JSP tags
Unit.java
public class Unit {
private String name;
private HashSet<Unit> units;
// getters && setters
}
Employees.java
public class Employees {
private HashSet<Unit> units;
// getters && setters
}
Application.java
...
request.setAttribute("employees", employees);
request.getRequestDispatcher("EmployeeList.jsp").forward(request, response);
...
EmployeeList.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
<ul>
<c:forEach var="unit" items="${employees.getUnits()}">
<li>
<c:set var="unit" value="${unit}" scope="request"/>
<jsp:include page="Unit.jsp"/>
</li>
</c:forEach>
</ul>
</body>
<html>
Unit.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<span>${unit.getName()}</span>
...
<ul>
<c:forEach var="innerUnit" items="${unit.getUnits()}">
<li>
<c:set var="unit" value="${innerUnit}" scope="request"/>
<jsp:include page="Unit.jsp"/>
</li>
</c:forEach>
</ul>

Categories

Resources