Spring model attribute/jsp not visible - java

Learning spring + jsp.
I am setting a model attribute in a method in a controller
#RequestMapping("/viewExpenses")
public String viewAllExpenses(Model model){
List<Expense> expenses;
expenses = expenseService.getAllExpenses();
model.addAttribute(expenses);
for(Expense e : expenses)
System.out.println(e);
return "viewExpenses";
}
where expenses size is > 1
Following is my jsp page:
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>
</head>
<body>
<h2>
Hello ${user.firstName} <br> HOME
</h2>
<div>All Expenses</div>
<span style=""></span>
<c:forEach var="expense" items="${expenses}">
<c:out value="${expense.expenseId}"></c:out>
<c:out value="${expense.expenseName}"></c:out>
<c:out value="${expense.expenseType}"></c:out>
<c:out value="${expense.expensePrice}"></c:out>
<c:out value="${expense.purchaseDate}"></c:out>
<c:out value="${expense.expenseComments}"></c:out>
</c:forEach>
</body>
</html>
Following is my output from the jsp(no errors):
Hello Pravat
HOME
All Expenses
I wonder why the expenses are not populated in my jsp

You need to give your attribute an attribute name:
model.addAttribute("expenses", expenses);
Background:
When a name is not supplied, Spring uses a generated name which is not the same as the variable name. The docs explain this:
Determine the conventional variable name for the supplied Object based on its concrete type. The convention used is to return the uncapitalized short name of the Class, according to JavaBeans property naming rules: So, com.myapp.Product becomes product; com.myapp.MyProduct becomes myProduct; com.myapp.UKProduct becomes UKProduct.

Give it a name
model.addAttribute("expenses", expenses);
Return ModelAndView.
Always enclose body of if/for/etc into { } even it's single-lined.

Related

For each loop with Expression Language

I want to print out every Item of my list "sorts" with Expression Language in a JSP File like that:
Try: Pizza-Margherita
Try: Cheese-Pizza
So it works if i use a normal expression like this
Try: ${sorts[0]}
Try: ${sorts[1]}
But i have to write it for every Item in the List
So I tried to use following two Loops:
<c:forEach items="${sorts}" var="item">
Try: ${item}<br>
</c:forEach>
<c:forEach var="item" items="${sorts}">
<td>
Try: <c:out value="${item}" />
</td>
</c:forEach>
It didn't work and I got this output each time:
Try:
Why won't my foreach loop work? what have I done wrong?
It is because you haven't included the core tag library in your JSP file.
You will do this by inserting following Line at the top of your file.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Here is sample JSP
<%# 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"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<c:forEach var="item" items="${sorts}">
${item.name}
</c:forEach>
</body>
</html>
Here is Sample Java Code
List<Sort> sortList = new ArrayList<>();
Sort s1 = new Sort();
s1.setName("Pizza-Margherita");
Sort s2 = new Sort();
s2.setName("Cheese-Pizza");
sortList.add(s1);
sortList.add(s2);
request.setAttribute("sorts", sortList);
Sample Object class
public class Sort {
private String name;
//create getter and setter for name
}
Make sure you have imported JSTL Library.

Set locale for JSP page in Openfire

I have a plugin for Openfire. There is a JSP page inside it, and I want the locale on this page to be different from the global locale.
I tried this:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
String locale = ParamUtils.getParameter(request, "locale");
%>
<html>
<head>
<title>Page</title>
</head>
<body>
<fmt:setLocale value="<%=locale%>" scope="session"/>
<fmt:message key="hello.world"/> <br>
</body>
</html>
But it doesn't work.
When I switch the global locale, my JSP page shows me right language. But I don't want to change the global locale, I only want to change it for this page.
What can I do to make this work?

How to link different URLs to different items in forEach loop in JSP page? [duplicate]

