Getting exception while invoking jsp from a servlet? - java

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.

Related

JSP not getting request parameters

I have a JSP page which is not seeing any of the request parameter values when displayed. Originally I tried with passing the parameters from a Servlet, which did not work. Just as a test I also tried calling that JSP from a form on an html page.
What I do in Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sampleValue = sampleModel.getMyValue();
request.setAttribute("param", sampleValue);
RequestDispatcher view = request.getRequestDispatcher("samplePage.jsp");
view.forward(request, response);
}
How I call JSP from an HTML page through a form with hidden fields:
<div>
<form action="samplePage.jsp" method="post">
<input name="param" type="hidden" value="sampleValue"/>
<input type="submit" value="Update">
</form>
</div>
Finally what I have on the JSP:
<body>
<p>Some info: ${param}</p>
</body>
As I said the problem is the value of the request attribute "param" which is lets say "sampleValue", does not get rendered on the page.
I have seen lots of examples how this is done and I think my code is correct. Is there any other reason why this may not be working? I am running a maven project with Tomcat 8.5.
EDIT: What I have found out so far is that the problem is not that the Expression language is not working. The request attribute just has no value when it arrives at the JSP.
Please ensure that isELIgnored is false in your jsp page.use bellow tag at the top of your jsp.
<%# page isELIgnored="false" %>
also you can ensure this by ${2 * 4} output is print as 8 on JSP.
Your form is using method=post. Your Servlet code should be located on the doPost method instead of doGet.
For Servlet case, replace ${param} in your samplePage.jsp with
<%=request.getAttribute("param")%>
For JSP case, replace ${param} in your samplePage.jsp with
<%=request.getParameter("param")%>
First, check whether variable sampleValue is capturing the string that you are passing from JSP like below
String sampleValue = sampleModel.getMyValue();
System.out.println(sampleValue);

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/

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.

Liferay : How to call a Servlet from a JSP Page

This is my first Portlet. I am not getting values inside my servlet. Please, see the program. Inside my custom portlet Java class doView() method, I show a JSP page
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
include(viewJSP, renderRequest, renderResponse);
}
Inside the view.jsp page, I refer to a servlet to receive the values:
<form action="formServlet" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="login"><br>
Password: <input type="password" name="password"><br>
<input type=submit value="Login">
</form>
Inside web.xml file:
<servlet>
<servlet-name>formServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>formServlet</servlet-name>
<url-pattern>formServlet</url-pattern>
</servlet-mapping>
Inside my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = (String)request.getParameter("login");
System.out.println("The Name is "+name);
}
But I don't know why the servlet is not being called.
NOTE: This is an answer to a somewhat complicated question. If you are trying to learn the basics of portlet creation, I posted a better answer in another question.
You are submitting a form using the POST method but your servlet just implements doGet(), which serves the GET method. You should either submit your form using GET or implement the doPost() method (which would be preferable in other situations).
Also, it is necessary to precede the <url-pattern> content by a slash if it is an absolute pattern. That is, it should be
<url-pattern>/formServlet</url-pattern>
instead of
<url-pattern>formServlet</url-pattern>
That said, forget servlets now!
You are doing it in one of the worst ways. It is really a bad idea to write a portlet which calls a servlet. After a long time working with Liferay I can imagine situations where it would be more or less reasonable, but it is not here and will not be most of the times.
So, what should you do? You should submit your form to an action URL. To do it, first include the portlet taglib in your JSP:
<%# taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
Now, replace the action of your form by the <portlet:actionURL />. This tag will be replaced by a special URL generated by the portal. Also, precede each input name with the tag <portlet:namespace />; your <input type="text" name="login"> should become <input type="text" name="<portlet:namespace />login"> then. This tag will be replaced by a string which is associated with only your portlet; since you can have a lot of portlets in a page, each input should specify from what portlet it comes from. This is the final result:
<form action="<portlet:actionURL />" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="<portlet:namespace />login"><br>
Password: <input type="password" name="<portlet:namespace />password"><br>
<input type=submit value="Login">
</form>
Now you are going to submit your data correctly - but how to get the submitted data? It certainly is not necessary to use a servlet! Instead, add to your custom portlet class a method called processAction(). This method should return void and receive two parameters, of the time javax.portlet.ActionRequest and javax.portlet.ActionResponse. This is an example of an empty processAction():
public void processAction(ActionRequest request, ActionResponse response) {
// Nothing to be done for now.
}
When a request to an action URL (as the one generated by <portlet:actionURL />) is sent to the server, it is firstly processed by the processAction() method and then by doView(). Therefore, the code you would write in your servlet should be put in your processAction(). The result should be then:
public void processAction(ActionRequest request, ActionResponse response) {
String name = (String)request.getParameter("login");
System.out.println("The Name is "+name);
}
Try it and you will see that it will work well.
yyy - Here's the answer to your comment:
In your JSP page you'll need to add the following for each of the actions you want that portlet to perform:
<portlet:actionURL var="addUserURL">
<portlet:param name="<%= ActionRequest.ACTION_NAME %>" value="addUser" />
</portlet:actionURL>
<form method="post" action="<%= addUserURL %>">
Then in your com.test.Greeting portlet you'd have for each of these:
public void addUser (ActionRequest actionRequest, ActionResponse actionResponse) {}
Does this answer your question?
Also it's usually best to start a new question rather than adding a comment.

Iterating over ArrayList in .jsp (MVC2 compliant)

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.

Categories