Passing an array from servlet to jsp along with a bean - java

I'm passing an array of beans from servlet to jsp. I also want to send status "onHand" for each bean. I'm using arrayList for the status.
In Servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import pckg.ProductBean;
public class GetProducts extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
Vector<String[]> v = DBHelper.runQuery("SELECT * FROM SKU;");
ProductBean [] beans = new ProductBean[v.size()];
ArrayList<String> onHand=new ArrayList<String>();
//onHand.add("a");
for(int i=0; i < v.size(); i++) {
String [] tmp = v.elementAt(i);
Vector<String[]> on = DBHelper.runQuery("SELECT on_hand_quantity FROM on_hand where sku='"+tmp[0]+"' ;");
if((on.size())>0){
String [] tmp1 = on.elementAt(0);
if(Integer.parseInt(tmp1[0])>0){
onHand.add("InStock");}
else if(Integer.parseInt(tmp1[0])==0){
onHand.add("MoreOnTheWay");
}
}
beans[i] = new ProductBean(tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],
tmp[5],tmp[8],Double.parseDouble(tmp[6]),Double.parseDouble(tmp[7]));
}
request.setAttribute("p_beans",beans);
request.setAttribute("onHand",onHand);
String toDo = "/WEB-INF/jsp/cameraList.jsp";
RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher(toDo);
dispatcher.forward(request, response);
}
}
In JSP page:
<%# page import = "java.util.*"%>
<%# page import="java.io.*" %>
<%# page import="java.net.*" %>
<%#page import="java.util.ArrayList" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<link rel="stylesheet" href="../css/cameraList.css" type="text/css"></link>
<script src="../script/jquery.js"></script>
<script src="../script/cameraList.js"></script>
</head>
<body>
<div id="main">
<% ArrayList<String> onHand=(ArrayList<String>) request.getAttribute("onHand");%>
<c:forEach items="${p_beans}" var="item">
<table >
<tr><td rowspan=5><img id="image" src="upload_dir/${item.image}" style="height:350px; width:350px; background-color:yellow";></td>
<td><b> ${item.vendor} ${item.model} ${item.category}</b></td></tr>
<tr><td width=45%> Price:$${item.retail}</td><td>Status:</td></tr>
<c:url value="/servlet/GetProductDetails?" var="myURL">
<c:param name="sku" value="${item.sku}" />
</c:url>
<tr><td><a href="${myURL}" >Get Details</a></td>
<c:url value="/servlet/OrderPage" var="cartURL">
<c:param name="itemID" value="${item.sku}" />
</c:url>
<td>Add To Cart</td></tr>
</table>
</c:forEach>
</div>
</body>
</html>
I get the following error in server:
An exception occurred processing JSP page /WEB-INF/jsp/cameraList.jsp at line 44:
41: <body>
42:
43: <div id="main">
44: <% ArrayList<String> onHand=(ArrayList<String>) request.getAttribute("onHand");%>
45: <c:forEach items="${p_beans}" var="item">
46:
47: <table >

request.getParameter() always return a String and it is basically use to get data from a form submitted by the user or to get the data from query string.
Because you are calling getParameter() , it will return String and therefore you are getting that exception.
As per your question, because you are setting value for onHand field as attribute in request, you should call getAttribute() method in JSP. Return type for getAttribute() is Object.

Cannot cast from String to ArrayList
It seems like your onHand object is of String type which you are setting your servlet/controller class (using request.setAttribute("onHand",onHand)), so you need to typecast to String rather than ArrayList<String> as shown below in your JSP:
<% String onHand= (String)request.getAttribute("onHand"); %>
Also, the important point is that you need to use request.getAttribute(key) to retrieve the objects inside JSP.

<%
String param = request.getAttribute("onHand");
%>
<c:forEach items="${p_beans}" var="item">
<tr>
<td>iterated fields</td>
<td>
..
..
<td><%=param%></td>
</tr>

Related

request.getAttribute() return null

