how to iterate an ArrayList in JSP - java

I create a JSP which call a java method and get an object ArrayList. I want to display the result in a table but nothing appeared. The jsp is like below:
<%# 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"%>
<%# page import="SCOfetch.*" %>
<%# page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>First Page</title>
<% JCOtest connection1 = new JCOtest(); %>
<%
ArrayList<CompanyRecord> list = new ArrayList<CompanyRecord>();
list = connection1.step4QueryTable();
%>
</head>
<body>
<c:forEach var="row" items="${list.rows}">
<tr>
<td><c:out value="${row.getValue(Name)}"/></td>
<td><c:out value="${row.getValue(Code)}"/></td>
</tr>
</c:forEach>
</body>
</html>
The java code of CompanyRecord class is
public class CompanyRecord {
private String Code;
private String Name;
public void setValue(String value,String column)
{
if (column.equals("Code"))
{
Code=value;
}
else
{
Name=value;
}
}
public String getValue(String column)
{
if (column.equals("Code"))
{
return Code;
}
else
{
return Name;
}
}
}
what's the correct way to call an ArrayList lineitem's method? Thanks.

please find the below code for iterate ArrayList in JSP.
and please don't create the ArrayList in JSP.please create ArrayList and set before calling JSP from the servlet.
<%# 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"%>
<%# page import="SCOfetch.*" %>
<%# page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>First Page</title>
<% JCOtest connection1 = new JCOtest(); %>
<%
ArrayList<CompanyRecord> list = new ArrayList<CompanyRecord>();
list = connection1.step4QueryTable();
%>
</head>
<body>
<c:forEach items="${list}" var="row">
<tr>
<td>${row.Name}</td> <!-- use variable name same like in DTO -->
<td>${row.Code}</td>
</tr>
</c:forEach>
</body>
</html>
AND please generate getter methods in CompanyRecord DTO class the only this code will work fine.
public class CompanyRecord {
private String Code;
private String Name;
public void setValue(String value,String column)
{
if (column.equals("Code"))
{
Code=value;
}
else
{
Name=value;
}
}
public String getValue(String column)
{
if (column.equals("Code"))
{
return Code;
}
else
{
return Name;
}
}
public String getCode()
{
return this.Code;
}
public String getName()
{
return this.Name;
}
}

Related

getting null while using request.setattriubute value in struts2

