NullPointerException when iterating over ArrayList in jsp - java

I am displaying a list which contains objects which store message information. The list is loaded through getting the request as such:
ArrayList<MessageModel> list = (ArrayList<MessageModel>) request.getAttribute("msgList");
I am trying to display information contained in each object as such:
for(MessageModel msg : list){
String messageTo = msg.toAddress;
String messageSub = msg.messageSubject;
out.println(messageTo+ " " +messageSub);
}
I am getting a NullPointerException at the for each statement.
As an aside, I am using this approach to debug as I want to check whether or not I can display the content of the MessageModel object at all. I tried using JSTL forEach tag but I could not access the object attributes.
<c:forEach items="${list}" var="current">
<li><c:out value="${current.toAddress}"/></li>
</c:forEach>
I set the attribute like this :
ArrayList<MessageModel> list =(ArrayList<MessageModel>) request.getAttribute("msgList");
pageContext.setAttribute("messages", list);
This results in the following error message when run :
org.apache.jasper.JasperException: /inbox.jsp (line: 37, column: 12) According to TLD or attribute directive in tag file, attribute items does not accept any expressions
And intelliJ says that it cannot resolve the variable list.
EDIT :
I forward the request from a servlet that handles user login as follows :
ArrayList<MessageModel> msglist = MessageModel.getRecievedMessages(username);
request.setAttribute("msgList", msglist);
I am trying to pass the ArrayList that contains the message objects and then iterate over the list and display it in the jsp.
Is there a possibility for the jsp itself to get the information ? I have a separate java class which handles the messages with a bunch of helper functions. So can I call the method that retrieves all those messages and display them without explicitly setting a request attribute in the servlet ? Because I will be navigating between other pages in the application.
Sorry if my vocabulary was off, this is the first time I am working with jsp's and servlets.

The NullPointerException in the foreach loop is probably due to the list variable being null. You may check for listnot being null before iterating over it.
Regarding the JasperException, can you describe how you forward to the JSP ?
Also, it's probably a typo, but you set an attribute named messages, then you iterate over an attribute named list in the <c:foreach>...

I solved this problem by using creating getter and setter methods to get the class members of MessageModel.
EL tag wiki: this article helped me understand how to interface a java class and a jsp.

Related

How do I set multiple attributes to request in a servlet and then read them on JSP?

I am new to JSP. Have tried a lot of things to no avail. Please help me know what can be the possible problem in this code?
Servlet Code
request.setAttribute("list", list);
request.setAttribute("rows",totalRows);
request.getRequestDispatcher("sample.jsp").forward(request, response);
Here, list is a collection of a custom datatype and totalRows holds an integer number. I am trying to set these attributes to the request so as to be able to manipulate them on my JSP, sample.jsp:
Sample.jsp
List rulesList = (List) request.getAttribute("list");
request.setAttribute("rulesList", rulesList);
String rowCount=(String)request.getAttribute("rows");
request.setAttribute("rowCount",rowCount);
I am unable to fetch the rowCount on JSP . rulesList works fine. Please help.
you need to use .toString(); like.... String rowCount=request.getAttribute("rows").toString();
and for list you can refer bellow sample code :-
List<String> result = (List) request.getAttribute("redultList");

Getting a set attribute in a jsp page

I have an attribute which is is set in a jsp page and would like to know how this is called in a java program and how this would be used in that program (e.g. as a string in a class)
You'll have to convert it to a List and then pass it through.
You can use List.addAll() function.
Set yourSet = new HashSet();
List yourList = new ArrayList();
yourList.addAll(yourSet);
return yourList;
try this
<%request.getAttribute("attrubuteName")%>
use scriptlets in you jsp page and access the attributes using request object.

JSP Request Parameter truncated after passing to javascript function

