Send object from a JSP page - java

What I want to do is to make a list of persons with id and other attributes.
First of all the app opens with a form to enter personal data. Then it goes to the servlet responsible to capture the data. Then the servlet sends it to another JSP file that shows data. Then if the user chooses to add another one it adds it.
This worked fine but I had to change the app to add to the HTML table a submit button so the user can delete the person he wants using another servlet for delete.
I tried to set the ArrayList that contains all the data as an attribute but it didn't work.
First i tried this way:
String x = request.getParameter("submit");
if (x != null) {
request.setAttribute("list", list);
request.setAttribute("id", p.getId());
request.getRequestDispatcher("Supprimer").forward(request, response);}
Then I tried this way:
out.println(" <tr><td> <form method='POST'>");
out.println("<input type='hidden' name='id' value='" + p.getId() + "' >");
request.setAttribute("list", list);
out.println("<input type='submit' value='Supprimer' name='submit' ></td></tr> ");
out.println(" <tr><td> </form >");
and this is the jsp file that will show the data
<%
ArrayList<personne> list = (ArrayList<personne>) request.getAttribute("list");
request.setAttribute("listt", list);
for (personne p : list) {
out.println("<table border='2'>");
out.println("<tr> <td>ID</td><td>");
out.println(p.getId());
out.println("</td> </tr><tr><td>Nom</td> <td>");
out.println(p.getNom());
out.println(" </td> </tr><tr> <td>Prenom</td> <td>");
out.println(p.getPrenom());
out.println(" </td> </tr><tr> <td>Sexe</td> <td>");
out.println(p.getSexe());
out.println(" </td></tr><tr><td>CodePostale</td><td>");
out.println(p.getCodePostal());
out.println(" </td></tr> </table> </br>");
out.println(" <tr><td> <form method='POST'>");
out.println("<input type='hidden' name='id' value='" + p.getId() + "' >");
request.setAttribute("list", list);
out.println("<input type='submit' value='Supprimer' name='submit' ></td></tr> ");
out.println(" <tr><td> </form >");
String x = request.getParameter("submit");
if (x != null) {
request.setAttribute("list", list);
request.setAttribute("id", p.getId());
request.getRequestDispatcher("Supprimer").forward(request, response);
}
out.println(" </table> </br>");
}
%>
this is the first servlet that will capture the data coming from the first submited form
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String nom = request.getParameter("nom");
String prenom = request.getParameter("prenom");
String sexe = request.getParameter("sexe");
int codePostal = Integer.parseInt(request.getParameter("cd"));
personne p = new personne(id, nom, prenom, sexe, codePostal);
ap.add(p);
request.setAttribute("list", ap);
request.getRequestDispatcher("affichage.jsp").forward(request, response);
}
and this is the servlet responsibale for deleting the object and resend us to the first servlet so it can send us again to the jsp file to show us the new data
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<personne> list = (ArrayList<personne>)request.getAttribute("list");
int id =Integer.parseInt(""+request.getAttribute("id"));
System.out.println(id);
java.util.Iterator<personne> itr = list.iterator();
while (itr.hasNext())
{
if(id==itr.next().getId()){
itr.remove();
}
}
request.setAttribute("list", list);
request.getRequestDispatcher("affichage.jsp").forward(request, response);
}
Btw this didn't help me: how to send ArrayList from jsp to servlet

The code you write can not work, because you are storing item info on request object when you are rendering the HTML page.
One solution is to define for each field an hidden HTML field, as you already define to id attribute.

I tried to set the Arraylist that contains all the data as an attribute but it didn't work.
Form submit from jsp will eventually discard old request object itself since browser makes a new request to server.
Instead of relying on request.setAttribute("list", list) make use of session.setAttribute("list", list) just once in the servlet itself, no need to set in jsp.
Now, to access the list use session.getAttribute("list")

Related

Code is not executing when nothing is entered

