I have a form that has two buttons, a submit button and an update button.
Here is the JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- Bootstrap core CSS !-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Custom scripts/styles for this page !-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/script/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/script/script.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/style.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
</head>
<body>
<!-- General Information Form -->
<form:form id="form" method="POST" action="${pageContext.request.contextPath}/create" modelAttribute="task">
<div id="general">
<table style="width: 224px;">
<tr>
<td colspan="2"><form:select id="systemType" path="systemType" items="${systemTypes}" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td colspan="2"><form:select id="userName" path="user.fullName" items="${userFullNames}" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td style="width: 50%;"><label for=line><b>Line: </b></label></td>
<td><form:select path="location.line" items="${lines}" id="line"/></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td style="width: 50%;"><label for=position><b>Position: </b></label></td>
<td><form:select path="location.position" items="${positions}" id="position" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td colspan="2">
<input id="submitButton" type="submit" name="submit" value=Submit />
<input style="display:none;" id="updateButton" type="submit" name="update" value="Update" />
<input id="cancel" style="float: right;" type="Reset" value="Cancel" />
</td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
Here is my controller:
#Controller
#RequestMapping("/")
public class HomeController {
private TaskService taskService;
#Autowired
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String initForm(Model model, HttpServletRequest request) {
Task task = new Task();
model.addAttribute("task", task);
return "home";
}
#RequestMapping(value="/create", params="submit", method = RequestMethod.POST)
public String submitForm(#ModelAttribute("task")Task task,BindingResult result, Model model) {
taskService.create(task);
return "redirect:/";
}
#RequestMapping(value="/create", params="update", method = RequestMethod.POST)
public String updateForm(#ModelAttribute("task")Task task, BindingResult result, Model model) {
System.out.println("Updating: " + task.toString());
taskService.update(task);
return "redirect:/";
}
The idea being that hitting the submit button will make a new item, and the update button will edit an existing one. The two .POST methods have different parameters specified to distinguish them.
The submit button is working as expected. However when the update button is pressed a Task object is delivered to the updateForm controller method - but all of its fields are null.
I am not sure why the form is binding the fields to the Task correctly on the submit method, but seemingly creating a new Task and not binding it at all in the update method.
I am inclined to just combine these methods into a single controller method and use some Java logic to determine whether to submit/update based on the parameter - but am curious as to what I'm missing and why this doesn't work.
Ok, I feel very stupid. This was not a SpringMVC issue at all. The problem was caused by a Jquery method that was disabling a part of the form. This gave the appearance that the form was not binding, but actually it was just binding to null values.
Related
I have a problm with update link for updating my transaction. At one jsp I have a list with transactions, and after pressing Update" which is link i wanted to pass transactionId, update it, save and get back to list. I've used c:param hidden and it doesnt work. I have no idea why it doesnt pass id and autofill forms. It seems like values are passed in session when ive clicked testing transaction:
http://localhost:8080/transaction/addTransaction?transactionId=64&userId=1
Here is transaction Controller:
#Controller
#RequestMapping("/transaction")
public class TransactionController {
#Autowired
TransactionService transactionService;
#Autowired
CategoryService categoryService;
#Autowired
UserService userService;
#GetMapping("/addTransaction")
public String transactionsList(Model theModel){
Transaction transaction = new Transaction();
theModel.addAttribute("user",userService.getAllUsers());
theModel.addAttribute("category", categoryService.getAllCategories());
theModel.addAttribute("newTransaction", transaction);
return "addTransaction";
}
#PostMapping("/saveTransaction")
public String saveTransaction(#ModelAttribute("newTransaction") Transaction
newTransaction,
BindingResult theBindingResult,
HttpServletRequest request) throws
ParseException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String date = request.getParameter("transactionDate");
LocalDate localDate = LocalDate.parse(date, formatter);
Date formatedDate =
Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.ofHours(-3)));
newTransaction.setTransactionDate(formatedDate);
transactionService.saveTransaction(newTransaction);
return "redirect:/user/userPage";
}
#GetMapping("/deleteTransaction")
public String deleteUser(#RequestParam("transactionId") int idFromTransactionToDelete,
#RequestParam("userId") int loggedUserId,
RedirectAttributes redirectAttributes){
transactionService.deleteTransactionById(idFromTransactionToDelete);
User loggedUser = userService.getUserById(loggedUserId);
redirectAttributes.addFlashAttribute("loggedUser", loggedUser);
return "redirect:/user/userPage";
}
#GetMapping("/updateTransaction")
public String updateUser(#RequestParam("transactionId") int
idFromTransactionToUpdate,
#RequestParam("userId") int loggedUserId,
RedirectAttributes redirectAttributes,
Model theModel){
Transaction transactionToUpdate = transactionService.getSingleTransactionById(idFromTransactionToUpdate);
transactionToUpdate.setUser(userService.getUserById(loggedUserId));
theModel.addAttribute("newTransaction",transactionToUpdate);
theModel.addAttribute("category", categoryService.getAllCategories());
User loggedUser = userService.getUserById(loggedUserId);
redirectAttributes.addFlashAttribute("loggedUser", loggedUser);
redirectAttributes.addFlashAttribute("newTransaction",
transactionToUpdate);
return "addTransaction";
}
}
Transactions list page:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<html>
<head>
<title>User page</title>
</head>
<body>
<c:url var="addTransactionLink" value="/transaction/addTransaction"/>
<c:url var="addFixedTransactionLink"
value="/fixedTransaction/addFixedTransaction"/>
<h1>Welcome ${loggedUser.login} !</h1>
<br>
<h2>Here are your latest transactions:</h2>
<br>
<a href=${addTransactionLink}>
<input type="button" value="Add Transaction"/>
</a>
<a href=${addFixedTransactionLink}>
<input type="button" value="Add Fixed Transaction"/>
</a>
<table>
<tr>
<th>Category</th>
<th>Price</th>
<th>Description</th>
<th>Date</th>
</tr>
<c:forEach var="transaction" items="${userTransactions}">
<c:url var="deleteTransactionLink"
value="/transaction/deleteTransaction">
<c:param name="transactionId"
value="${transaction.transactionId}"/>
<c:param name="userId" value="${loggedUser.id}"/>
</c:url>
<c:url var="updateTransactionLink"
value="/transaction/addTransaction">
<c:param name="transactionId"
value="${transaction.transactionId}"/>
<c:param name="userId" value="${loggedUser.id}"/>
</c:url>
<tr>
<td>${transaction.category.categoryName}</td>
<td>${transaction.moneyAmount}</td>
<td>${transaction.description}</td>
<td>${transaction.transactionDate}</td>
<td>Delete </td>
<td>Update </td>
<td>${transaction.transactionId}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
And add transaction formular:
<%# taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Add Transaction Form</title>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css"/>
</head>
<body>
<h1>Add transaction to database:</h1>
<form:form action="saveTransaction" modelAttribute="newTransaction"
method="post">
<form:hidden path="transactionId"/>
${newTransaction.toString()}
${newTransaction.transactionId}
<table>
<tr>
<td><label>Choose category:</label></td>
<td><form:select name="category.id" path="category.id">
<c:forEach items="${category}" var="category">
<form:option value="${category.id}">${category.categoryName}
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><label>Choose user:</label></td>
<td><form:select name="user.id" path="user.id">
<c:forEach items="${user}" var="user">
<form:option value="${user.id}">${user.login}
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><label>Amount:</label></td>
<td><form:input path="moneyAmount" />
</td>
</tr>
<tr>
<td><label>Transaction date:</label></td>
<td><form:input type = "date" path="transactionDate"/>
</td>
</tr>
<tr>
<td><label>Description:</label></td>
<td><form:input path="description" />
</td>
</tr>
<tr>
<label></label>
<td><input type="submit" value="Submit" class="save"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Problem seems to be in your code. You have defined in jsp:
<c:url var="updateTransactionLink"
value="/transaction/addTransaction">
while in java code:
#GetMapping("/updateTransaction")
public String updateUser(#RequestParam("transactionId") int
In JSP Change it to :
<c:url var="updateTransactionLink"
value="/transaction/updateTransaction">
Currently in my project, addEmployee.jsp show properly when "Add Employee" or "Edit" is clicked, but when I try to hit submit button in "Add Employee" page, page return "Http status 500 Request processing failed; nested exception is java.lang.NullPointerException", or when I try to hit submit button in "Add Employee" page for update employee info, I will get "HTTP Status 405 - Request method 'POST' not supported"
The way I want is when I add a new employee or update the existing employee info, I will still using addEmployee.jsp page. If it is add a new one, all the field will be empty, otherwise, all the field will contain the existing information for update.
Here is the code for employee.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>
</head>
<body>
<div align="center">
<h1 style="background-color: lightgreen; color: darkgreen">Employee
Page</h1>
<table align="center" width="80%" cellspacing="0" cellpadding="5">
<tr>
<td align="center">
<table cellspacing="0" cellpadding="6" border="0" width="100%">
<tr bgcolor="lightblue">
<td align="left"><a
href="${pageContext.request.contextPath}/employee/addEmployee"
style="background-color: lightblue;"> Add Employee </a></td>
</table>
</td>
</tr>
<tr>
<td>
<table cellspacing="0" cellpadding="6" border="1" width="100%">
<tr>
<td colspan="8"
style="background-color: lightblue; color: darkgreen; font-size: 16pt"
align="center">Employee List</td>
</tr>
<tr bgcolor="grey" style="color: white">
<th>No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
<th>Department</th>
<th>Salary</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="employee" items="${employeesList}"
varStatus="status">
<tr bgcolor="lightyellow">
<td><b>${status.index + 1}</b></td>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.jobTitle}</td>
<td>${employee.department}</td>
<td>${employee.salary}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
And Here is the code for addEmployee.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#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>Add Employee</title>
</head>
<body>
<div align="center">
<h1 style="background-color: lightgreen; color: darkgreen">Add
New Employee Page</h1>
<table width="80%" align="center">
<tr bgcolor="lightblue">
<td align="left"><a href="listEmployees"
style="background-color: lightblue;">List Employee</a></td>
</table>
</div>
<br />
<div align="center">
<table cellspacing="0" cellpadding="6" border="1" width="80%">
<tr>
<td colspan="8"
style="background-color: lightblue; color: darkgreen; font-size: 16pt"
align="center">Employee Information</td>
</tr>
<tr>
<td><form:form method="POST" action="updateEmployee">
<table width="100%">
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td align="left" width="70%"><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td align="left" width="70%"><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="jobTitle">Job Title</form:label></td>
<td align="left" width="70%"><form:input path="jobTitle" /></td>
</tr>
<tr>
<td><form:label path="department">Department</form:label></td>
<td align="left" width="70%"><form:input path="department" /></td>
</tr>
<tr>
<td><form:label path="salary">Salary</form:label></td>
<td align="left" width="70%"><form:input path="salary" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form></td>
</tr>
</table>
</div>
</body>
</html>
Here is the code for EmployeeController.java
package com.vincent.springmvc.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.vincent.springmvc.model.Employee;
import com.vincent.springmvc.service.EmployeeService;
#Controller
#RequestMapping("/employee")
public class EmployeeController {
//Logger file
private static Logger logger = LoggerFactory.getLogger(EmployeeController.class);
#Autowired
private EmployeeService employeeService;
#RequestMapping(method = RequestMethod.GET)
public String welcomeEmployee(ModelMap model){
model.addAttribute("name", "Hello World!");
model.addAttribute("greetings", "Welcome to Spring MVC");
return "hello";
}
#RequestMapping(value = "/listEmployees", method = RequestMethod.GET)
public String listEmployees(ModelMap model){
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/addEmployee", method = RequestMethod.GET)
public ModelAndView addEmployee(ModelMap model){
return new ModelAndView("addEmployee", "command", new Employee());
}
#RequestMapping(value = "/updateEmployee", method = RequestMethod.POST)
public String updateEmployee(#ModelAttribute("employee") Employee employee, ModelMap model){
if(employee.getId() == 0)
this.employeeService.insertEmployee(employee);
else
this.employeeService.updateEmployee(employee);
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/delete/{empId}", method = RequestMethod.GET)
public String deleteEmployee(#PathVariable("empId") Integer empId, ModelMap model){
this.employeeService.deleteEmployee(empId);
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/edit/{empId}", method=RequestMethod.GET)
public ModelAndView editEmployee(#PathVariable("empId") int id, ModelMap model){
return new ModelAndView("addEmployee", "command", this.employeeService.getEmployeeById(id));
}
}
Here is the project structure
Project Structure
and the rest of the code you can find in https://github.com/zhengye1/SpringMVC
Thank you for the help
Kind of resolve for now.... but seems like not a very good idea, it is time to looking for good advice..
The way I fix is, in my controller class, I change the annotation in updateEmployee with following annotation #RequestMapping(value = {"/updateEmployee", "/edit/updateEmployee"}, method = RequestMethod.POST). This because when I tracing the log, I realize somehow the server try to mapping the page called edit/updateEmployee, originally is not exists, that is why it raising the 504 error for update.
For adding issue is causing by the form, since the form return the null id, therefore when I try to compare the null object with 0, it raise the null pointer exception. The way I fix is, change that line to if (employee.getId() == null), and also in addEmployee.jsp page, I add the this line to my form, <form:hidden path="id" />. That is resolve the issue.
My Spring JSP Form uses 2 classes that I put in a wrapper class. The employee name part works. But now I need to create a drop-down list of Clients to choose from. I'm updating someone else's code, I believe "resultBoard.getFilteredResultsClients()" will return a List of Clients. Any tips or sample code of a Spring JSP Form that uses a drop-down to select from a List?
Java wrapper class with employee and client classes inside:
public class EmployeeFormWrapper {
private NewEmployeeVM employee = new NewEmployeeVM();
private ClientVM client = new ClientVM();
public NewEmployeeVM getEmployee(){
return this.employee;
}
public ClientVM getClient(){
return this.client;
}
}
My Controller class:
#Controller
#SessionAttributes({"resultBoard", "filterBoard"})
public class NewEmployeeController {
#Autowired
NewEmpDAO newEmpDAO;
#RequestMapping(value = "NewEmpInput", method = RequestMethod.GET)
public String promptEmployee(Model model)
{
model.addAttribute("myForm", new EmployeeFormWrapper());
return "NewEmpInput";
}
#RequestMapping(value = "NewEmpInput", method = RequestMethod.POST)
public String newEmployee(#ModelAttribute("myForm") EmployeeFormWrapper myForm)
{
NewEmployeeVM employee = myForm.getEmployee();
ClientVM client = myForm.getClient();
System.out.println("Employee = " + employee.getFirstName() + " " + employee.getLastName());
System.out.println("Client = " + client.getText());
try{newEmpDAO.writeNewEmployee(employee);}
catch (Exception e){
e.printStackTrace();
}
return "ConfirmNewEmp";
}
}
My JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page session="false"%>
<%# page import="com.model.FilterBoard"%>
<!DOCTYPE html>
<!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -->
<html>
<head>
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="assets/css/bootstrap.css" rel="stylesheet">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<link rel="stylesheet"
href="<c:url value='/resources/css/mainStyle.css'/>">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style type="text/css">
body {
color:#000000;
// background-color:#FFFFFF;
background-color:tan;
background-image:url('Background Image');
background-repeat:no-repeat;
}
a { color:#0000FF; }
a:visited { color:#800080; }
a:hover { color:#008000; }
a:active { color:#FF0000; }
</style>
<title>New Employee Proposed To Project</title>
</head>
<body class="NewEmpBody">
<p>New Employee</p>
<form:form commandName="myForm" modelAttribute="myForm">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="employee.firstName" /></td>
<td>Middle Initial:</td>
<td><form:input path="employee.middleInitial" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="employee.lastName" /></td>
</tr>
<tr>
<td>Clients:</td>
<td>
<ul>
<c:forEach items="${resultBoard.getFilteredResultsClients()}"
var="filteredResultsClient">
<li><form:button name="toggleClient" class="btn btn-link"
value='${filteredResultsClient.toJSON()}'>
${filteredResultsClient.getText()}
</form:button></li>
</c:forEach>
</ul>
</td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
I got it, I changed my JSP to look like this and it gave me a nice drop-down list:
<body class="NewEmpBody">
<p>New Employee Proposed To Project Before Entered Into OpenAir</p>
<form:form commandName="myForm" modelAttribute="myForm">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="employee.firstName" /></td>
<td>Middle Initial:</td>
<td><form:input path="employee.middleInitial" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="employee.lastName" /></td>
</tr>
<tr>
<td>Client :</td>
<td><form:select path="client.text">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${resultBoard.getFilteredResultsClients()}" />
</form:select>
</td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
Hi I'm trying to make a "Clear Cart" button in my java code but i'm having difficulty.
I've been trying for a couple of hours but i can't get it to work
I think it has something to do mostly with the first part that has all the strings and variables.
Here's the code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%# page errorPage="errorpage.jsp" %>
<jsp:useBean id="cart" scope="session" class="beans.ShoppingCart" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>the Game Store</title>
</head>
<body>
<%
String id = request.getParameter("id");
if ( id != null ) {
String desc = request.getParameter("desc");
Float price = new Float(request.getParameter("price"));
cart.addItem(id, desc, price.floatValue(), 1);
}
%>
Shopping Cart Quantity:
<%=cart.getNumOfItems() %>
<hr>
<center><h3>Games</h3></center>
<table border="1" width="300" cellspacing="0"
cellpadding="2" align="center">
<tr><th>Description</th><th>Price</th></tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<td>Goat Simulator</td>
<td>$11.95</td>
<td><input type="submit" name="Submit" value="Add"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="Goat Simulator">
<input type="hidden" name="price" value="11.95">
</form>
</tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<td>Metal Gear Solid V</td>
<td>$59.99</td>
<td><input type="submit" name="Submit" value="Add"></td>
<input type="hidden" name="id" value="2">
<input type="hidden" name="desc" value="Metal Gear Solid V">
<input type="hidden" name="price" value="59.99">
</form>
</tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<input type ="submit" name="empty" id="empty-button" value="Empty Cart"/>
</form>
Clear
</tr>
</table>
</body>
</html>
Here's the second page for the entire page
<%# page errorPage="errorpage.jsp" %>
<%# page import="java.util.*" %>
<jsp:useBean id="cart" scope="session" class="beans.ShoppingCart" />
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Contents</title>
</head>
<body>
<center>
<table width="300" border="1" cellspacing="0"
cellpadding="2" border="0">
<caption><b>Shopping Cart Contents</b></caption>
<tr>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<%
Enumeration e = cart.getEnumeration();
String[] tmpItem;
// Iterate over the cart
while (e.hasMoreElements()) {
tmpItem = (String[])e.nextElement();
%>
<tr>
<td><%=tmpItem[1] %></td>
<td align="center">$<%=tmpItem[2] %></td>
<td align="center"><%=tmpItem[3] %></td>
</tr>
<%
}
%>
</table>
</center>
Back to Catalog
</body>
</html>
In this code, when user adds delete button, raw is being deleted from database, but user is being redirected to empty home page, unless he logs out and logs in again. how can I fix the code, so that when he deletes something, whole layout is not disappearing, but only the line that he deleted.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function del() {
if (confirm("Do You Want to Delete this Menu?")) {
} else {
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="images/style.css" type="text/css"
charset="utf-8" />
</head>
<body>
<%
menu_slno1 = request.getParameter("menu_slno");
if (menu_slno1 != null)
menu_slno = Integer.parseInt(menu_slno1);
delete_menu = request.getParameter("delete_menu");
if ("yes".equals(delete_menu)) {
MenuId = request.getParameter("MenuId");
x = stmt1
.executeUpdate("Delete from menu where MenuId="
+ MenuId);
}
%>
<center><h2>VIEW MENU</h2></center>
<center><table width="736" height="97" border="1"></center>
<%
if (x == 1) {
%>
<tr bgcolor="gray">
<th height="35" colspan="9"><div align="center">
Menu deleted successfully!
</div></th>
</tr>
<%
}
%>
<tr bgcolor="gray">
<td><div align="center">
<strong>Menu ID</strong>
</div></td>
<td><div align="center">
<strong>Name </strong>
</div></td>
<td><div align="center">
<strong>Info</strong>
</div></td>
<td><div align="center">
<strong>Price</strong>
</div></td>
<td colspan="2"><div align="center">
<strong>Action</strong>
</div></td>
</tr>
<%
String sUserID=request.getParameter("username");
session.setAttribute("username", sUserID);
int icount = 0;
rs = stmt.executeQuery("SELECT menu.menuID, menu.name, menu.info, menu.price, menu.RestaurantID FROM menu INNER JOIN clients ON menu.username = clients.username where menu.username='" +sUserID+ "'");
while (rs.next()) {
//menu_slno = rs.getInt("menu_slno");
MenuId = rs.getString("MenuId");
%>
<tr>
<td><div align="center"><%=++icount%></div></td>
<td><%=rs.getString("Name")%></td>
<td><%=rs.getString("Info")%></td>
<td><%=rs.getDouble("Price")%></td>
<td><div align="center">
Edit
</div></td>
<td><div align="center">
<a
href="view_menu.jsp?delete_menu=yes&MenuId= <%=MenuId%>&MenuId=<%=MenuId%>"
onclick="return del()">Delete</a>
</div></td>
</tr>
<%
}
%>
</table>
Add Menu
</body>
</html>
When a user clicks on the delete link, the username parameter is not set in the URL. So when the page refreshes, the String sUserID=request.getParameter("username"); call return null or empty, and then the rest of the page is not displayed because the following SQL Query returns nothing without a valid username.
It seems that you only need to add something like &username=<%=sUserID%> to your delete link to make it work:
Delete
P.S: I assume that this a legacy JSP, and that you have no choice but continuing using such ugly code. If you have a choice, I strongly recommend you to drop those scriptlets and this all-in-the-view architecture, and start using JSTL tags, servlets and beans.