I can`t understand one thing when i send request to get object by name from db,
it always return me null. I surf all sites try to fix it with session and etc. Nothing to work.
Any ideas?
enter image description here
This is my Servlet class:
#WebServlet(value = "/display", name = "IndexServlet")
public class IndexServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if(!(request.getParameter("mysql")==null)) {
MySQLRepository sql = new MySQLRepository();
Headline object = sql.getByHeadline(request.getParameter("mysql"), DatabaseConnection.initDatabase());
request.setAttribute("id", object.getId());
request.setAttribute("headline", object.getHeadline());
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("out.jsp");
requestDispatcher.forward(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is index.jsp:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>MySQLSolrProject</title>
</head>
<!DOCTYPE html>
<body>
<form action="out.jsp" method="get">
<p>Headline:</p>
<label>
<input type="text" name="mysql">
</label>
<%--<br>
<p>Full text:</p>
<label>
<input type="text" name="solr">
</label>--%>
<br><br>
<input type="submit" value="Search" formmethod="get">
</form>
</body>
</html>
This is out.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Out</title>
</head>
<body>
<h2>Text is:</h2>
<table>
<tr><th>Id</th><th>Headline</th><th></th></tr>
<tr><td><%=session.getAttribute("id")%></td>
<td><%=session.getAttribute("headline")%></td>
</tr>
</table>
<p>Return to search</p>
</body>
</html>
the error was that Tomcat version 10.* didn't want to work with version 4 servlets
I downgraded Tomcat to version 9.* and it worked.

How do i return a jsp as a response from this servlet? [duplicate]

This question already has an answer here:
Servlet send response to JSP
(1 answer)
Closed 3 years ago.
how do i set the jsp file as response in my servlet ?And what kind of expression do i need to use in the jsp page?
this is the form
<html>
<head>
<title>Select your Hobby</title>
</head>
<body>
<form method="POST" action="SelectHobby">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
the servlet
package com.example.web;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HobbyServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
String hobby = request.getParameter("hobby");
}
}
and this is the jsp in wich i want to see the hobby in the body
<html>
<head>
<title>These are your hobbies</title>
</head>
<body>
<%
</body>
</html>
I recomend you to read this post. JSTL will help you. I suppose you mapped your servlet. Here is a quick example:
<%# 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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="testservlet">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
The servlet:
#WebServlet(name = "test", urlPatterns = { "/testservlet" })
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hobby = request.getParameter("hobby");
request.setAttribute("theHobby", hobby);
request.getRequestDispatcher("hobbypage.jsp").forward(request, response);
}
I defined an attribute called theHobby to hold the value from the selected hobby in the first page. I also created a page called hobbypage.jsp where I want to send the value to.
<%# 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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hobby: ${theHobby}
</body>
</html>
With JSTL you can call the attribute through the name you defined like this ${nameOfAttribute}.

How do you populate an html with data from an array list using servlet? [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 3 years ago.
I am trying to populate an html data with data from my arraylist, but i am having some difficulties. I already loaded the data and stored it inside my arraylist but when launching my program the table is empty. Could someone help me with this? I already tried googling my problem, but i cant seem to find an answer.
This is where i'm loading my data and populating it inside my arraylist
import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
#WebServlet("/registered-class")
public class myRegist extends HttpServlet{
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
getInfo registerStu = new findInfo();
String ssn = request.getParameter("ssn");
String fullName = registerStu.getFullName(ssn);
String phone = registerStu.getPhone(ssn);
List<StudentClass> classList = registerStu.loadClass(ssn);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
StudentClass stu = new StudentClass();
request.setAttribute("message", classList);
request.getRequestDispatcher("/table.jsp").forward(request,response);
//ptints out info about course
//out.println(classList.get(0));
/*StudentInfo info = new StudentInfo(ssn, fullName, phone);
HttpSession session = request.getSession();
session.setAttribute("student", info);
String address = null;
if (fullName == null) {
address = "/myRegist.jsp";
}
else if (fullName != null) {
address = "/myRegist.jsp";
}
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward(request, response);*/
}
}
My html table
<html>
<body>
<head>
<title>
View Books
</title>
</head>
<body>
<table border=2>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Author</th>
<th>No. of copies AVAILABLE</th>
<th>Number of favourites</th>
</tr>
<tr>
<td><%=b.bookID%></td>
<td><%=b.bookTitle%></td>
<td><%=b.bookAuthor%></td>
<td><%=b.bookCopies%></td>
<td><%=b.bookFavs%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
Although #olivakyle's answer is correct, I prefer the use of jstl tags instead of scriplets: it keeps the JSP less messy:
<!DOCTYPE html>
<%#page contentType="text/html"%>
<%#page pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<head>
<title>
View Books
</title>
</head>
<body>
<table border=2>
<tr>
<th>Student ID</th>
<th>Name</th>
</tr>
<c:forEach var="stu" items="${message}">
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
It's quite simple actually – given that you're familiar in passing objects to your JSP. Here is an example using the object you passed and named message and I'm just assuming it has a String property named name.
<%for (StudentClass sc: message) {%>
<span><%=sc.name%></span><br>
<%}%>

pass parameter from jsp to another jsp dynamically

i am working on java application where user's login and predict football matches , i create an admin jsp to get all teams name from stored table in database to set this week matches and set the final results later when the matches finish to compare them with users results and calculate points , top users etc ...
my admin.jsp where i choose matches team from jstl foreach loop and set the final result later to compare them with user prediction results.
<%#page import="pws.daoImp.UsersDaoImp"%>
<%#page import="java.lang.String"%>
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="pws.beans.Users"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<% request.getAttribute("admminresult");
%>
<%
List<String> teams1 = new ArrayList();
UsersDaoImp udi = new UsersDaoImp();
List<String> admminresult = new ArrayList();
admminresult = udi.getadminresult();
request.setAttribute("admminresult", admminresult);
List<String> teams = new ArrayList();
teams = udi.getallteams();
request.setAttribute("teams", teams);
%>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Match Prediction</title>
</head>
<body>
<div>
<h1 class="title">Welcome to Match Prediction Site </h1>
<div id="logo" >
<img src="images/cl.png" alt="Smiley face" width="142" height="142">
</div>
</div>
<form action ="AdminUserHandling" method = "post" >
<div class="form-lables">
<h1><select name="clteam1" >
<c:forEach items="${teams}" var="teams" >
<option name="clm1g1" value="${teams}">
${teams}
</option>
</c:forEach>
</select> Vs <select name="clteam1" >
<c:forEach items="${teams}" var="teams" >
<option name="clm1g1" value="${teams}">
${teams}
</option>
</c:forEach>
</select> </h1>
<label for="user_lic">Goals : </label><input id="user_lic" name="clm1g1" type="number" min="" max="10" step="1" value ="1"/>
<label for="user_lic">Goals : </label><input id="user_lic" name="clm1g2" type="number" min="" max="10" step="1" value ="1"/>
</div>
<input type ="submit" value="Submit" />
</form>
</body>
</html>
and my servlet code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UsersDaoImp udi = new UsersDaoImp();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String team1 = request.getParameter("clteam1");
String team2 = request.getParameter("clteam2");
String team1gl = request.getParameter("clteam1gl");
String team2gl = request.getParameter("clteam2gl");
Users user = (Users) request.getSession().getAttribute("user");
System.out.println(team1);
System.out.println(team2);
udi.adminhandling(team1, team2,team1gl,team2gl); //save teams name and goals in database
processRequest(request, response);
}
}
my question is that i set the teams name and final result in admin page jsp but have problem to pass them to users jsp dynamically , iam running out of ideas to do so any help would be much appreciated.
You can use RequestDispatcher.
Defines an object that receives requests from the client and sends
them to any resource (such as a servlet, HTML file, or JSP file) on
the server. The servlet container creates the RequestDispatcher
object, which is used as a wrapper around a server resource located at
a particular path or given by a particular name.
RequestDispatcher rd = request.getRequestDispatcher("/path/to/your/users.jsp"); // mention correct path to your user.jsp here
request.setAttribute("teams",teams);
rd.forward(request, response);
Or
You can set the object into Session.
HttpSession session = request.getSession(false);
session.setAttribute("teams",teams);

request.getAttribute is null when I call it in jsp

It calls Servlet by click a href.
<li >privilegeManagement</li>
this code is include in the navigation.jsp which is included in the main.jsp.
then it's my servlet.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
ProviderDao pd = new ProviderDao();
List<ProviderArchives> list = pd.getArchives();
String str = "chenfeng";
req.setAttribute("list", list);
req.setAttribute("hu" , str);
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
}
then it's my main.jsp.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="java.util.*"%>
<%#page import="com.chenfeng.javabean.ProviderArchives"%>
<%# 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>main</title>
</head>
<body>
<%# include file="navigation.jsp"%>
<div>
<%# include file="management.jsp"%>
</div>
<div>
<%
String k = (String)request.getAttribute("hu");
out.println(k);
%>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.provideID() }</td>
<td>${item.GID }</td>
<td>${item.Gname }</td>
<td>${item.PID }</td>
<td>${item.TEL }</td>
<td>${item.ADDR }</td>
<td>
Modify
Delete
</td>
</tr>
</c:forEach>
</div>
</body>
</html>
then when I run this on server,it shows like this
thank in advance for any help!
Actually,there is no reason for this code.But the eclipse run into problem.The real problem log output after I delete class file in build directory and build it again.
It's quite clear. You set attribute of Request Object while you're forwarding Servlet Context Object.
Instead of:
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
Write:
req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);

Categories