c:foreach doesn't print objects - java

I'm extremely new to JSP. Anyway, I'm trying to print every object in a list using c:foreach but it does not work and I can't figure out why. I've already checked out similar issues but nothing has solved my problem.
<h2>
Your account information:
<%
LinkedList<BankAccount> accounts = null;
accounts = account1.getAccountList();
request.setAttribute("accounts", account1.getAccountList());
%>
</h2>
<c:foreach items="${accounts}" var="acct">
<p>${acct.accountName}</p><br/>
<p>$${acct.AccountBalance}</p><br/>
</c:foreach>
<TD valign="top"><B><%=accounts.get(0).accountName%></b><br>
<TD valign="top"><b>$<%=accounts.get(0).AccountBalance%></b></br>
</br></br>
<TD valign="top"><b><%=accounts.get(1).accountName%></b><br>
<TD valign="top"><b>$<%=accounts.get(1).AccountBalance%></b></br>
The bottom code works --- accounts.get(0), etc. But I can't use this because if I add data to the database then I have to add more code every time.
Thanks for the help.

You didn't provide info about your BankAccount class, therefore i would make an assumption:
package testingThings.EL.linkedlist;
public class BankAccount {
protected String accountName;
protected double accountBalance;
public BankAccount(String accountName, double accountBalance) {
this.accountName = accountName;
this.accountBalance = accountBalance;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double accountBalance) {
this.accountBalance = accountBalance;
}
}
I changed AccountBalance accountBalance to stick to the conventions.
In your JSP you need the line that LeHill mentioned.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Don't forget the protocol: http://
The JSP:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="testingThings.EL.linkedlist.BankAccount"%>
<%# page import="java.util.LinkedList"%>
<%# 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
LinkedList<BankAccount> accounts = new LinkedList<BankAccount>();
accounts.add(new BankAccount("acc1", 1000.00));
accounts.add(new BankAccount("acc2", 2000.00));
pageContext.setAttribute("accounts", accounts);
%>
<c:forEach items="${accounts}" var="acct">
<p>${acct.accountName}</p>
<br />
<p>${acct.accountBalance}</p>
<br />
</c:forEach>
</body>
</html>
The Output in Browser:
acc1
1000.0
acc2
2000.0

It looks like you don't have getters and setters.
Your scriptlet has the attribute name as "accountName".
JSTL expects "get" or "is" as the beggining of the beans method name.
you can't call the attribute directly. You have to use getter methods.
if you created a method called "getAccountName" it should work.

Related

How to pass the values from Spring controller to JSP

I have Spring controller and I am setting a model value and want to display in my JSP:
public class TestController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(Model model){
model.addAttribute("message", "Programmer Gate");
return "/test";
}
}
My test.jsp code:
<%# 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>
<title>Welcome</title>
</head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<p>${message}</p>
</body>
</html>
I am not seeing the message value as the JSP rendering as follows:
Well, life goes on ...
(0.3343913194169942)
${message}
How to access the model message variable value in the JSP?

Why can't I retrieve an attribute from the Model but I'm able to from JSP?

I'm learning spring mvc and understand the use of the Model and ModelAttribute. However, I can't retrieve the Model's attribute so I resorted to using the JSP param value. What am I doing wrong? I checked the model still had a value for the attribute using #ModelAttribute("username") User user / user.username and sure enough it does.
Controller
package login.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class LoginUser {
#RequestMapping("/")
public String showMenu()
{
return "menu";
}
#RequestMapping("login")
public String loginUser(Model model)
{
User newUser = new User();
model.addAttribute("user", newUser);
return "login-user";
}
#RequestMapping("processUser")
public String processUser(Model model)
{
Option newOption = new Option();
model.addAttribute("option", newOption);
return "process-login";
}
}
User
package login.user;
public class User {
private String username;
private char password[];
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public char[] getPassword() {
return password;
}
public void setPassword(char[] password) {
this.password = password;
}
}
login-user.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"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value="/resources/css/style.css" />" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login User</title>
</head>
<body>
<div>
<form:form action="processUser" modelAttribute="user">
<table>
<tr>
<td>Username:</td>
<td>
<form:input path="username" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<form:input type="password" path="password" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="Login" />
</td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
process-login.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"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="option">
<h3>Welcome ${param.username}. Please choose an activity below</h3> <---- changed from ${user.username}
<div>
<form:select path="option">
<form:option value="Email" label="Email"></form:option>
<form:option value="Enter Recipe" label="Enter Recipe"></form:option>
<form:option value="Retrieve Recipe" label="Retrieve Recipe"></form:option>
</form:select>
</div>
</form:form>
</body>
</html>
Just change your last #RequestMapping method as follows:
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user, Model model)
{
Option newOption = new Option();
model.addAttribute("user", user);
model.addAttribute("option", newOption);
return "process-login";
}
Now use ${user.username} in jsp.
The spring model data is stored in the standard Java request scope. If you are trying to get the username, you need to add it in the request scope again. So, you can write the processUser method as follows.
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user,Model model)
{
Option newOption = new Option();
// do stuff with user data
newOption.setUsername(user.getUsername());
model.addAttribute("option", newOption);
return "process-login";
}
So, you should be able to get it in the jsp as ${option.username}.

