How to get values from array in jsp - java

I want to show the data from an array using JSP.
I have three files:
index.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World! </h1>
<form name="Input Name Form" action="response.jsp"/>
<p> Enter your name:</p>
<input type="text" name="name"/>
<input type="submit" value="ok" />
</form>
</body>
</html>
response.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1> <br>
<jsp:useBean id="aaa" scope="page" class="A.a" />
<jsp:setProperty name="aaa" property="name" value="<%= request.getParameter("name")%>" />
<jsp:getProperty name="aaa" property="name" />
</body>
</html>
a.java:
public class a {
public a ()
{}
private String name;
ArrayList() array_list = new ArrayList();
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
//some magic to fill array_list with values
}
}
My question is:
What statement should I use in jsp to get values from array_list in a.java?
I know that there is statement
<c:forEach> </c:forEach>
but I am not sure how to use it.

<c:forEach items="${dataDetail}" var="data" varStatus="item">
<c:out value="${data.id}"/>
</c:forEach>
Here "dataDetail" is name of the key where you have set your list in controller.
(session or request ).setAttribute("dataDetail",---List of Data of type Class Data---);
Above code is similar to
for(Data data : dataDetail){
System.out.println(data.getId());
}

A similar question has been asked here: Iterate ArrayList in JSP
Long story short:
<c:forEach items="${aaa.array_list}" var="item">
${item}
</c:forEach>

use JSTL.
Try this out:
Have this at top of your JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
And code for displaying data
<c:forEach begin="0" end="${fn:length(array_list) - 1}" var="index">
<tr>
<td><c:out value="${array_list[index]}"/></td>
</tr>
</c:forEach>

Related

Spring checkbox parameters

I have a problem with checkbox. I have such jsp page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>All Photos</title>
</head>
<body>
<form action="/photos/deletePhotos">
<c:forEach var="photo" items="${photoList}">
<p><input type="checkbox" name="id" value="${photo.key}">${photo.key}</p>
<img src="/photos/photo/${photo.key}" width="300" height="200">
<br/><br/>
</c:forEach>
<input type="submit" value="Delete" />
</form>
</body>
</html>
and such controller:
#RequestMapping("/deletePhotos")
public ModelAndView deleteSomePhotos(#PathVariable(name = "id", required = false) long[] id) {
System.out.println(id);
return new ModelAndView("all", "photoList", photos);
}
problem is id==null, no matter checked checkbox or not. Where is my mistake?
#PathVariable is for path variable, like #RuquestMapping("/deletePhotos/{id}").
Use #RequestParam instead of #PathVariable.
Refer here : #RequestParam vs #PathVariable

spring:mvcUrl mapping wrong id

I am trying to map productId to URL in my jsp page, but the value is wrong.
The URL is returning Título 1 but the response is returning the right value:
HTML Mapping
My jsp code:
<%# 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"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
${success}
</div>
<table>
<tr>
<td>Id</td>
<td>Titulo</td>
<td>Valores</td>
</tr>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td>${product.title}</td>
<td>
<c:forEach items="${product.prices}" var="price">
[${price.value} - ${price.bookType}]
</c:forEach>
</td>
</tr>
</c:forEach>
</table>
My Java Controller Code:
#RequestMapping(method=RequestMethod.GET)
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("products/list");
modelAndView.addObject("products", productDAO.list());
return modelAndView;
}
My Java DAO Code:
public List<Product> list() {
return manager.createQuery("select distinct(p) from Product p join fetch p.prices", Product.class).getResultList();
}
Unfortunately I cannot see your method 'show'.
I guess you have a misprint in the path:
#RequestMapping("/show{/id}")
//--------------------^^ WRONG
public String show(#PathVariable("id") long id) {
...
}
instead
#RequestMapping("/show/{id}")
//--------------------^^ RIGHT

problems taking the value of the select option jsp

I need to take the value of the select option to send it to another page to be processed, but can not capture the value.
any ideas?
the select is loaded from the database, that part works, shows the categories of product.
<%#page import="com.sun.xml.internal.txw2.Document"%>
<%#page import="java.util.ArrayList"%>
<%# page import = "com.seminario.beans.categoria" %>
<%# page import = "com.seminario.datos.DbCategoria" %>
<%# page import = "com.seminario.beans.Producto" %>
<%# page import = "com.seminario.datos.DbProducto" %>
<jsp:useBean id="dataProd" class="com.seminario.datos.DbProducto" scope="page"/>
<jsp:setProperty name="dataProd" property="*"/>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="../stylo.css" rel="stylesheet" type="text/css" media="screen" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Alta Producto</title>
</head>
<%
categoria c = new categoria();
DbCategoria bdc = new DbCategoria();
ArrayList <categoria> myList = new ArrayList();
myList = bdc.SelectAll();
%>
<body>
<h1>Nuevo Producto</h1>
<form name ='formulario' action='nuevoProducto.jsp' method='post' >
Descripcion<input name='descripcion' type='text' size='20' required><br>
Precio<input name='precio' type='text' size='20' required><br>
Stock<input name='stock' type='text' size='20' required><br>
**Categoria <select name="categoid" id="categoid">
<% for(int i=0;i<myList.size();i++){%>
<option value="<%= myList.get(i).getId() %>" > <%out.print(myList.get(i).getDescripcion());%></option>
<%}%>
</select><br>**
Imagen<input name="imagen" text="seleccionar archivo" type="file" size="10" accept="image/jpg" /><br>
<input type ="submit" value ='Guardar' />
<!-- <input type="submit" value="guardar">-->
</form>
<br><br><a href='menuAdmin.jsp'>Volver al menu principal</a>
</body>
</html>

