problems taking the value of the select option jsp - java

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>

Related

How to get values from array in jsp

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>

Get record value from form using javascript

I want to get value of id and name from the following table and send to the server to update the record.
So far, I have made particular record editable but I am totally unable to get the updated value to the server side. I am newbie in JavaScript. Help is appreciated.
JavaScript Code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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" %>
<%# taglib uri="http://displaytag.sf.net" prefix="display" %>
<%# taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Records</title>
<link rel="stylesheet" type="text/css" href="/XMLTest/css/tableStyle.css" />
<script type="text/javascript">
function makeEditable(elem) {
var parentNode = elem.parentNode.parentNode;
var childs = parentNode.childNodes;
for(var i = 0; i < childs.length-1; i++){
var innerChilds = childs[i].childNodes;
var innerChildValue = "";
if( innerChilds.length > 0){
for(var j = 0; j < innerChilds.length; j++){
var tag = innerChilds[j];
if(tag.type == 'button')
continue;
if(tag.type == 'hidden')
innerChildValue = tag.value;
}
}
childs[i].innerHTML = "<input type='text' size='10' value='" +innerChildValue +"' />";
}
childs[childs.length-1].innerHTML = "<form action='updateOrganization'><input type='hidden' name='id' value='' /><input type='submit' value='Save'/></form><input type='button' value='Cancel' onClick='window.location.reload()'/>";
}
</script>
</head>
<body>
<jsp:include page="/header.jsp"></jsp:include>
<center>
<display:table id="record" name="listOfOrganization" requestURI="/organization" pagesize="10">
<display:caption>Organization Records</display:caption>
<display:column title="Id">
<c:out value="${record.id}"></c:out>
<input type="hidden" name="id" value="${record.id}" />
</display:column>
<display:column title="Name" >
<c:out value="${record.name}"></c:out>
<input type="hidden" name="name" value="${record.name}" />
</display:column>
<display:column media="html">
<input type="button" onclick="makeEditable(this)" value="update" />
<input type="button" onclick="makeEditable(this)" value="view" />
</display:column>
</display:table>
</body>
</html>

Passing parameter from controller to jsp in spring

I have a controller method as follow.
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
model.addAttribute("id",jobId);
return "edit";
}
in which i am passing the jobId to get the instance of the job by id and returning "edit" string so that it maps to edit.jsp as per the InternalResourceViewResolver. But when i click on the link it goes to /edit/44 in which case 44 would be the id of the job for which the edit link belongs to. Finally i got the error stating no resource found.
home.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page session="false"%>
<html>
<head>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/css/style.css"/>" />
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<title>Home</title>
</head>
<body id="main">
<div class="container">
<h2 style="color:white">All posted jobs</h2>
<c:if test="${empty jobList}">
<h6>No Job Post Yet</h6>
</c:if>
<c:if test="${!empty jobList}">
<c:forEach items="${jobList}" var="job">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">${job.title }</h3>
</div>
<div class="panel-body">${job.description }</div>
<div class="panel-footer">
<a id="link" href="delete/${job.id }">Delete</a>
<a id="link" href="edit/${job.id}">Edit</a>
</div>
</div>
</c:forEach>
</c:if>
<section>
<form:form method="post" action="add" modelAttribute="job"
class="form-horizontal">
<div class="form-group" id="addForm">
<form:label class="control-label" path="title">Title:</form:label>
<form:input class="form-control" path="title"/>
<form:label class="control-label" path="description">Description</form:label>
<form:textarea class="form-control" rows="5" path="description" />
<button class="btn btn-success">
<span class="glyphicon glyphicon-plus-sign"></span> Add a Job
</button>
</div>
<a id="addJob" href="add">+</a>
</form:form>
</section>
</div>
JobController.java
package com.job.src;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.job.src.model.Job;
import com.job.src.services.JobService;
#Controller
public class JobController {
#Autowired
private JobService jobService;
#RequestMapping(value= "/")
public String listJobs(Map<String,Object> map){
map.put("job", new Job());
map.put("jobList", jobService.listJobs());
return "home";
}
#RequestMapping(value= "/add", method=RequestMethod.POST)
public String addJob(Job job){
jobService.addJob(job);
return "redirect:/";
}
#RequestMapping("/delete/{jobId}")
public String deleteJob(#PathVariable("jobId") Integer jobId){
jobService.removeJob(jobId);
return "redirect:/";
}
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
model.addAttribute("id",jobId);
return "edit";
}
}
edit.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/css/style.css"/>" />
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="post" action="editSuccess" modelAttribute="job"
class="form-horizontal">
<div class="form-group" id="addForm">
<form:label class="control-label" path="title">Title: </form:label>
<form:input class="form-control" path="title" />
<form:label class="control-label" path="description">Description</form:label>
<form:textarea class="form-control" rows="5" path="description" />
<button class="btn btn-success">
<span class="glyphicon glyphicon-plus-sign"></span> Add a Job
</button>
</div>
</form:form>
In editJob method your are returning only id of job with model attribute to edit.jsp. But actually on edit.jsp page you need job object so you need to get job object by id add it as model attribute.
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
//model.addAttribute("id",jobId); this is wrong
Job job = jobService.getJobById(jobId);
//write method in jobservice to get job by id i.e. getJobById(Integer jobId);
model.addAttribute("job",job)
return "edit";
}

Spring unable to get form values

Im using the below servlet to get the form values, when the form is posted im able to get the username and password but unable to access it in the mainpage.jsp which displays the username/password.
Servlet
package com.school.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.school.beans.Login;
#Controller
public class Logincontroller {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "loginform", new Login());
}
#RequestMapping(value = "/validatelogin", method = RequestMethod.POST)
public String validatelogin(#ModelAttribute("SchoolManagement")Login login,
ModelMap model) {
model.addAttribute("username", login.getUsername());
model.addAttribute("password", login.getPassword());
System.out.println("useranme = " + login.getUsername());
System.out.println("password = " + login.getPassword());
return "mainpage";
}
}
login.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<!--
<script src="javascript/login.js"></script>
<link rel="stylesheet" type="text/css" href="css/login.css"/>
http://www.mkyong.com/spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/
-->
<!--<script src="<c:url value="/resources/js/jquery.1.10.2.min.js" />"></script>-->
<link href="<c:url value="/resources/css/login.css" />" rel="stylesheet">
<script src="<c:url value="/resources/js/login.js" />"></script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="top"></div>
<div id="middle">
<form:form method="POST" id="loginform" commandName="loginform"
action="/SchoolManagement/validatelogin">
<form:label path="username"> Username:</form:label>
<form:input path="username" /> <br>
<form:label path="password"> Password:</form:label>
<form:input path="password" />
<input type="submit" value="submit">
</form:form>
</div>
<div id="bottom"></div>
</body>
</html>
mainpage.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>MainPage</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
</table>
</body>
</html>
Try getting the values directly out of the request.
<%
String username = (String) request.getAttribute("username");
String password = (String) request.getAttribute("password");
%>
<table>
<tr>
<td>Name</td>
<td><%= username %></td>
</tr>
<tr>
<td>Password</td>
<td><%= password %></td>
</tr>
</table>
That should definitely work... if not, something's wrong with the setup.
your command name
commandName="loginform"
is different than model attribute
#ModelAttribute("SchoolManagement")
try to use same names

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}

Categories

Resources