Modifying existing object in one JSP file in another

I want to add another user in registration JSP file to my HashMap which is created in my homepage, but it seems the another HashMap is being created when I'm trying to register user.
How to access the HashMap from homepage JSP file in another?
This is my base class:
package com.jakub.spring;
import java.util.HashMap;
public class registeredUsers {
public HashMap<String, String> userSource;
public registeredUsers() {
userSource=new HashMap<String, String>();
}
public void register(String name, String password) {
userSource.put(name, password);
}
public String userExists(String user) {
String passwordFromSource = userSource.get(user);
if(passwordFromSource != null) {
return passwordFromSource;
}else
return "";
}
}
This is my homepage:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body bgcolor="#CCCFFF">
<form method="post" action="validate.jsp">
<p align="left">Podaj login:</p>
<input type="text" name="name" />
<p align="left">Podaj haslo:</p>
<input type="text" name="password" />
<input type="submit" value="Zaloguj" />
</form>
Rejestracja
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
out.println("Dostepni uzytkownicy w systemie: \n");
out.print(registeredUsers.userSource.keySet());
%>
</body>
</html>
This is my registration page:
<%# page language="java" contentType="text/html; charset=ISO-8859-2"
pageEncoding="ISO-8859-2"%>
<!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-2">
<title>Konto utworzone</title>
</head>
<body>
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
registeredUsers.register(request.getParameter("name"),request.getParameter("password"));
out.print("Konto zostało utworzone");
out.print(registeredUsers.userSource.keySet());
%>
Powrót do strony glownej
</body>
</html>
Use ConcurrentHashMap instead of HashMap because it's in Application scope and that can be accessed simultaneously by multiple threads at a time and it results in ConcurrentModificationException.
Please have a look at Thread Safe JSP-Servlet Q&A

PrintWriter output to jsp page inside body tag

