I have this class:
public class Orders{
private Integer id;
private String name;
//getters/setters
}
In controller I pass a List<Orders> to jsp:
#RequestMapping(value = "/orders")
public ModelAndView orders(){
List<Orders> orders = ...//get list from db
//print list in console
orders.forEach(e -> System.out.println(e.getId() + " - " + e.getName()));
//print -> 1 - name1 ; 2 - name2
return new ModelAndView("orders", "orders", orders);
}
In jsp use it like this:
${orders.size()}
<c:forEach items="${orders}" var="order">
<c:out value="${order.getId()}"></c:out>
</c:forEach>
In browser at inspect(html code) looks like this:
"2"
<c:foreach items="[com.web.entity.Orders#21e16dd6,
com.web.entity.Orders#52a33913]" var="order">
<c:out value=""></c:out>
</c:foreach>
I tested in controller by printing list in console and everything is right.
Why in jsp is not printed?
Could you please provide more details (controller code, html page tags ...).
Still I've some point to share with you :
Use always a toString method in your Entity/POJO.
Use order.id instead of order.getId()
Make sure you have JSTL core tag in the top of your HTML page :
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Try to have a simple c:out tag:
<c:out value="${order.id}"/>
Related
In my servlet, i have:
List list = new ArrayList();
....
request.getSession().setAttribute("list",list);
RequestDispatcher dispatcher=request.getRequestDispatcher("result.jsp");
dispatcher.forward(request,response);
And in my result.jsp file, i wanted to print out the checks on website, so i tried :
String[] str = (String[])request.getAttribute("list");
But there is a error said
org.apache.jasper.JasperException: java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.String;
So what should i do to print the list?
Thank you.
Actually list is of type ArrayList not an Array, so try this instead :
<%
ArrayList<String> list = (ArrayList<String>) request.getSession().getAttribute("list") ;
//do something ...
%>
And make sure you are allowing your jsp to access to the Session using : <%# page session="true" %>
However as #JBNizet said it's so preferable to use jstl expression over than Java code in the jsp pages :
in the servlet :
List<String> list = new ArrayList<>();
request.setAttribute("list" , list);
RequestDispatcher dispatcher=request.getRequestDispatcher("result.jsp");
dispatcher.forward(request,response);
In the Jsp :
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:forEach items="${list}" var="element">
//use the element here...
${element}
</c:forEach>
I know that in Struts2 can be used json plugin to return a json type result. A json could also be returned from the stream result like in this answer.
On the Struts2 docs page for Ajax result with JSP, I've found that it's possible to return dispatcher type result with JSP that outputs a JSON.
<%# page import="java.util.Iterator,
java.util.List,
com.esolaria.dojoex.Book,
com.esolaria.dojoex.BookManager" %>
<%
String bookIdStr = request.getParameter("bookId");
int bookId = (bookIdStr == null || "".equals(bookIdStr.trim()))
? 0 : Integer.parseInt(bookIdStr);
Book book = BookManager.getBook(bookId);
if (book != null) {
out.println(book.toJSONString());
System.out.println("itis: " + book.toJSONString());
}
%>
But it's using scriptlets to write JSON to the out. I know that using scriplets in JSP is highly discouraged. But I couldn't find the answer for my problem in this question How can I avoid Java code in JSP files, using JSP 2?. How can I use JSP result to generate a JSON object? Is there a better way to return JSON object from JSP?
You can return a JSP through the dispatcher result, then use <s:property /> tag to call an action method that will return the serialized data in the JSP.
You should also express the right contentType for your JSP:
public class DispatcherJsonAction extends ActionSupport {
private Book book;
#Action("dispatcherJson")
#Result(name = ActionSupport.SUCCESS, location = "page.jsp")
public String execute(){
book = loadBookSomeHow();
return SUCCESS;
}
public String getJsonBook(){
Gson gson = new Gson();
try {
return gson.toJson(book);
} catch (Exception e){
return gson.toJson(e.getMessage());
}
}
}
page.jsp:
<%#page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<s:property value="jsonBook" />
Hi I am new to Java world and I am trying to make my own web application with Spring MVC. Now, I am going to read a text file in my local directory, for example, the text file like this:
TestData_FileOne.txt
1,100
2,200
3,300
4,400
5,500
The result I would like to present in a browser page like this (in a table) :
1 2 3 4 5
100 200 300 400 500
so I implemented 1) Controller , 2) Model , and 3)View(.jsp file).
**1) My Controller and 2)Model ([Q1] [Q2]) **
#Controller
public class TestController {
#RequestMapping("/testMVC")
public String testmvc(Model model){
String dirString = "C:/Users/Me/Documents/Test/";
Path testFile;
List<String> testData;
testFile = Paths.get( dirString + "TestData_FileOne.txt");
try {
testData = Files.readAllLines(testFile, StandardCharsets.UTF_8);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//return "unable to read...";
return "unable to read...";
}
// ====== changes from here based on Aeseir's answer========
List<String> dataNum = new ArrayList<String>();
List<String> data = new ArrayList<String>();
for(int i=0; i<testData.size()-1;i++){
dataNum.add(testData.get(i).split(",")[0]);
data.add(testData.get(i).split(",")[1]);
}
model.addAttribute("dataNum", dataNum);
model.addAttribute("data", data);
// ======= changes until here ==============
return "testMVC";
}
}
(Read the text file works fine when I checked System.out.println part)
2) testMVC.jsp file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<table>
<thread>
<tr>
<th>Table with dynamic data from model</th>
</tr>
</thread>
<tbody>
<c:forEach var="dataNumValue" items="${dataNum}"> [items added but.. Q5]
<tr>
<td>
${dataNumValue}
</td>
</tr>
</c:forEach>
<c:forEach var="dataValue" items="${data}"> [items added but.. Q5]
<tr>
<td>
${dataValue} --- [Q2']
</td>
</tr>
</c:forEach>
</tbody>
</table>
So..I know Q1/Q1' should be match, and Q2/Q2' as well.
1) however, I am confused about the object in model.addAttribute("", object); in Q1, Q2? and addAttribute is the right choice among model attributes?
2) Do I need var="dataNum" and var="data" in Q3, Q4 and did I do correctly?
I appreciate any advice if I made mistake.
Extra Question
so I have updated Controller code and jsp file like the above after Aeseir's answer (Thanks!!) but I have warning in jsp file after I added items then warning (Q5) and of course, the page is not presented.
[Q5]: warning : "items" does not support runtime expressions
I searched for the warning, then advices like check the jstl version - should be above version 1.0 - My jstl version is 1.2. so shouldn't be any problem....
Can you check my changes part? and What else could cause this warning except jstl version?.
Solution for extra question 5
#taglib directive should be like this in jsp file:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> => /jsp was missing in the middle
This #taglib correction + code changes the above based on Aeseir's answer works all fine!
Q1 and Q2
You were almost there. Model will pass most data you put into it. Its up to your rendering page to determine how to display it.
And you will need to change the types to arrays since you want to output multiple strings.
List<String> dataNum = //populate accordingly
List<String> data = // populate accoridngly
model.addAttribute("dataNum", dataNum);
model.addAttribute("data", data);
Q3 and Q4
Yes you do but you need to complete it this way:
<c:forEach var="dataNumValue" items="${dataNum}">
<tr>
<td>
${dataNumValue}
</td>
</tr>
</c:forEach>
<c:forEach var="dataValue" items=${data}>
<tr>
<td>
${dataValue}
</td>
</tr>
</c:forEach>
Hope that helps
I just started to use JSTL for my project, but sorry to say it's really confusing to me.
I originally used Number.java
package com.mycompany
public class Number {
private int total;
public static int add (int x, int y) {
return total;
}
And in showNumber.jsp i could just use
<%#page import= "com.mycompany.Number" %>
and inline use <%= Number.add(5,6) %>
How can I rewrite this part in JSTL?
Is that also possible to import the class Number.java?
I tried so many different things, e.g. <c:out value="${Number}.add(5,6)" />, but still cannot find a solution. Thanks.
Edited:
I use #Victor's approach, and it does work. In my case, I need to reuse other's variable from spring framework, say NumberTwo.java and totalTwo as private variable inside. And added "100" to this totalTwo.
For the src where i need to use it is <spring:param name="secondNumber" value ="${NumberTwo.totalTwo}" />.
However, intutively i used (int) pageContext.getAttribute("NumberTwo.totalTwo"), it always returned me null.
The other workaround is
first <c:set var="result" value="${NumberTwo.totalTwo}" />
then <% String result = (String) pageContext.getAttribute("result"); %>
and then <%= Number.add(result, 100) %>
Unfortunately it's not possible to arbitrarily call methods with JSTL, the function capabilities of JSTL are very limited: http://docs.oracle.com/javaee/5/tutorial/doc/bnalg.html . But it's still possible to use your Number class. Here the workaround:
<%#page import= "com.mycompany.Number" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("addResult", Number.add(7, 8));
%>
<html>
<body>
JSP 1.x: Result is: <c:out value="${addResult}" /><br/>
JSP 2.x: Result is: ${addResult}
</body>
</html>
With pageContext.setAttribute() the method result is stored in the page context, and the JSTL tags can access values (attributes) stored in that context.
Note: the second output line "Result is: ${result}" works only with JSP 2 afaik.
You can use the 'usebean' tag as in the following example:
<?xml version="1.0"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- UseBean.jsp
Copyright (c) 2002 by Dr. Herong Yang
-->
<html><body>
<jsp:directive.page import="CacheBean"/>
<jsp:useBean id="b" class="CacheBean"/>
<jsp:setProperty name="b" property="text" value="Hello world!"/>
Property from my Bean:
<jsp:getProperty name="b" property="text"/>
<br/>
Info from my Bean:
<jsp:expression>b.getInfo()</jsp:expression>
</body></html>
</jsp:root>
Where:
/**
* CacheBean.java
* Copyright (c) 2002 by Dr. Herong Yang. All rights reserved.
*/
public class CacheBean {
private String text = "null";
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getInfo() {
return "My JavaBean - Version 1.00"
}
}
CREDIT TO: http://www.herongyang.com/jsp/usebean.html
Please look at EL functions in BalusC's answer at
Hidden features of JSP/Servlet
also
look at "Using Custom Methods in EL" at
http://www.roseindia.net/jstl/jstl-el.shtml
look at Functions at
http://docs.oracle.com/javaee/5/tutorial/doc/bnahq.html
i was searching for the same problem as mine, but i didn't find anything. This is my problem:
I have ArrayList which includes beans. My beans is class 'Row'. There are setters and getters.
This is method from Database class:
public ArrayList<Row> getDatalist() {
datalist = new ArrayList<Row>();
try {
String query = "SELECT * FROM ...";
ResultSet r = s.executeQuery(query);
while(r.next()) {
Row row = new Row();
row.setLocation(r.getString(4));
row.setVolume(r.getInt(3));
row.setTime(r.getTime(5));
row.setDate(r.getDate(5));
datalist.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return datalist;
}
My servlet:
ArrayList<Row> rows = db.getDatalist();
request.setAttribute("rows", rows);
request.getRequestDispatcher("/main.jsp").forward(request,response);
And at least 'main.jsp':
<c:forEach var="row" items="${rows}">
<c:out value="${row.location}"></c:out>
</c:forEach>
The problem is that ${row.location} is empty. My page source:
<c:forEach var="row" items="[webservice.model.Row#1e41769, webservice.model.Row#1bd0815, webservice.model.Row#15dd716, webservice.model.Row#1d40d08]">
<c:out value=""></c:out>
</c:forEach>
Any idea? Thanks a lot.
Well, your page source indicates the problem clearly: the c tags aren't interpreted by the container. This means that you forgot to declare the c taglib at the top of the JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
be sure you have set this:
<%# page isELEnabled ="true"%>
to make el expression enable。