Struts 2 Select tag error - java

I am new to Struts2. I want to compare JSTL's c tag and Struts2 s tag which one is easy to use... My code as below
ListDepartmentNameAction.java
package actions;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.mapping.Array;
import com.opensymphony.xwork2.ActionSupport;
import service.ListDepNameService;
public class ListDepartmentNameAction extends ActionSupport{
private static Logger log = Logger.getLogger(ListDepartmentNameAction.class);
ListDepNameService listDepNameService;
private List<String> allDNlist ;
public String execute() {
allDNlist = listDepNameService.ListAllDepName();
for (String ss : allDNlist) {
System.out.println(ss);
}
log.info(allDNlist);
return "success";
}
public ListDepNameService getListDepNameService() {
return listDepNameService;
}
public void setListDepNameService(ListDepNameService listDepNameService) {
this.listDepNameService = listDepNameService;
}
public List<String> getAllDNlist() {
return allDNlist;
}
public void setAllDNlist(List<String> allDNlist) {
this.allDNlist = allDNlist;
}
}
query.jsp
<%# page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<s:head />
<h1 align="center" id="h1"></h1>
<body>
<s:form action="listDepName" id="form" method="post">
<input name="Button" type="submit" id="listsubmit" value="List all Department Name"
onclick="javascirpt:abc(this)"/>
</s:form>
<select>
<c:forEach items="${allDNlist}" var="item">
<option value="abc" >${item}</option>
</c:forEach>
</select>
<s:if test="%{allDNlist==null}">456</s:if>
<s:else><s:select name="xxx" list="allDNlist" /></s:else> <!-- 1st -->
<s:select name="xyz" list="allDNlist" /> <!-- 2nd -->
</body>
</html>
"allDNlist" can get value from action class,therefore, JSTL c tag work properly.
I don't understand why the "1st" struts2 select tag work fine, but "2nd" select s tag doesn't work, and got message like this
HTTP Status 500 - tag 'select', field 'list', name 'xyz': The requested list key 'allDNlist' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
even I comment() the "2nd" select s tag, I still got same error message as above, only remove it.

EDIT:
I reproduced your whole code and it is perfectly working.
Note that you don't close </head> tag, i reproduced that too and it works the same...
It should be
<head>
<s:head/>
</head>
You should declare your ListDepNameService listDepNameService; as private too (you already have the accessors), and check what type of List is returned.
I tested the code with
allDNlist = new ArrayList<String>();
allDNlist.add("Valore 1 ");
allDNlist.add("Valore 2 ");
allDNlist.add("Valore 3 ");
in execute() method, this is the only difference.
Please try this instead the service call, and let me know...

I had the similar type of collection error while populating the drop down with <s:select: tag. after research i figured out that "i did not initialize my instance variable List" in your case make private List<String> allDNlist = new ArrayList<String>(); should solve the problem.

Related

Jsp include another jsp with Struts2, but no result

I used a jsp include another jsp, but I don't get any result, only html tag content.
HelloEmp.jsp: it had iterator value with stuts2 tag.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix = "s" uri = "/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Example of List</h2>
<s:iterator value="helloList">
<s:property /><br/>
</s:iterator>
</body>
</html>
HelloAction.java: it had a string array
import java.util.ArrayList;
import java.util.List;
public class HelloAction {
private List<String> helloList = new ArrayList<String>();
public String execute() throws Exception {
helloList.add("Jacky");
helloList.add("Natali");
return "success";
}
public List<String> getHelloList() {
return helloList;
}
public void setHelloList(List<String> helloList) {
this.helloList = helloList;
}
}
employees.jsp: it included HelloEmp.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<title>Employees</title>
</head>
<body>
<p>An example of the include tag: </p>
<s:include value = "example/HelloEmp.jsp"/>
</body>
</html>
struts.xml:
<package name = "helloworld" extends = "struts-default">
<action name = "hello" class = "example.HelloAction" method = "execute">
<result name = "success">HelloEmp.jsp</result>
</action>
</package>
When I opened employees.jsp, only can see tag content in HelloEmp.jsp, I can't see the iterator value:
But if I directly open HelloEmp.jsp, I got the result:
Please help me how to fix it? thank you!
Instead of using value use page
<jsp:include page="Demo.jsp" /> might work.
Finally I use action tag instead,
<s:action name="action_name" executeResult="true"/>
that works for me!
Thank you for you guys.