This is the code to print to my jsp page. However I have other code in the page. When I call this function I want it to print the message right after where it is called. I can't check for sure because I am using xhtml negotiation, but I suspect it prints after the /html tag.
This is my function
public Print(HttpServletRequest request,HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
};
This is where I call it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<%# page import="com.otrocol.app.*" %>
<%
Print(request, response);
%>
</body>
</html>
This is what I think the result is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
</body>
</html>
"haha"
This is what I want the response to be:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
"haha"
</body>
</html>
This is the error I get:
The JSP uses its own PrintWriter, the JspWriter out. So pass this to the (static) function.
Otherwise you are taking a second writer, and with buffering everything goes haywire.
Also as output already did happen do not set the content type in the function.
At the top of the JSP is a nice location, also for the imports.
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
When having one writer the function would print at the correct spot in the body.
Nice intuition about the cause. BTW begin a function name with a small letter.
It's not a direct answer to your question but I believe what you're doing will cause you nothing but pain even if you get it to work. You're not using the right tool for the job; creating custom JSP tags is a better option for writing to JSP from Java code.
Code example:
register.jsp
<%# taglib prefix="custom" uri="/WEB-INF/custom-tags.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<p>
<c:out value="${custom:printHaha()}" />
</p>
</body>
</html>
custom-tags.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0"
xmlns="http://java.sun.com/xml/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<tlibversion>1.0</tlibversion>
<jspversion>2.0</jspversion>
<shortname>custom-taglib</shortname>
<uri>CustomTags</uri>
<function>
<name>printHaha</name>
<function-class>com.yourpackage.Tags</function-class>
<function-signature>
java.lang.String print()
</function-signature>
</function>
(...)
Tags.class
public class Tags {
public static String print() {
return "haha";
}
}
More info on Tags: official docs
I din't check your code ... you can't do a out.print again using get writer in a jsp page ... because the response for this request is already committed by rendering the jsp
now to print something on asp you can do this any number of ways
print by expression tag
use out (which is an object the server creates)
out.print("Blah...");
and more
to understand what happens to a jsp look into /work/catalina/blah.../
There are two pages. The first one is the Main Page. This one performs some
pseudo calcs.
Based on those calcs, either Success.jsp or Failure.jsp is returned.
This code will do what you wanted to have achieved.....
Even though as the others pointed out, there are more advanced techniques as of
late, still in order to dance, first you have to know the moves....
Primarily look at this
cObj.Print(request, response); in the 2nd jsp page.
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP and JavaBean</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%
int x=cObj.setStoreCust();
if(x>=1)
{
%>
<jsp:forward page="Success.jsp" />
<%
}
else
{
%>
<jsp:forward page="Failure.jsp" />
<%
}
%>
</body>
</html>
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<!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>Failure!</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%cObj.Print(request, response);%>
</body>
</html>
Java Bean
package rustler.Beans;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Beany implements Serializable
{
public Beany()
{
}
/**
*
*/
private static final long serialVersionUID = 1L;
private String custID;
private String custName;
private int qty;
private float price;
private float total;
private int storeCust;
public String getCustID() {
return custID;
}
public void setJunk(String sStr)
{
//System.out.println("What a punk!");
custName = sStr;//"What a punk!";
}
public void Print(HttpServletRequest request,HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
public String prntJunk()
{
//System.out.println("What a punk!");
return custName;//"What a punk!";
}
public void setCustID(String custID) {
this.custID = custID;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public int setStoreCust()
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
PreparedStatement pstmt=null;
String query=null;
query="insert into customer values(?,?,?,?,?)";
pstmt=con.prepareStatement(query);
pstmt.setString(1,custID);
pstmt.setString(2,custName);
pstmt.setInt(3,qty);
pstmt.setFloat(4,price);
pstmt.setFloat(5,total);
int i=pstmt.executeUpdate();
this.storeCust=i;
}
catch(Exception e)
{
}
return storeCust;
}
}

How do I reset a ModelAttribute in Spring 3?

I just started with Spring MVC so it's probably a rookie mistake.
The ModelAttribute is reused every request. How can I make sure every POST starts with a clean object?
My controller (MyController.java):
#Controller
public class MyController {
#RequestMapping(method = RequestMethod.POST)
public String processChoice(#ModelAttribute("myData") MyData myData, BindingResult bindingResult) {
System.out.println("POST: myData = " + myData);
return "redirect:/myview?choice=" + myData.getChoice();
}
#RequestMapping(method = RequestMethod.GET)
public String displayChoice(#RequestParam(required = false) String choice, Model model) {
System.out.println("GET: Choice = " + choice);
model.addAttribute("myData", new MyData(choice));
return "myview";
}
}
My view (myview.jsp):
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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=UTF-8">
<title>Spring Tests</title>
</head>
<body>
<form:form modelAttribute="myData" method="POST">
<form:select path="choice">
<option></option>
<option value="one">One</option>
<option value="two">Two</option>
</form:select>
<input type="submit" value="Choose"/>
</form:form>
<c:if test="${not empty myData.choice}">Choice = ${myData.choice}</c:if>
<c:if test="${empty myData.choice}">No choice</c:if>
</body>
</html>
Successive clicks on the "Choose" button appends the chosen values instead of just POST-ing the current one:
GET: Choice = null
POST: myData = MyData [choice=two]
GET: Choice = two
POST: myData = MyData [choice=two,one]
GET: Choice = two,one
POST: myData = MyData [choice=two,one,]
GET: Choice = two,one,
POST: myData = MyData [choice=two,one,,one]
GET: Choice = two,one,,one
Add this into your controller:
#ModelAttribute("myData")
public MyData getMyData() {
return new MyData();
}

Categories