I am attempting to build a world clock, to display GMT, PST etc.
The only problem I'm having is that when the user types nothing in the text field, it's not going into the if statement that only executes when the user doesn't enter anything and displays the local time. I have provided all my code to see what the problem is.
html code:
<body>
<form action="WorldClockWebApp" method="post">
<table>
<tr>
<td>Enter Time Zone:</td>
<td><input type="text" name="timezone" /></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String input = request.getParameter("timezone");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
ZoneId z;
boolean valid = true;
TimeZone t = null;
String[] ids = TimeZone.getAvailableIDs();
if (input != "") // If the user enters in a timezone.
{
for (String id : ids) {
if (input.equalsIgnoreCase(id))
t = TimeZone.getTimeZone(id);
}
}
if (t == null)
response.getWriter().append("<h1>What's the time Mr Wolf?</h1>")
.append("<p>No time provided, but the local time is " + t.getDisplayName().toString() + " is:</p>")
.append("<h2>" + LocalTime.now(t.toZoneId()).format(dtf) + "</h2>")
.append("<form action=\"/project4/WorldClock.html\">" + "<button type=\"submit\">Go Back</button>"
+ "</form>"); // Button gives user option to go back.
else
response.getWriter().append("<h1>What's the time Mr Wolf?</h1>")
.append("<p>The current time in " + t.getDisplayName().toString() + " is:</p>")
.append("<h2>" + LocalTime.now(t.toZoneId()).format(dtf) + "</h2>")
.append("<form action=\"/project4/WorldClock.html\">" + "<button type=\"submit\">Go Back</button>"
+ "</form>"); // Button gives user option to go back.
}
I think you need to do if input != null instead of if input !="".
assuming that you implement doPost method and it is like doGet method, you should use equals instead of != "" .
your code can be like below code.
if (!input.equals(""))

I am not able to get the value form JSP page to Controller Class on Submit

This code is wriiten in Liferay 6.1 platform.
Description: I have one drop down menu by name "Store Name". I will select any one of the value from drop down and pass that value to javascript function "getStoreDetails" onchange. The sent value from this function will be checked in the javascript array "lNames", If value is present in this array then index will be obtained and using index we obtain value from "fNames" array and add to span class "FirstName". I am able to do this and code is working fine.
Problem:I am not able to get FirstName value from jsp file to Controller Class of submitIssue method.
This is my Controller class
public class IssueController{
public String handleRenderRequest(RenderRequest request, RenderResponse response, Model model) throws Exception {
HttpServletRequest httpRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
User user = PortalUtil.getUser(httpRequest);
model.addAttribute("my_user", user);
/*Some code goes here to set user attributes like department and organization using model object */
return "issue"; /*This is my jsp file mentioned below*/
}
#ActionMapping
public void submitIssue(#ModelAttribute IssueForm submitIssueForm, ActionRequest request, ActionResponse response) throws PortalException, SystemException, IOException, PortletException {
String First_Name=request.getParameter("FirstName");
System.out.println("First Name while submitting is :\t"+First_Name);
/* here i am not able to obtain value of First_Name */
}
}
The below code is my issue.jsp file
<div class="large-4 medium-8 small-12 columns">
Store Name <select
class="no-highlight" id="StoreName_dropdown"
name="storeName"
onchange="getStoreDetails(this.value);"
<%
String stores[] = new String[] {"1021","1022","1023","1024","1025","1026","1027","1028","1029","1030"};
for(int i=0;i<stores.length;i++){%>
<option value="<%=stores[i]%>"><%=stores[i]%></option>
<%}%>
</select>
</div>
<%
String fNames[] = new String[] {"John1021","wilson1022","test1023","test1024","test1025","test1026","test1027","test1028","test1029","test1030"};
StringBuffer bufferfNames = new StringBuffer();
bufferfNames.append("[");
for(int i=0; i<fNames.length; i++){
bufferfNames.append("\"").append(fNames[i]).append("\"");
if(i+1 < fNames.length){
bufferfNames.append(",");
}
}
bufferfNames.append("]");
String First_Name=bufferfNames.toString();
String lNames[] = new String[] {"1021","1022","1023","1024","1025","1026","1027","1028","1029","1030"};
StringBuffer bufferlNames = new StringBuffer();
bufferlNames.append("[");
for(int i=0; i<lNames.length; i++){
bufferlNames.append("\"").append(lNames[i]).append("\"");
if(i+1 < lNames.length){
bufferlNames.append(",");
}
}
bufferlNames.append("]");
String Last_Name=bufferlNames.toString();
%>
<div class="row ">
<div class="large-3 medium-4 columns">
<span class="firstName">First Name : <span
class="hide-for-medium-up"><b>"dynamically name added"</b></span></span>
<div class="hide-for-small" id="FirstName" >
<b>"dynamically name added"</b>
</div>
</div>
</div>
<div class="row ">
<div class="large-2 medium-3 columns">
<button class="submitIssue submit_button"
id="submitIssue" tabIndex=9>
Submit
</button>
</div>
</div>
<script>
function getStoreDetails(store) {
var fNames=<%=First_Name%>;
var lNames=<%=Last_Name%>;
var index;
index=lNames.indexOf(store);
if (index > -1) {
document.getElementById("FirstName").innerHTML = fNames[index];
}
else{
alert("Store is not present in lNames !!");
}
}
</script>
My javascript program in separate file submitIssue.js
$( document ).ready(function() {
$('button.submitIssue').click(function(){
$('#submitIssueForm').submit();
});
});
Can anyone suggest me to get this value. Please comment in case if you have not understood my problem statement. thanks in advance.
Are you able to see "FirstName" printed in your jsp? If yes, you need to pass this value in input tag, so that you can expect this value to come in your controller. Hope this helps!!