This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 7 years ago.
I have a facultylist.jsp page which displays List<Faculty> as a request attribute parameter in forEach loop and I want every item in this loop to be a link to specified faculty facultyview.jsp. How can I achieve that ?
facultylist.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculties</title>
</head>
<body>
<h1>Faculties list</h1>
<ul>
<c:forEach var="faculty" items="${faculties}">
<li>${faculty.name}</li>
</c:forEach>
</ul>
</body>
</html>
facultyview.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculty</title>
</head>
<body>
<h1>${faculty.name}</h1>
<ul>
<li>Faculty name: <c:out value="${requestScope.name}"></c:out></li>
<li>Total seats: <c:out value="${requestScope.total_seats}"></c:out></li>
<li>Budget seats: <c:out value="${requestScope.budget_seats}"></c:out></li>
</ul>
apply for this faculty
</body>
</html>
I don't know if its may help, but I'm using following technologies: tomcat, jsp, servlets and log4j.In my project I have one FrontController, which is a servlet that interacts with Command pattern - each Command returns a path to resource and action type: forward or redirect.
You can solve your issue by adding a query params to the link, edit with respect to the comment. Note that you cannot access directly the JSP pages that reside under WEB-INF folder. Also, to encode properly the paramters, better construct url like
<c:url value="facultyview.jsp" var="url">
<c:param name="name" value="${faculty.name}"/>
<c:param name="total_seats" value="${faculty.total_seats}"/>
<c:param name="budget_seats" value="${faculty.budget_seats}"/>
</c:url>
<li>${faculty.name}</li>
and than than in your facultyview.jsp read from the query params
<li>Faculty name: ${param.name}</li>
<li>Total seats: ${param.total_seats}</li>
<li>Budget seats:${param.budget_seats}</li>
This direct JSP communication should solve your immediate issue, but a truly proper way would be to pass an id of a faculty to servlet, fetch the faculty instance, place in the model and pass to the view.
in other way is just take the selected value from the drop down with a name and forward it to front controller servlet ,there use if else conditions and depends on the value you could forward the request to corresponding jsp or servlet
<select name="value"> in jsp
String value=req.getParameter("value"); in servlet
if()
else if()
If you have a field in Faculty entity simply:
${faculty.name}
#Mark: faculty represents an entity from database, i'm not sure if I want to change it adding another field, or you mean some other way ?
Add a field does not means you must change database, you can have a Helper entity that inherits from Faculty and have more fields you can need,
public class FacultyFormHelper extends Faculty implements Serializable {
private String URL;
and in your view:
${facultyHelper.name}
But, If you don't want to modify your database, either create a helper class, you may add onclick event to the <a>
<a onclick="goToURL(${faculty.id})">
Then retrieve the data... i'm not sure how you get the urls... from a variable in the view, ajax call or wherever you have this URL...

Google App Engine: Get source link to entity property

I'm new to Google App Engine so I was hoping that you could help me here.
I'm trying to get the source link to a property of an entity (want to download a json), but can't figure out how.
This is the code:
<%-- //[START all]--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="com.google.appengine.api.users.User" %>
<%# page import="com.google.appengine.api.users.UserService" %>
<%# page import="com.google.appengine.api.users.UserServiceFactory" %>
<%-- //[START imports]--%>
<%# page import="com.google.appengine.api.datastore.DatastoreService" %>
<%# page import="com.google.appengine.api.datastore.DatastoreServiceFactory" %>
<%# page import="com.google.appengine.api.datastore.Entity" %>
<%# page import="com.google.appengine.api.datastore.FetchOptions" %>
<%# page import="com.google.appengine.api.datastore.Key" %>
<%# page import="com.google.appengine.api.datastore.KeyFactory" %>
<%# page import="com.google.appengine.api.datastore.Query" %>
<%-- //[END imports]--%>
<%# page import="java.util.List" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Mandatory Assigment 2</title>
</head>
<body>
<h1>Mandatory Assignment 2</h1>
<p>This page shows the CSV files uploaded</p>
<h2>Uploaded CSV files</h2>
<%-- //[START datastore]--%>
<%
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key guestbookKey = KeyFactory.createKey("Guestbook", "guestbookName");
// Run an ancestor query to ensure we see the most up-to-date
// view of the Greetings belonging to the selected Guestbook.
Query query = new Query("Greeting", guestbookKey).addSort("date", Query.SortDirection.DESCENDING);
List<Entity> greetings = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
if (greetings.isEmpty()) {
%>
<p>There are no CSV files. Please refresh to reload</p>
<%
} else {
%>
<p>CSV files: </p>
<%
for (Entity greeting : greetings) {
pageContext.setAttribute("greeting_content",
greeting.getProperty("content"));
if (greeting.getProperty("user") == null) {
%>
<p>An anonymous person wrote:</p>
<%
} else {
pageContext.setAttribute("greeting_user",
greeting.getProperty("user"));
%>
<p>json string: ${fn:escapeXml(greeting_content)}</a></a></p>
<%
}
%>
<blockquote></blockquote>
<%
}
}
%>
</body>
</html>
<%-- //[END all]--%>
The "${fn:escapeXml(greeting_content)}" code outputs the json as a String, but I would like to be able to download the json instead like this:
<p>download JSON</a></p>
Can someone help me? I'd appreciate it!
Try this code:
<p>download JSON</a></p>
Adding download attribute you can make content downloadable in the format you specified

Including JSP file within another JSP file

I'm writing a wizard for creating a user in my application with Spring MVC. At each step the controller will set session attributes for the completed wizard fields.
I want the wizard to look the same regardless of which page it's on, except for each page's fields, obviously. For example, menus and links at the top of the page and buttons at the bottom should remain the same.
I have the following JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Create a new User</title>
</head>
<body>
<h1>User Creation Wizard</h1>
Step <c:out value = "${pageNum}"/>/<c:out value = "${pageMax}"/>
<form action="" method="POST">
<jsp:include page="userform${pageView}.jsp"/>
<input name = "currentPage" type = "hidden" value = "${pageNum}"/>
<c:if test = "${pageNum > 1}">
<input name = "prev" type = "submit" value = "Previous" />
</c:if>
<c:if test = "${pageNum < pageMax}">
<input name = "next" type = "submit" value = "Next" />
</c:if>
<c:if test = "${pageNum == pageMax}">
<input name = "submit" type = "submit" value = "Finish" />
</c:if>
</form>
</body>
</html>
In the jsp I'm including, do I need to remove the <html>, <head>, and <body> tags? The above code is based on this example.
Yes, you'd need to remove the <html>, <head> and <body> tags from the included JSP file. As they'd already be present in the including file keeping them would result in invalid HTML.
Only the content that you want to vary would be in the JSP file you're including. Everything else, including the necessary <html>, <head> and <body> tags, would be in the JSP file that does the including.

Categories