I have an issue with a parameter that I'm trying to pass into a Javascript function where the parameter gets cut off.
In my Servlet, I have set a parameter request.setAttribute("questions", service.getQuestions("123"))
It sets a list of questions with each question containing several values;
I loop through them with a JSTL loop <c:forEach var="data" items="${questions}">...</c:forEach> which I can then access the values as so ${data.question}, ${data.options} etc.
console.log(${data.question}) returns a value of the form 123,45,35|43,94,73|23,91,34 which is as expected.
But when I try to pass this ${data.question} into a javascript function such as <script>MyFunction(${data.question})</script>, it only receives 123.
MyFunction(data) {
console.log(data); //Only shows 123
//Split the string into arrays for processing
}
You receive first element becouse your function expect one parameter, and your value 123,45,35|43,94,73|23,91,34 is split by comma so it looks for function like diferent parametrs. Use arguments property insted or pass all value as string in '' like this
<script>MyFunction('${data.question}')</script>
Sorry for my english.. still working on it

creating array in javascript from array object pass in by request.setAttribute in servlet

i'm trying to create a dynamic photo gallery which retrieve the photo's location from mySQL. Store the location to a photo object under the name 'private String location;'
There will be an ArrayList to hold all the different photos. After, the servlet will forward to a jsp page
request.setAttribute("list", list);
request.getRequestDispatcher("car.jsp").forward(request, response);
i have a java script for the photo gallery that takes in an array of, ["path_to_image", "optional_link", "optional_linktarget", "optional_textdescription"].
imagearray: [
["path_to_image", "optional_link", "optional_linktarget", "optional_textdescription"],
["a.jpg", "www.a.com", "", ""]
],
I would like to retrieve the location from the object in the list passed in from the servlet and convert it into the imagearray for my photo gallery to work.
I'm quite new to javascript and i've been looking around for similar example or tutorial but i couldn't find any relevant ones. Please help me out, thank you so much for your time.
what i get from your question is photo is an object of a class and location is a member variable of that class.
request.setAttribute("list", list);
request.getRequestDispatcher("car.jsp").forward(request, response);
is this list is a Arraylist of photo object or location member variable.
also you are setting attribute in java and you want that list to hold by javascript.
then in that case you can check JSON for holding your java object and to convert into javascript object.
you will get your string in JSON similar to
{imagearray:[{"path_to_image":"path_to_image","optional_link":"optional_link","optional_linktarget":"optional_linktarget","optional_textdescription"}]}
What you want to do can be simply achieved by the following sequence:
Get results from a database.
Create JSON object.
Set that object as request attribute.
Assign JSON to a JavaScript variable.
Now, let's carry on doing that list.
Get results from database
You should have a method of type getPhotoList() that returns List<Photo>. I suppose that your Photo class has the fields you'd like to export to JavaScript. In the end, you'll have List<Photo> photos initialized.
Create a JSON object
You can of course do that on your own, but a much better idea is to employ a specialized library that converts a java object to a JSON object. For example, you could use Gson library, which is a known library for that type of conversions. In the end, you'll have a JSON object, by calling String photosJSON = new Gson().toJson(photos);.
Set the JSON as a request attribute and perform a forward
Standard operation here.
request.setAttribute("photos", photosJSON);
request.getRequestDispatcher("car.jsp").forward(request, response);
Assign JSON to a JavaScript variable
In your JSP code, within a <script> block, have the following line:
var photosJS = JSON.parse(${photos});
Finally, you'll have a JS variable photosJS with a list you got from the database.

Look for string in arraylist element and pair it with specific image

Im trying to do a MVC application with Model , JSP and Servlet.
From my Model I get an arrayList:
ArrayList<String> myArrayList = new ArrayList<String>();
Each element look like this example: 96125;www.qwerty.com
Lets say I have a image named: www.qwerty.com.png
I want to take myArrayList pass it from my servlet to the jsp. So lets say I call for myArrayList[0] and the first element is 96125;www.qwerty.com I want it to show the image www.qwerty.com.png in my JSP instead of the actual element.
How can I solve this?
For getting just the image name, you can use split method of String Class:
myArrayList[0].split(";")[1]

Categories

Resources