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>
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);
%>
I am getting values from DAO its stored in varaible editVal and page return to edit.jsp now how to get varaible editVal values in edit.jsp page..
Controller page:
#RequestMapping(value="edit", method=RequestMethod.GET)//String
public ModelAndView callgetSuccess(#ModelAttribute("id")String Id, BindingResult result, ModelMap model) {
ModelAndView shop=new ModelAndView();
shopModel shModel=new shopModel();
if(result.hasErrors()){
System.out.println("error");
return new ModelAndView("edit","shopModel",editVal);//"edit"
}else{
shModel = shopService1.editshop(Id);
model.addAttribute("shopModel",shModel);
shop.addObject("shopModel", shModel);
return new ModelAndView("edit","shopModel",shModel);
}
edit.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<body>
<h2>Hello World!</h2>
<form>
<h1>Success</h1>
edit page
<c:out value="${id}" />
</form>
</body>
</html>
Edit.jsp Page Imge
edit jsp page image
As editVal is a string, you can access it <c:out value="${shopModel}" />
If its a list of string, then the following can be used
<c:forEach var="shop" items="${shopModel}">
<c:out value="${shop}" />
</c:forEach>
If its a list of objects, then var.<object attribute name> as follows
<c:forEach items="${shopModel}" var="shop">
<tr>
<td>${shop.name}</td>
<td>${shop.number}</td>
...
</tr>
</c:forEach>
I'm trying to use the following class in a JSP-based custom tag:
public class HelloWorldTest {
public void hello1() { }
}
The tag file is in WEB-INF/tags/hello.tag:
<%# tag language="java" pageEncoding="ISO-8859-1" %>
<% HelloWorldTest hello; %>
I'm trying to use the tag from index.jsp:
<%#taglib tagdir="/WEB-INF/tags" prefix="my"%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<my:hello></my:hello>
</body>
</html>
I get the following exception:
org.apache.jasper.JasperException: java.lang.ClassNotFoundException: org.apache.jsp.index_jsp
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:178)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:370)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
The problem is trying to use the HelloWorldTest class, because a tag without it works fine:
<%# tag language="java" pageEncoding="ISO-8859-1" %>
<% for(int i = 0; i < 5; i++) { %>
<%= i %>
<% } %>
You need to actually import the class with an import directive.
<%# page import="my.package.HelloWorld" %>
(Where my.package is replaced with your class's actual package.)
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}"/>
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>