Iterating over ArrayList in .jsp (MVC2 compliant) - java

I'm writing a web app that uses a servlet to maintain an ArrayList of VideoData objects (these just contain basic information about movies like the title, type of movie, etc).
The servlet puts this List in the request's scope and forwards both the request and response to a jsp (only part of the servlet code is shown here):
public class VideoServlet extends HttpServlet {
private ArrayList<VideoData> library = new ArrayList<VideoData>();
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try {
// put ArrayList in Request's scope
request.setAttribute("the_table", library);
request.getRequestDispatcher("/listvideos.jsp").forward(request,
response);
...
The listvideos.jsp is shown below. I'm getting a Tomcat error stating that the uri for the JSTL cannot be resolved. I've used EL in other parts of my jsp code without having to have any special import line like this, and I'm not sure if JSTL is still the preferred way to solve this type of problem while still trying to adhere to MVC2 and keeping all the Java code in the Servlet. Can anyone point me in the right direction here? Ideally I'd like a pure EL solution, if that's possible.
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'
'http://www.w3.org/TR/html4/loose.dtd'>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Cattle Drive Assignment Servlets-4: Videos</title>
</head>
<body>
<h1>Cattle Drive Assignment Servlets-4: Videos</h1>
<form method='post' action='/videos/VideoServlet'>
Add a video
<br>
<br>
<table border="1">
<tr>
<th>Title</th>
<th>Star</th>
<th>Type</th>
<th>VHS</th>
<th>DVD</th>
<th>Description</th>
</tr>
<c:forEach items="${the_table}" var="movie">
<tr>
<td>${movie.getTitle()}</td>
<td>${movie.getStar()}</td>
<td>${movie.getType()}</td>
<td>${movie.inVHS()}</td>
<td>${movie.inDVD()}</td>
<td>${movie.getDesc()}</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>

Your code looks basically correct. Looks like the error you're seeing indicates that the JSTL taglibs cannot be found in the classpath. Please make sure that jstl.jar and standard.jar are in your war's WEB-INF/lib folder.

Related

How to access a ModelAndView object added without attribute name within the jsp page

I was going through spring MVC tutorials and came across ModelAndView.
My JSP view looks like this,
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC </title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${student.getName()}</td>
</tr>
<tr>
<td>Age</td>
<td>${student.getAge()}</td>
</tr>
<tr>
<td>ID</td>
<td>${student.getBranch()}</td>
</tr>
</table>
</body>
</html>
It worked when I set both attribute name and attribute value in controller like the following,
ModelAndView mv = new ModelAndView();
mv.setViewName("result");
Student student = new Student("arun2", "CSE", 22);
mv.addObject("student",student);
return mv;
Then I came across other overloaded method ModelAndView.addObject(Object attributeValue) and I tried setting only attribute value mv.addObject(student); But this time it doesn't show student details in the browser.
My questions:
Is it possible to access those values in JSP by just setting attribute value as i did second-time mv.addObject(student);.
If yes, How? If not, Why do we have such overloaded method? Why do we need to set only value if we can't access it in the view (JSP)?
I went through the javadocs, But didn't find anything that could make me understand.
Yes, you can do it like that and access the parameters,but need to pay some attention.
Check the API for addObject at ModelAndView,it will shows method as below:
Then,let's look at the definition of ModelMap.addAttribute(Object)
It shows using a generated name,the definition of generated name listed as below:
So,if you just want to use the mv.addObject(student) method,you can access data in your jsp page as below:
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC </title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${student.name}</td>
</tr>
<tr>
<td>Age</td>
<td>${student.age}</td>
</tr>
<tr>
<td>ID</td>
<td>${student.branch}</td>
</tr>
</table>
</body>
</html>
If the object is a Group class, then you can get value via ${group.name}
And pay attention that the ModelAndView is from org.springframework.web.servlet.ModelAndView
Also,I suggest you use the EL Expressions to access data in your jsp page directly.

how can i use servlet in jsp page?

<body>
<form action="testServlet.java">
<TABLE border="0" align="center">
<TR height="40">
<TD width="40"><a href="Hoda/testServlet?direction=b"><img
src=<%=request.getAttribute("imgSrc")%> width="40" height="40" /></a>
</TD>
</form>
</body>
SERVLET:
#WebServlet("/testServlet")
public class testServlet extends HttpServlet {
String imgSrc = "red.png";
protected void service(HttpServletRequest reques,HttpServletResponse response) throws ServletException, IOException {
String str = request.getParameter("direction");
if (str.startsWith("b")) {
imgSrc = "black.png";
}
request.setAttribute("imgSrc", imgSrc);
}
}
In my JSP page, I created a cell whose image source I want to get from servlet. I put the link tag to ask servlet for imgSrc, but it does not work . Please show me how to change the imgSrc in JSP page using servlet. I want the JSP to merely show the result, not a dispatch to another page.
here is my code :
You'll have to use the Servlet API's RequestDispatcher to forward from the Servlet to the JSP so that the processing occurs on the same request, otherwise the attribute won't be set. You could probably also use some custom include logic, but typically you'd use the servlet as a "front" and then use the JSP to render the content. Hopefully this makes sense, you should be able to track the APIs down in the Servlet JavaDoc.
Please refer this post may be can help you.
http://ajax911.com/dynamically-display-images-java-servlet-tomcat/

Getting exception while invoking jsp from a servlet?

i have a jsp. which calls a servlet on jsp load and display the results in same jsp as below.
Some.jsp
<html>
<jsp:include page="/HelloWorld"/>
<%Iterator itr;%>
<% List data= (List)request.getAttribute("results");
for (itr=data.iterator(); itr.hasNext(); )
{
%>
<TABLE align="center" cellpadding="15" border="1" style="background-color: #ffffcc;">
<TR>
<TD align="center"><%=itr.next()%></TD>
</TR>
</TABLE>
<%}%>
</body>
</html>
in servlet i am storing results in request and using requestdispatcher to invoke the jsp as below.
public class SomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
List<String> list = new ArrayList<String>();
//some logic to populate list
request.setAttribute("results", list);
request.getRequestDispatcher("/WEB-INF/Some.jsp").forward(request, response);
}
}
But i am getting below exception while displaying results in jsp:
java.io.IOException: Stream closed
at org.apache.jasper.runtime.JspWriterImpl.ensureOpen(JspWriterImpl.java:202)
at org.apache.jasper.runtime.JspWriterImpl.clearBuffer(JspWriterImpl.java:157)
Please help me..
The JSP includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP...
You have a serious design issue here. Adopt the MVC principles: all requests go to a servlet (Controller), which loads the Model, and dispatches to the appropriate JSP (View). A view should not include a servlet, and certainly not in a recursive way like this.
You can not give servlet url pattern in jsp:iclude tag. The reason is, it doesnt know whther to call get method or ost method. You should give only jsp path.

