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}"/>
Related
this is my implementation class
#Service
public class QuizServiceImp implements QuizService {
#Autowired
QuizCategoryRepository quizCategoryRepository;
#Override
public List<QuizCategory> findAll() {
List<QuizCategory> list = new ArrayList();
list=(List<QuizCategory>)quizCategoryRepository.findAll();
return list;
}
}
JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.util.List"%>
<%#page import="com.quizV1.service.QuizServiceImp"%>
<%#page import="com.quizV1.model.QuizCategory"%>
<%# taglib uri = "java.sun.com/jsp/jstl/core" prefix = "c" %>
<%-- <%# page isELIgnored="false"%> --%>
<% QuizServiceImp ob=new QuizServiceImp(); List<QuizCategory> list=ob.findAll(); %>
i want to call this funtion in jsp page
You use Spring to inject dependencies into QuizServiceImp so you cannot use constructor to initialize variables of QuizServiceImp because in this case Spring doesn't know then you've created new instance and it needs to inject dependencies.
To fix it you need to get bean from Spring context.
<%#page import="org.springframework.web.context.WebApplicationContext"%>
<%#page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(application);
QuizService service = context.getBean(QuizeService.class);
%>
In the servlet:
List<myItem> yourObjectToReturn = search.parserContent();
request.setAttribute("yourObjectToReturn",yourObjectToReturn);
the array yourObjectToReturn consists 3 variable(id, txtfile, sentence) which you can see from
the myItem class
public class myItem{
String sentence;
int id;
String txtfile;
// public myItem(){
// }
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getTxtfile(){
return txtfile;
}
public void setTxtfile(String txtfile){
this.txtfile = txtfile;
}
public String getSentence(){
return sentence;
}
public void setSentence(String sentence){
this.sentence = sentence;
}
}
how to display the id, txtfile, sentence in the JSP separately? How to pass the arraylist from servlet to JSP .
the JSP : how to edit my JSP. I got error of my JSP:
type safety: unchecked cast from objectto arraylist
<%# page import="java.io.*" %>
<%# page import="java.net.*" %>
<%# page import="java.util.*" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
<% List<myItem> myList = (ArrayList<myItem>) request.getAttribute("yourObjectToReturn"); %>
The search Result SENTENCE IS: <%=myList %> --%>
</body>
</html>
Don't use scriptlets in your jsp page.
Include the JSTL standard taglib via:
<%# taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
Then in your JSP use the iteration tag:
<c:forEach items="${requestScope.yourObjectToReturn}" var="current">
<c:if test="${current.sentence== 'secret' }">
<h1>seeeeeeeeeecret revealed</h1>
</c:if>
</c:forEach>
Where:
${requestScope.yourObjectToReturn} is your collection object.
And (during each iteration):
${current} is your actual element.
For further reference look http://docs.oracle.com/javaee/5/tutorial/doc/bnahq.html
And to avoid weird errors: don't forget to import myItem class (Should really be MyItem, thou...)
EDIT: Before digging deep into JSTL, I suggest you to take a reading of this other question. Particularly focus on the selected answer, it provides great insights.
To retrieve the Id and Txtfile from the List you need to iterate with using for example a for loop like:
...
for (int i=0; i < myList.size(); i++) {
%>
<%=myList.get(i).getId()%>
<%=myList.get(i).getTxtfile())%>
<%}%>
You can use for loop and html together as follows:
<%
#SupressWarnings("unchecked")
List<mtItem> myList
for (MyItem myitem : myList)
{
%>
The search result is <%=myitem%>
<%
}
%>
I have an action class with a String property named jspString. I create the content for the resulting JSP of this action class using the property jspString. I have included my action class and the resulting JSP codes. My problem is, when I try to include a JSP page , using jsp:include tag, it is not rendering the content of that page in the resulting page.
Action class :
public class HomeAction extends ActionSupport
{
private String jspString = "";
public String execute()
{
jspString += "<div>";
jspString += "<p>";
jspString += "<jsp:include page=\"check.jsp\">";
jspString += "</p>";
jspString += "</div>";
return "success";
}
public String getJspString()
{
return jspString;
}
public void setJspString(String jspString)
{
this.jspString = jspString;
}
}
Resulting JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="/struts-tags" prefix="s" %>
<html>
<body>
<s:property escapeHtml="false" value="jspString"/>
</body>
</html>
now div, p tags are created. But jsp:include is not working. It is not displaying the contents of check.jsp in the resulting page.
Use the s:action tag it allows execute action on the server and return jsp in the body of the tag.
<s:action name="home"/>
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.
I need to display all values of an enum as <option> elements. I have achieved this using scriptlets:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="errors" tagdir="/WEB-INF/tags/jostens/errors" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<%
Class<?> c = CarrierCode.class;
for (Object carrier : c.getEnumConstants()) {
CarrierCode cc = (CarrierCode) carrier;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
out.print(formatter.format("<option value='%s'>%s</option>\n", cc.getMfCode(), cc.name()));
}
%>
...
However, I would like to implement it using JSTL/EL code instead. How can I do it?
UPDATE:
Spring has a much easier way to do this now. First add the spring frame work tags
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
then if you just declare a select where the variable in path is an Enum,
spring automagically finds the other elements.
<form:select path="dataFormat.delimiter" class="dataFormatDelimiter">
<form:options items="${dataFormat.delimiter}"/>
</form:select>
Create a ServletContextListener implementation which puts the enum values in the application scope during webapp startup so that it's available in EL by ${carrierCodes}. This class is reuseable for all other things you'd like to do once during webapp's startup.
#WebListener
public class Config implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("carrierCodes", CarrierCode.values());
}
#Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP
}
}
Note that I used Enum#values() instead of the clumsy Class#getEnumConstants() method. It returns an array of all enum values.
Then, in JSP, just use JSTL <c:forEach> to iterate over it.
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="carrierCode">
<c:forEach items="${carrierCodes}" var="carrierCode">
<option value="${carrierCode.mfCode}">${carrierCode}</option>
</c:forEach>
</select>