Edit link of a table of each row will send the primary key of the row to controller

Hi i am new in jsp and Spring. I have a table of employee information. I want to add a edit link in each row and an edit link will be click it will send the primary key of the row to the controller. When i click the edit link it display the error "The request sent by the client was syntactically incorrect ()."
This page display the table
employeeList.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee List</title>
</head>
<body>
<div align="center">
<h1 align="center">Employee List</h1>
<table align="center" border="1">
<tr><th>Pk</th><th>Employee Name</th><th>Employee email</th><th>Address</th><th>Manager Id</th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="employeeList" items="${list}">
<tr>
<td><c:out value="${employeeList.id}"/></td>
<td><c:out value="${employeeList.name}"/> </td>
<td><c:out value="${employeeList.email}"/> </td>
<td><c:out value="${employeeList.address}"/></td>
<td><c:out value="${employeeList.managerId}"/></td>
<td><a href="editEmployee.htm?id=${id}" >Edit</a></td>
<td><a href="deleteEmployee.htm?id=${id}" >Delete</a></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
my controller code is
#RequestMapping(value="/editEmployee.htm")
public String editEmployee(#RequestParam("id") int id,ModelMap model){
try {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "editEmployee";
} catch (Exception ex) {
return "index";
}
}
editEmployee.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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=ISO-8859-1">
<title>Registration Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
}
</style>
</head>
<body>
Edit Employee<br>
</body>
</html>
How i can solve this problem.
Change your jsp to something like this
<c:url var="editUrl" value="/editEmployee.htm" />
<a href="${editUrl}?id=${employeeList.id}">
Edit
</a>
<c:url var="deleteUrl" value="/deleteEmployee.htm" />
<a href="${deleteUrl}?id=${employeeList.id}">
Delete
</a
#RequestMapping(value="/editEmployee.htm") - wrong
#RequestMapping(value="/editEmployee/{id}")
public String editEmployee(#PathVariable int id,ModelMap model){
try {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "editEmployee";
} catch (Exception ex) {
return "index";
}
}
and also a href="editEmployee.htm?id=${id}
this should be something like a href="editEmployee/${id}

POST an array of custom objects to a Struts 2 action

How do I POST an array of custom objects to a Struts 2 action in Java?
For example if I have the following Java object:
public class Person {
private String name;
private String lastName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
And the following Action:
public class SavePersons extends ActionSupport {
private List<Person> persons;
#Override
public String execute() throws Exception {
// Do something
return SUCCESS;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
}
I'd like to do something like this in an HTML form:
<html>
<body>
<form method="POST" action="http://postHere">
<input type="text" name="persons[0].name" value="Name1"/>
<input type="text" name="persons[0].lastName" value="LastName1"/>
<input type="text" name="persons[1].name" value="Name2"/>
<input type="text" name="persons[1].lastName" value="LastName2"/>
<input type="submit" />
</form>
</body>
</html>
Any tips?
What you have looks good. It does not make a difference to struts2 if you post or get as far as setting values.
Using the same SavePersons class, except that I added a public List<Person> getPersons() method. This is required to make the solution work.
And using essentially the same form, except I prefer to write my forms using s2 tags where it makes sense (what puts some people off the form tags is the default s2 theme, you can globally set the theme to simple, the label attribute will not work but the UI tags will work just like you'd expect similar html elements to behave):
<%#taglib prefix="s" uri="/struts-tags"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Person Form</title>
</head>
<body>
<h1>Person Form</h1>
<s:form action="person-test" method="post">
<s:textfield name="persons[0].name" label="fName 1"/>
<s:textfield name="persons[0].lastName" label="lName 1"/>
<s:textfield name="persons[1].name" label="fName 2"/>
<s:textfield name="persons[1].lastName" label="lName 2"/>
<s:submit/>
</s:form>
</body>
</html>
Note that method="post" is not needed, it is the default.
Here is the page used to display the form data.
<%#taglib prefix="s" uri="/struts-tags"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>List of People</h1>
<s:iterator value="persons">
<s:property value="name"/> <s:property value="lastName"/><br/>
</s:iterator>
</body>
</html>
And it worked just fine.

Categories

Resources