I am working on struts2 but getting issue in the jsp while accessing a variable in form class using a set variable inside property tag.
Please find the below full code.
Testactionform.java
public class Testactionform {
String name = "india";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
TestAction.java
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
public class TestAction implements SessionAware
{
public Testactionform test;
public Testactionform getTest() {
return test;
}
public void setTest(Testactionform test) {
this.test = test;
}
private Map<String, Object> session;
public Map<String, Object> getSession() {
return session;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public String execute()
{
final HttpServletRequest request = ServletActionContext.getRequest();
test=new Testactionform();
request.setAttribute("name1", "name");
test.setName("london");
session.put("Testactionform",test);
System.out.println("execute() method called");
return"success";
}
}
Success.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>error page</h1>
<s:set var="name2" value="#request.name1"></s:set>
<s:property value="%{#session.Testactionform.name2}"/>
</body>
</html>
In JSP with below line, I want to access the name variable in Testactionform, but I get nothing in the response.
<s:property value="%{#session.Testactionform.name2}"/>
Below is the command which is working fine for me .
<s:property value="#session.Testactionform[#name2]"/>

Problem with displaying List by jsp in Java

Hi i have a problem with my project,That's my posts.jsp
<!DOCTYPE html>
<html>
<head>
<title>Blog Site-posts</title>
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Description</th>
<th>Date</th>
<th>Completed</th>
<th>Written by</th>
</tr>
</thead>
<tbody>
<c:forEach items="${posts}" var="Post">
<tr>
<td>${Post.postId}</td>
<td><fmt:formatDate pattern="dd/MM/yyyy"
value="${post.postDate}" /></td>
<td>${Post.text}</td>
<td>${Post.authorId}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
That's my PostController
#Controller
public class PostController {
#Autowired
PostService postService;
#RequestMapping(value="/posts",method = RequestMethod.GET)
public String showPosts(ModelMap model) {
model.addAttribute("posts",postService.findall());
return "posts";
}
}
and that is my post class
public class Post {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int postId;
//#Column(unique=true)
//#NotEmpty
private String title;
//#Column(length=20000)
#Size(max=20000, message="Message cannot be longer than 20000 characters!")
//#NotEmpty
private String text;
private Date postDate;
private int authorId;
I want to display elements of List with posts in jsp to see how it works , but it looks like this :
enter image description here
What's wrong with jsp or controller?
Add this to posts.jsp before tag html :
<%# 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"%>

Why the class can use undefined members in JSTL?

I am reading JSP tutorial from a book and meeting a program that is hard to understand.
It has two beans, one is Message.java, another is MessageServies.java as below.
package com.jeecourse.model;
public class Message {
private String name;
private String text;
public Message() {
}
public Message(String name, String text) {
this.name = name;
this.text = text;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
And the MessageService.java
package com.jeecourse.model;
public class MessageService {
private Message[] fakeMessages;
public MessageService() {
fakeMessages = new Message[3];
fakeMessages[0] = new Message("Jimmy", "Jimmy's message!");
fakeMessages[1] = new Message("Jack", "Jack's message!");
fakeMessages[2] = new Message("Tom", "Tom's message!");
}
public Message[] getMessages() {
return fakeMessages;
}
}
And finnally the message.jsp with EL:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#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">
<jsp:useBean id="messageService" class="com.jeecourse.model.MessageService"/>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>NoteBook</title>
</head>
<body>
<table style="text-align: left; width: 100%;" border="1">
<tr>
<td>Name</td><td>Message</td>
</tr>
<c: forEach var="message" items="${messageService.messages}">
<tr>
<td>${message.name}</td><td>${message.text}</td>
</tr>
</c: forEach>
</table>
</body>
</html>
Please note here it uses messageService.messages in EL expression. It is very strange that messageService have neither such members, nor such functions. But it can work. Why?
When you write ${messageService.messages} it gets translated at compile time to messageService.getMessages. Just in the same way that ${message.text} is invoking actually message.getText().
For this kind of "magic" it is important to follow some conventions when naming your methods. If not, the compiler won't know which method it should call when you use the abbreviated version.
You can see more about EL here: https://stackoverflow.com/tags/el/info
This feature is at the top of the page.

addFieldError on Struts2 not displaying error on the fields

Hi I m very new to struts2. from some books and websites I got this example. In action class it use validate method to check logic. The method is called bcoz from the print statements. But the error is not shown near to the fields. Jst help me
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!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>Home</title>
</head>
<body>
<s:form action="LoginAction ">
<s:textfield name="username" label="Username" />
<s:textfield name="password" label="Password" />
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>
Struts.xml
<package name="default" extends="struts-default">
<action name="LoginAction" class="org.shammu.struts2.actions.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="input">/index.jsp</result>
</action>
<action name="emptypassthrough">
<result>index.jsp</result>
</action>
</package>
LoginAction.java
package org.shammu.struts2.actions;
import org.shammu.struts2.beans.LoginBean;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")
public class LoginAction extends ActionSupport{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute(){
LoginBean login = new LoginBean();
login.setPassword(password);
login.setUsername(username);
if (getUsername().equals("abcd")) {
return "success";
} else {
return "input";
}
}
#Override
public void validate() {
if (username.length() < 3) {
System.out.print("user err ok");
this.addFieldError(username, "Username Empty Pls provide");
}
if (password.length() < 3) {
System.out.print("Pass err ok");
this.addFieldError(password, "Password Empoty provride one pkls");
}
}
}
I m not considering execute method. I want jst the error msg printed near to fields... Help
To display fielderror you need to add <s:fielderror /> in your jsp.
It Render field errors if they exists. Specific layout depends on the particular theme. The field error strings will be html escaped by default.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!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>Home</title>
</head>
<body>
<s:form action="LoginAction ">
<s:textfield name="username" label="Username" /><s:fielderror fieldName="username"/>
<s:textfield name="password" label="Password" /><s:fielderror fieldName="password"/>
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>
You are not correctly using addFieldError method. The first parameter in that method is a name of the field. In your case it should be "username".
addFieldError("username", "Username Empty Pls provide");

Struts 2 radio button list [duplicate]

This question already has answers here:
Struts 2 select tag with values of a array list
(2 answers)
Closed 6 years ago.
am working on Struts 2 radio button.
I want to retrieve the list from my action class but it is giving following error
org.apache.jasper.JasperException: tag
'radio', field 'list', name
'user.yourGender': The requested list
key '#user.gender' could not be
resolved as a
collection/array/map/enumeration/iterator
type. Example: people or people.{name}
- [unknown location]
my action class & user class is as follow
HelloAction
package com.geekcap.struts2.action;
import com.geekcap.struts2.model.User;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import java.util.ArrayList;
public class HelloAction extends ActionSupport
{
private User user;
public String execute() throws Exception
{
return "success";
}
public void validate()
{
if(user.getName().length()==0)
{
addFieldError("user.name", "User Name is required");
}
if(user.getAge()==0)
{
addFieldError("user.age","Age is required");
}
if(user.getPassword().length()==0)
{
addFieldError("user.password","Please enter your password !");
}
/* if(user.getGender().equals("-1"))
{
addFieldError("user.gender","Please select gender !");
}*/
}
public User getUser()
{
return user;
}
public void setUser(User userbean)
{
user=userbean;
}
}
User class
package com.geekcap.struts2.model;
import java.util.List;
import java.util.ArrayList;
public class User
{
private String name,password;
// private List like;
private int age;
private List<String> gender;
private String yourGender;
public User()
{
gender= new ArrayList<String>();
gender.add("MALE");
gender.add("FEMALE");
gender.add("UNKNOWN");
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password=password;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age=age;
}
public List<String> getGender()
{
return gender;
}
public void setGender(List<String> gender)
{
this.gender=gender;
}
public void setYourGender(String yourGender)
{
this.yourGender=yourGender;
}
public String getYourGender()
{
return yourGender;
}
public String getDefaultGenderValue()
{
return "UNKNOWN";
}
helloForm.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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>Welcome to Struts 2</title>
</head>
<body>
<s:form action="Hello">
<s:textfield name="user.name" label="User name" value="shahid"/>
<s:password name="user.password" label="Password"/>
<s:textfield name="user.age" label="Age"/>
<s:radio label="Gender" name="user.yourGender" list="user.gender" value="defaultGenderValue"/>
<s:submit/>
</s:form>
</body>
</html>
hello.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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>Hello, Struts 2</title>
</head>
<body>
<h4>
Hello, <s:property value="user.name"/>!
<br>Your password :<s:property value="user.password"/></br>
<br>your age :<s:property value="user.age"/></br>
<br>Gender :<s:property value="user.yourGender"/></br>
</h4>
</body>
</html>
Are you sure the list gender is NOT null in the JSP?
If it is null, then struts will not see it and therefore think it isn't there

Categories