who's can help me with struts2 and hibernate to solve a particular exception: HTTP 404 - There is no Action mapped for namespace

I'm learning how to use struts2 and hibernate, but i canĀ“t resolve this exception "There is no Action mapped for namespace [/] and action name [registrar_barrios] associated with context path [/ConsultarPatente].". I know it's asked many time, but it's common for several case, as well here we go:
The next is built on eclipse.
1.- Project explorer https://www.dropbox.com/s/4gg52h64e4hz64s/package.png?dl=0
2.- Codes (src and WebContent folers).
https://www.dropbox.com/s/x3q9qtq050a8anv/Files.rar?dl=0
3.- I thinks AgregarBarrioAction and registrar_barrios are not working.
4.- Database.
CREATE TABLE `barrio_table` (
`barrioId` int(11) NOT NULL auto_increment,
`Nombre` varchar(24) collate utf8_bin NOT NULL,
PRIMARY KEY (`barrioId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=4 ;
5.- AgregarBarrioAction code.
package com.java.rmo.actions;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import com.java.rmo.dao.BarrioDAO;
import com.java.rmo.dao.BarrioDAOImpl;
import com.java.rmo.model.Barrio;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
#Namespace(value="/")
public class AgregarBarrioAction extends ActionSupport
implements ModelDriven<Barrio>
{
private static final long serialVersionUID = -6659925652584240539L;
private Barrio barrio = new Barrio();
private List<Barrio> barrioList = new ArrayList<Barrio>();
private BarrioDAO barrioDAO = new BarrioDAOImpl();
#Override
public Barrio getModel()
{
return barrio;
}
#Action
(
value="agregarBarrio",
results={#Result(location="/registrar_barrios.jsp", type="redirect")}
)
public String add()
{
barrioDAO.saveBarrio(barrio);
return SUCCESS;
}
#Action
(
value="consultarBarrio",
results={#Result(location="/registrar_barrios.jsp")}
)
public String list()
{
setBarrioList(barrioDAO.listBarrio());
return SUCCESS;
}
public Barrio getBarrio()
{
return barrio;
}
public void setBarrio(Barrio barrio)
{
this.barrio = barrio;
}
public List<Barrio> getBarrioList()
{
return barrioList;
}
public void setBarrioList(List<Barrio> barrioList)
{
this.barrioList = barrioList;
}
}
6.- registrar_barrios.jsp code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<!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>
<s:form action="agregarBarrio">
<s:textfield name="nombre" label="Nombre" />
<s:submit />
</s:form>
<s:if test="consultarBarrio.size() > 0">
<div class="content">
<table class="barrioTable" cellpadding="5px">
<tr class="even">
<th>Nombre</th>
</tr>
<s:iterator value="consultarBarrio" status="barrio">
<tr
class="<s:if test="#barrio.odd == true ">odd</s:if><s:else>even</s:else>">
<td><s:property value="nombre" /></td>
</tr>
</s:iterator>
</table>
</div>
</s:if>
</body>
</html>
Give me a help, i appreciate to you. Good luck!!!
The error
There is no Action mapped for namespace [/] and action name [registrar_barrios] associated with context path [/ConsultarPatente].
is telling you that your action is not accessible. And it is not a surprise, since you don't have any #Action(name="registrar_barrios").
Your actions are instead agregarBarrio and consultarBarrio:
#Action(value="agregarBarrio",
results={#Result(location="/registrar_barrios.jsp", type="redirect")}
)
#Action(value="consultarBarrio",
results={#Result(location="/registrar_barrios.jsp")}
)
The first result is also using redirect out of turn. Remove it.

Struts 2 If-Else-If

I have set an attribute in session in the UserAction class that will be retrieved in a JSP. The retrieved attribute from the session will control how the page will be displayed. The intention is to make certain portions of the JSP turn on/off depending on the type of user (0 = guest, 1 = admin, 2 = user) after logging in.
Action Class:
public class UserAction extends ActionSupport implements SessionAware {
private static final long serialVersionUID = 1L;
private Map<String, Object> session;
private String userId;
private String userPassword;
private String userEmail;
private int userType;
private Date registeredDate;
#Override
public String execute() {
UserManager um = new UserManager();
String registeredPassword = um.getCurrentUserDetail("user_password",
getUserId());
if (getUserPassword().equals(registeredPassword)) {
String currentUserId = um.getCurrentUserDetail("user_id", userId);
int currentUserType = um.getCurrentUserType(userId);
session.put("currentUserId", (String) currentUserId);
session.put("currentUserType", (Integer) currentUserType);
System.out.println("You have successfully logged in!");
return SUCCESS;
}
System.out.println("Your login has failed!");
return ERROR;
}
#Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
// getters and setters
}
index.jsp:
<%# taglib prefix="s" uri="/struts-tags"%>
<%# page import="com.mypackage.model.UserAction"%>
<html>
<head>
<title>My Site - Home</title>
<%# include file="css/style.css"%>
<%# include file="css/style2.css"%>
<s:set var="type" value="0" />
<s:if test='#session.containsKey("currentUserType")'>
<s:set var="type" value='#session["currentUserType"]' />
</s:if>
</head>
<body>
<div id="wrapper">
<div id="inner">
<div id="header">
<s:if test="type==0">
<%# include file="templates/guest-header.jsp"%>
</s:if>
<s:else>
<%# include file="templates/logged-header.jsp"%>
</s:else>
</div>
<dl id="browse">
<s:if test="type==1 || type==2">
<%# include file="templates/logged-acct.jsp"%>
</s:if>
<dt>NAVIGATE WEBSITE</dt>
<s:if test="type==0">
<%# include file="templates/guest-nav.jsp"%>
</s:if>
<s:elseif test="type==1">
<%# include file="templates/admin-nav.jsp"%>
</s:elseif>
<s:elseif test="type==2">
<%# include file="templates/user-nav.jsp"%>
</s:elseif>
<dt>SEARCH MOVIE</dt>
<dd class="searchform">
<%# include file="templates/search-box.jsp"%>
</dd>
</dl>
<div id="body">
<div class="inner">
<%# include file="templates/content.jsp"%>
</div>
<!-- end .inner -->
</div>
<!-- end body -->
<div class="clear"></div>
<%# include file="templates/copyright.jsp"%>
</div>
<!-- end inner -->
</div>
<!-- end wrapper -->
<%# include file="templates/footer.jsp"%>
</body>
</html>
However, it does not seem to enter any of the if-conditions. At the very least, I believe the guest view should be displaying, since type has been initially set to 0 by <s:set var="type" value="0" />.
(Kindly forgive the design for now, I have been made aware there is an elegant approach with this using <s:include> instead of <%# include %>, but I am only beginning Struts 2. I often make improvements/optimizations after I make it work.)
You've forgot the pound sign # in your testing.
It should be like this.
<s:if test="#type==0">
<%# include file="templates/guest-header.jsp"%>
</s:if>
<s:else>
<%# include file="templates/logged-header.jsp"%>
</s:else>
Reference on how to access a variable in struts

Custom list + JSP + java.lang.NumberFormatException

I want to implement custom JSP list tag, but have problem with accessing properties of custom list object. With example like below accessing a name property of List2 on test.jsp page give an error org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "name". How to solve this ?
public class List2 extends ArrayList<String> {
public String getName() {
return "name";
}
}
test.jsp
<%-- java.lang.NumberFormatException --%>
${list.name}
<%-- this works ok --%>
<c:forEach items="${list}" var="item">
${item}
</c:forEach>
EDIT
Whole test.jsp working
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${list}" var="item">
${item}
</c:forEach>
Whole test.jsp NOT working
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
${list.name}
TestController.java:
#Controller
public class TestController {
#ModelAttribute("list")
public List2 testList() {
List2 l = new List2();
l.add("foo");
l.add("bar");
return l;
}
/* test.jsp */
#RequestMapping("/test")
public String test() {
return "test";
}
}
I think it's due to the fact that the JSP EL allows using . or [] to access object properties. But both have a special meaning for List instances: it means access to the nth element. You may thus write ${list[2]} or ${list.2}. Since EL detects that your object is an instance of a collection, it tries to transform name into a number, and you get this exception.
Note that this is only an explanation of the exception you get. I haven't checked the specification to see if it's a bug of Tomcat or if it's expected behavior.
You should very very rarely extend ArrayList. Most of the time, it's better to use delegation, and thus wrap the list inside another object. Couldn't you just have something like the following?
public class List2 {
private List list;
public String getName() {
return "name";
}
public List getList() {
return list;
}
}
Creating an extra class would be redundant, try using the following:
<c:set var="listName"><jsp:getProperty name="list" property="name"/></c:set>
<c:out value="${listName}"/>

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