Calling a servlet from a dynamically generated form

I'm making a mock up of an online store for school. I'm storing my products in an SQL Database. I want to display all products in the DB with buttons next to them that will send their ID to the cart_servlet. In order to display the products I'm generating a table like so:
public static String getInventory(){
String result = "<table>";
for ( Product p : DAO_Product.getProducts() ) {
result = result + "<tr>"
+ "<td>" + p.getName() + "</td>"
+ "<td><img src=\"resources/images/" + p.getImage() + "\" alt=\"Duke waving his hand\"></td>"
+ "<td>" + p.getDollars() + "</td>"
+ "<td>" + p.getPennies() + "</td>"
+ "<td>" + p.getStock() + "</td>"
+ "<td>" + p.getDescription() + "</td>"
//creates a form consisting of one button and a hidden value
//clicking the button should submit the corresponding hidden value
+ "<td><form action=\"${pageContext.request.contextPath}/cart_servlet\" method=\"post\">"
+ "<input type=\"hidden\" name=\"product\" value=\"" + p.getId() + "\" />"
+ "<input type=\"submit\" name=\"submit\" value=\"Add to Cart\" />"
+ "</form>"
//End Form
+ "</tr>";
}
}
This creates the correct table as I envisioned and the HTML it generates looks correct:
<table><tr><td>Caverna</td>
<td><img src="resources/images/caverna.jpg" alt="sampleImage"></td>
<td>112</td><td>12</td><td>34</td>
<td> you are the bearded leader of a small dwarf family which lives in a little cave in the mountains. Together, you</td>
<td><form action ="${pageContext.request.contextPath}/cart_servlet" method="post">
<input type="hidden" name="product" value="4" />
<input type="submit" name="submit" value="Add to Cart" />
</form>
However when I click the button I am presented with: 'HTTP Status 404 - Not Found' description: 'The requested resource is not available'
The Servlet I am requesting is my 'CartServlet':
#WebServlet( "/cart_servlet" )
public class CartServlet extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String result;
Status status = new Status();
req.setAttribute( "status", status );
//RequestDispatcher view = req.getRequestDispatcher( "browseProducts.jsp" );
if ( req.getParameter( "submit" ) != null ) {
}
//view.forward( req, resp );
}
}
I've commenting out everything in my 'CartServlet' and I am sure that it probably cant get the context somehow or find the class but I am unsure about how to fix this.
It turns out I was approaching this all wrong. Instead I should have built the table within my JSP using JSTL. With the following code I was able to delete 'getInventory()':
The First step is to add the following line to the top of your JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Note Ensure you have downloaded the JSTL library and added it to your project. You can find it here.
The Second step is to declare any variables you would need. In this case I require an ArrayList of 'Products':
<%
ArrayList<Product> products = DAO_Product.getProducts();
//Set an attribute to reference our Arraylist
pageContext.setAttribute( "products", products );
%>
Now we are ready to build our table. The table will display information about each product and have a button in the last column that will call 'cart_servlet'. We are going to use the 'forEach' from 'JSTL':
<table border="1" cellpadding="5" >
<tr>
<th>Name</th>
<th>Image</th>
<th>Price</th>
<th>Description</th>
<th>Stock</th>
<th>Add to Cart?</th>
</tr>
<c:forEach var="p" items="${products}" >
<tr>
<td>${p.name}</td>
<td><img src="resources/images/${p.getImage()}" alt="Cool Pic"></td>
<td>$${p.dollars}.${p.pennies}</td>
<td>${p.description}</td>
<td>${p.stock}</td>
<td>
<form action="${pageContext.request.contextPath}/cart_servlet" method="post">
<input type="hidden" name="productID" value="${p.id}">
<input type="submit" name="addToCart" value="Add to Cart">
</form>
</td>
</tr>
</c:forEach>
</table>