In a JSP MVC design is it possible to automatically invoke a Command upon page load?

My application has the following patterns: a FrontController, Command, Service, and DAO.
The problem im having is that I want to display a list of users (and their avatars) on my homepage. How do I get my jsp page to automatically call the ListMembersCommand upon page load without a get/post request?
You don't. What you do is you call the controller and have if forward to the JSP. You never call the JSPs directly themselves.
So, what you end up with is:
request --- invokes ---> Controller --- forwards to ---> JSP
The Controller can fetch whatever is necessary and populate the request appropriately before called the JSP to render it all.
Addenda -
Here is a simple Servlet, mapped to /MyServlet :
public class MyServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MemberDAO dao = DAOFactory.getMemberDAO();
List<Member> members = dao.getMembers();
request.setAttribute("members", members);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/jsp/members.jsp");
rd.forward(request, response);
}
}
And here is an associated JSP placed at /WEB-INF/jsp/members.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Members List</title>
</head>
<body>
<h1>Members List</h1>
<table>
<tr>
<td>Member ID</td>
<td>First Name</td>
<td>Last Name</td>
</tr>
<c:forEach items="${members}" var="member">
<tr>
<td>${member.id}</td>
<td>${member.firstName}</td>
<td>${member.lastName}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
In your browser, you hit: http://yourhost/yourapp/MyServlet
The servlet, acting as a controller, takes the request, acts on it (in this case getting a list of all of the members from the database using a simple DAO pattern), and then puts the results in to the request with the tag "members" (the request.setAttribute("members", members) does this).
One the request is properly populated with interesting information, the servlet forward to the JSP.
Note in this case the JSP is located below the WEB-INF directory. JSPs located within WEB-INF are NOT accessible at all from the browser. So a request to http://yourhost/yourapp/WEB-INF/jsp/members.jsp will simply fail.
But they are accessible internally.
So, the Servlet forwards to members.jsp, and members.jsp renders, locating the members value from the request (${members} in the JSTL c:forEach tag), and the c:forEach iterates across that list, populating the member variable, and from there filling out the rows in the table.
This is a classic "controller first" pattern which keeps the JSP out of the way. It also helps maintain that the JSPs only live in the View layer of MVC. In this simple example, Member and the List is the model, the Servlet in the Controller, and the JSP is the view.

Why my included JSP file won't get processed correctly?

I am trying (and learning) to build a java web framework, and in the process of developing its' code generator based on the content of the database. In the view making process, I stumble in a difficulty, which I don't know how to solve it.
Firstly, I want all the pages to be created using the following index.jsp :
<body>
<%# include file="header.jsp" %>
<hr/>
<%# include file="body.jsp" %>
<hr/>
<%# include file="footer.jsp" %>
</body>
And, in the body.jsp, I want it to be like this :
<jsp:include page="${application_modul}" %>
Where application_modul is an attribute defined in its' controller this way :
request.setAttribute("application_modul","user_account\\view_user_account.jsp");
It can find the file correctly, but the processed jsp is not what I expected. Here :
<c:forEach items="[application.models.UserAccountModel#18a49e0, application.models.UserAccountModel#1f82982]" var="item" varStatus="status" >
<tr>
....
You can see the items attribute of jstl forEach, got its variable name (toString())...
Any Idea what the problem is????
I hope I describe my problem correctly
Many thanks!
PS :
I already create a quick fix for this, but not what I want it though. In the generated view_user_account.jsp, I do it like this :
<body>
<%# include file="header.jsp" %>
<hr/>
<c:forEach items="${row}" var="item" varStatus="status" >
<tr>
....
<hr/>
<%# include file="footer.jsp" %>
</body>
You can see that I create the whole file here...
EDITED:
PS : ${row} is an ArrayList populated with data from certain table
So, to summarize your problem in a single sentence, JSTL tags are not been parsed and they end up plain in generated HTML output?
You need to declare JSTL taglib in top of the JSP page where you're using JSTL tags to get them to run. For the JSTL core taglib, that'll be
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
I am not sure but, Try this...
index.jsp
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />

Categories