Looping through a list of images in JSP and calling a servlet to display each one in a table, but the final output displays same image

I am working on an assignment in which I have to provide a user login after which he will be directed to a page where he can upload images and all of his previous + new images will be displayed below in a table. So the structure of my application is like this...
(trimmed most of the code for clarity)
JSP file that allows upload and displays the image
<p>Please select an image file to upload(Max file size 1 MB)</p>
<%
Integer userId = 0;
userId = (Integer) session.getAttribute("userId");
%>
<%
String errorMessage = (String) request.getAttribute("error");
if (errorMessage != null) {
out.print("<h4> " + errorMessage + "</h4>");
}
%>
<form action="imageupload" enctype="multipart/form-data" method="post">
<br /> <input type="file" name="uploader" id="uploader" /> <br /> <br />
<input type="submit" /> <input type="button"
value="clear" onClick="clear()" />
</form>
<br />
<h4>Uploaded Images</h4>
<br />
<table width="80%">
<tr>
<th>S No.</th>
<th>Name</th>
<th>size</th>
<th>Preview</th>
<th>Actions</th>
</tr>
<%
UserImagesDAOImplementation userImages = new UserImagesDAOImplementation();
List<Image> images = (List<Image>) userImages.getUserImages(userId);
for (Image image : images) {
%>
<tr>
<td><%=image.getSn()%></td>
<td><%=image.getImageName()%></td>
<td><%=image.getSize()%></td>
<td><% session.setAttribute("image",image.getImage() ); %><img src="toimage" height="100px" width="100px" /></td>
<td><img src="img/edit.png" /> <img src="img/url.png" /></td>
</tr>
<%
}
%>
</table>
<br />
Total space used: <%= (userImages.getSizeUsage(userId)/1024) %> KB / 10 MB
the "toimage" servlet that returns the image
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Byte[] image = (Byte[]) session.getAttribute("image");
int len = image.length;
byte[] imageData = new byte[len];
for(int i=0; i < len; i++) {
imageData[i] = image[i];
}
response.setContentType("image/jpg");
response.getOutputStream().write(imageData);
response.getOutputStream().flush();
response.getOutputStream().close();
}
My problem is that it displays the last image in the list in all the table rows and after uploading some other image it displays that new image in every row.
I am not very confident about my design for the site but this is the first time I am working with JSP. I decided to get the image list inside JSP as I will have to perform some more operations on it later on. I guess the problem is either in setting the session variable or the src servlet being called in the end. Whatever it is, can someone please explain the typical flow of events in this design.
Edit:
Putting a print statement inside the "toimage" servlet proves that it is being called just once. So how can I make the JSP loop to call the image src every time ??
You use a single session attribute to store every image. So, at the end of the loop, this session attribute contains the last one.
You shouldn't use the session at all. Instead, you should pass the ID or name or whatever identifies the image as a URL parameter:
<img src="toimage?imageId=<%= image.getId() %>" height="100px" width="100px" />
And the servlet should use this parameter to now which image it must oad and send to the browser.
Also, learn the JSTL and the EL. Scriptlets sould not be used.

Convert a List to String to populate webpage in JSP

I have DAO bean rows retrieved in a List. In my JSP I am accessing the List to iterate thru to populate my page. My JSP can't access the List because it says it must be a String when I execute a request.getParameter. How I convert this to String eventually populate my page?
public List getAccessRequest()
{
List accessRequesttList = new ArrayList()); // parse List to string
//AccessRequest accessrequest = null;
AccessRequest accessRequest = new AccessRequest());
try
{
System.out.println("Try statement begins AccessRequestDAO");
PreparedStatement accrqststmt = super.getConnection().prepareStatement(AccRqstSqlStmt);
ResultSet resultSet = accrqststmt.executeQuery();
while (resultSet.next())
{
// Creating an instant of job follows
accessRequest = new Accessrequest();
accessRequest.setJOB_NAME(resultSet.getString("job_name"));
accessRequest.setRequest_ts(resultSet.getTime("request_ts"));
accessRequestList.add(accessRequest);
Iterator iterator = accessRequestList.iterator();
while (iterator.hasNext())
{
accessRequest = (Accessrequest) iterator.next();
}
}
return (accessRequestList);
My JSP look like below:
<%
List jobList = request.getParameter("acccessrequests"); // parse List to String
Iterator iterator = jobList.iterator();
while (iterator.hasNext())
{
accessRequest = (AccessRequest) iterator.next());
%>
<tr>
<td><input type="checkbox" name="<%accessRequest.getApproval_ind(); %>"></td>
<td><input type="text" id="jobname' name="accessRequests" value="job_name"></td>
HttpServletRequest#getParameter() returns a String, not a List. So the compiler is right.
I am not sure how you have ever set the List as a request parameter, there's no such method like HttpServletRequest#setParameter(). So you're probably misinterpreting something. The normal approach is to set the list as request attribute by HttpServletRequest#setAttribute() and access it in JSP by EL (expression language) like as ${attributeName}. You also normally iterate over the list using JSTL <c:forEach> tag.
Assuming that you've set the list in the request scope using a Servlet like follows...
request.setAttribute("list", list);
...here's a kickoff example how to iterate over the list:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.property1}</td>
<td>${item.property2}</td>
<td>${item.property3}</td>
</tr>
</c:forEach>
</table>
Alhamdulillah, thanks God!
This help me a lot. I try to build my own java Web framework.
Before reading this QA, I don't know how to access an object (say, row of table) from a JSP.
I just redirect it, and leave the database code in JSP, generated by DreamWeaver. Now I know how to do it. For example, this is a BiroController, which display data from Biro Table :
public void index() throws IOException, ServletException {
List list=new ArrayList();
list.add(BiroModel.create("1", "SDM"));
list.add(BiroModel.create("2", "Keuangan"));
request.setAttribute("list", list);
super.index();
}
firstly, I populate an array (subsequently, this will come from database table). and then set request attribute, then call superclass index method :
public void index() throws IOException, ServletException {
RequestDispatcher rd = request.getRequestDispatcher(viewPage);
if(rd!=null){
rd.forward(request, response);
}else{
PrintWriter out = response.getWriter();
out.print("can not dispatch to " + viewPage);
}
//OLD Code : response.sendRedirect(ServletUtil.getBaseUrl(request) + viewPage)
}
And, I did as you instructed in the JSP :
<c:forEach items="${list}" var="item">
<tr>
<td>${item.idbiro}</td>
<td>${item.biro}</td>
</tr>
</c:forEach>
I use Netbeans, so I can easily pick JSTL library from the list of available library
It works charmingly.. :) tq

Categories

Resources