I am studying Spring MVC, and I have a problem with understanding how to use my classes in jsp, here is my controller:
#Controller
public class BusinessController {
#Autowired
private BusinessService businessService;
#RequestMapping("/index")
public String listContacts(Map<String, Object> map) {
map.put("business", new Business());
map.put("businessList", businessService.listBusiness());
return "business";
}
#RequestMapping("/find/{businessDate}")
public String listContactsByDate(#PathVariable("businessDate") Map<String, Object> map, String businessDate) {
map.put("businessByDate", new Business());
map.put("businessByDateList", businessService.listBusinessByDate(businessDate));
return "businessByDate";
}
#RequestMapping("/")
public String home() {
return "redirect:/index";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addBusiness(#ModelAttribute("business") Business business, BindingResult result) {
businessService.addBusiness(business);
return "redirect:/index";
}
#RequestMapping("/delete/{businessId}")
public String deleteBusiness(#PathVariable("businessId") Integer businessId) {
businessService.removeBusiness(businessId);
return "redirect:/index";
}
}
And here is my jsp:
<!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=utf8">
<title><spring:message code="label.title" /></title>
</head>
<body>
<h2>
<spring:message code="label.title" />
</h2>
<form:form method="post" action="add" commandName="business">
<table>
<tr>
<td><form:label path="businessDate">
<spring:message code="label.date" />
</form:label></td>
<td><form:input path="businessDate" /></td>
</tr>
<tr>
<td><form:label path="description">
<spring:message code="label.description" />
</form:label></td>
<td><form:input path="description" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="<spring:message code="label.addbusiness"/>" /></td>
</tr>
</table>
</form:form>
<form:form method="post" action="/find/{$businessDate}"
commandName="businessByDate">
<table>
<tr>
<td><form:label path="businessDate">
<spring:message code="label.date" />
</form:label></td>
<td><form:input path="businessDate" /></td>
</tr>
</table>
<c:if test="${!empty businessByDateList}">
<table class="data">
<tr>
<th><spring:message code="label.date" /></th>
<th><spring:message code="label.description" /></th>
<th> </th>
</tr>
<c:forEach items="${businessByDate}" var="business">
<tr>
<td>${businessByDate.businessDate}</td>
<td>${businessByDate.description}</td>
<td><a href="delete/${businessByDate.id}"><spring:message
code="label.delete" /></a></td>
</tr>
</c:forEach>
</table>
</c:if>
</form:form>
<h3>
<spring:message code="label.businesses" />
</h3>
<c:if test="${!empty businessList}">
<table class="data">
<tr>
<th><spring:message code="label.date" /></th>
<th><spring:message code="label.description" /></th>
<th> </th>
</tr>
<c:forEach items="${businessList}" var="business">
<tr>
<td>${business.businessDate}</td>
<td>${business.description}</td>
<td><a href="delete/${business.id}"><spring:message
code="label.delete" /></a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
And, here is my service implementation class:
#Repository
public class BusinessDAOImpl implements BusinessDAO{
#Autowired
private SessionFactory sessionFactory;
public void addBusiness(Business business){
sessionFactory.getCurrentSession().save(business);
}
#SuppressWarnings("unchecked")
public List<Business> listBusinessByDate(String businessDate){
String hql = "from Business B where B.date = :business_date";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("business_date", businessDate);
return query.list();
}
#SuppressWarnings("unchecked")
public List<Business> listBusiness(){
return sessionFactory.getCurrentSession().createQuery("from Business").list();
}
public void removeBusiness(Integer id){
Business business = (Business) sessionFactory.getCurrentSession().load(
Business.class, id);
if (null != business) {
sessionFactory.getCurrentSession().delete(business);
}
}
}
Without the part of jsp, where I try to list businesses for date everything works fine, I can add a business and it will be immediately listed in a table below, but if I add a part with businessByDate I'll get
Neither BindingResult nor plain target object for bean name 'businessByDate' available as request attribute
How can I solve that? Thank you
enter code here
That's coming out of this form tag:
<form:form method="post" action="/find/{$businessDate}"
commandName="businessByDate">
It looks like you only do:
map.put("businessByDate", new Business());
In the method that is this form's action. You need to add that object to the map in the method that actually loads the page!
Related
Not sure what I'm doing wrong on this one. Attempting to make a button that can delete added entities from database. I'm getting a 405 error but I am not sure if I'm getting this because of something I'm doing in the controller or something badly I wrote in thymeleaf. Thanks for any help.
Controller:
#Controller
public class BuyerController {
private BuyerService buyerService;
#Autowired
public void setBuyerService(BuyerService buyerService){
this.buyerService = buyerService;
}
#RequestMapping("/add-buyer")
public String showBuyerPager(Model model){
List<Buyer> buyers = buyerService.findAllBuyers();
model.addAttribute("buyers", buyers);
model.addAttribute("buyer", new Buyer());
return "add-buyer";
}
#GetMapping("/showBuyerForm")
public String addBuyerForm(Model model){
model.addAttribute("buyer", new Buyer());
model.addAttribute("buyerId", new Buyer().getBuyerId());
return "add-buyer";
}
#PostMapping("/addBuyer")
public String postBuyerForm(#ModelAttribute("buyer") Buyer buyer, Model model){
buyerService.saveBuyer(buyer);
model.addAttribute("buyer", new Buyer());
return "redirect:/";
}
#GetMapping("/deleteBuyer")
public String deleteBuyer(#RequestParam("buyerid") Long id){
buyerService.deleteBuyer(id);
return "redirect:/";
}
}
View:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
<link href="styles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<header> Welcome to Toner Stock </header>
<h1>Add Buyer</h1>
<div id="mynav" align="center">
<ul>
<li>Home</li>
<li>Add Buyer</li>
<li>Add Manager</li>
<li>Current Stock</li>
<li>Transactions</li>
<li>Order Form</li>
</ul>
</div>
<div id="display-table" align="center">
<form th:action="#{/addBuyer}" th:object="${buyer}" style="width:100%" method="post">
<table>
<td><label>First Name: </label></td>
<td><input type="text" th:field="*{firstName}"/></td>
<td><label>Last Name: </label></td>
<td><input type="text" th:field="*{lastName}"/></td>
<td><label>Enter Address: </label></td>
<td><input type="text" th:field="*{buyerAddress}"/></td>
<td><input type="submit" value="save"/></td>
</table>
</form>
</div>
<div>
<div>
<table id="info-table" align="center" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
<tr th:each="buyer : ${buyers}">
<td th:text="${buyer.firstName}"></td>
<td th:text="${buyer.lastName}"></td>
<td th:text="${buyer.buyerAddress}"></td>
<td>
<form th:action="#{/deleteBuyer}" th:object="${buyer}" method="post">
<input type="hidden" name="buyerid" id="buyerid" value="${buyer.buyerId}"/>
<input type="submit" value="Delete" onClick="return confirm('sure?')"/>
</form>
</td>
</tr>
</table>
</div>
</div>
<div>
<select>
<option th:each="buyer : ${buyers}"
th:text="${buyer.firstName}"
th:value="${buyer.buyerId}"
></option>
</select>
</div>
<div>
<div>
</div>
</div>
</body>
</html>
I don't know much about Thymeleaf but you can keep it simpler and change your front-end code from form to basic link :
<c:url var="deleteBuyer" value="/DeleteBuyer">
<c:param name="buyerId" value="${buyer.buyerId}" />
</c:url>
<a class="simpleLink" href="${deleteBuyer}">delete</a>
And handle it in your controller :
` #GetMapping("/DeleteBuyer")
public String deleteAnswer(#RequestParam("buyerId") int theId) {
buyerService.deleteBuyer(theId);
return "redirect:/";
}`
I hope this help you.
Change the
<form th:action="#{/deleteBuyer}" th:object="${buyer}" method="post">
To GET to conform with the Spring request mapping
<form th:action="#{/deleteBuyer}" th:object="${buyer}" method="get">
Here are all available HTTP Methods
EDIT:
I want to show a spring-mvc dropdown box out of a object list which is a property from another class.
I did this after searching:
<sf:form action="${pageContext.request.contextPath}/venta/save"
method="post" commandName="venta">
<table>
<tr>
<td>Número de factura</td>
<td><sf:input path="numero_factura" type="text" /></td>
<td><sf:errors path="numero_factura" cssclass="error" /></td>
</tr>
<tr>
<td>Producto:</td>
<td><sf:select path="${producto.nombreProducto}">
<sf:option value="" label="...." />
<sf:options items="${productos}" />
</sf:select></td>
<td><sf:errors path="${producto.nombreProducto}"
cssclass="error" cssStyle="color: #ff0000;" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Guardar cambios"></td>
</tr>
<tr>
</table>
</sf:form>
The class I'm mapping is this:
Venta.class
#Entity
public class Venta implements Serializable {
#Id
#NotNull
#Digits(integer=12, fraction = 0)
private Integer numero_factura;
#LazyCollection(LazyCollectionOption.FALSE)
#ManyToMany
#NotEmpty
private List<Producto> productos = new ArrayList<Producto>();
private Date fechaDeIngreso;
#ManyToOne(cascade = CascadeType.ALL)
private Empleado empleado;
public Venta() {
}
...
}
And this is the controller:
#Controller
public class VentaController {
#Autowired
public IServiceProducto serviceProducto;
#Autowired
public IServiceVenta serviceVenta;
#Autowired
public IServiceEmpleado serviceEmpleado;
#RequestMapping("/venta")
public String showVenta(Model model, HttpSession session) {
// Model es una interfaz que nos permite definir atributos en el modelo
init(model);
return "venta";
}
#RequestMapping(value = "/venta/save", method = RequestMethod.POST)
public String handleVenta(#Valid #ModelAttribute("venta") Venta ventaForm, BindingResult result, Model model,
HttpSession session, RedirectAttributes ra) {
try {
if (result.hasErrors()) {
model.addAttribute("productos", serviceProducto.getAll());
return "venta";
}
Empleado empleado = (Empleado) session.getAttribute("empleado");
empleado.setVenta(ventaForm);
serviceVenta.exist(ventaForm);
serviceEmpleado.addChild(empleado, ventaForm);
ra.addFlashAttribute("resultado", "La venta fué agregada exitosamente");
return "redirect:/venta";
} catch (ServicioException e) {
ra.addFlashAttribute("resultado", e.getMessage());
return "redirect:/venta";
}
}
public void init(Model model){
Venta venta = new Venta();
Producto producto = new Producto();
model.addAttribute("venta", venta);
model.addAttribute("producto", producto);
model.addAttribute("productos", serviceProducto.getAll());
}
}
It gives me the view I was looking for, but this code is doing nothing when it comes to select an item from the dropdown box and hitting the submit button. It gives me no error and stay static in http://localhost:8585/electronicaDonPepe/venta/save
Please please help me, I'm almost there !
OLD VERSION:
I want to show a combobox in jsp from a list. It gives me a dropdownlist which I don't want.
I made a map with the list and it gives me the same result.
Venta.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="sf" 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<sf:form action="${pageContext.request.contextPath}/venta/save"
<td>Producto</td>
<td>
<sf:select path="productos">
<sf:option label="---select---" value="NONE"/>
<sf:options items="${productos}"/>
</sf:select>
</td>
<td><sf:errors path="productos" cssClass="error"/> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Guardar cambios"></td>
</tr>
</table>
</sf:form>
<c:out value="${resultado}"></c:out>
</body>
</html>
Necessary VentaController.java code to understand
#Controller
public class VentaController {
#Autowired
public IServiceProducto serviceProducto;
#Autowired
public IServiceVenta serviceVenta;
#Autowired
public IServiceEmpleado serviceEmpleado;
#RequestMapping("/venta")
public String showVenta(Model model, HttpSession session) {
// Model es una interfaz que nos permite definir atributos en el modelo
Venta venta = new Venta();
model.addAttribute("venta", venta);
List<Producto> listaProductos = serviceProducto.getAll();
Map<String, String> mapaProductos = new LinkedHashMap<String, String>();
for (Producto producto : listaProductos) {
mapaProductos.put(producto.getNombreProducto(), producto.getNombreProducto());
}
model.addAttribute("productos", mapaProductos);
return "venta";
}
The result is a list with multiple selections. I'm aware that if I use the property multiple=false the multiple selection will be off but it still work in my case.
DropdownList with multiple selection
Still, I want a combobox function and not a dropdownlist without multiple selection.
This is my idea of what I want:
select with options
I have this approach:
<sf:form action="${pageContext.request.contextPath}/venta/save"
method="post" commandName="ventaDTO">
<table>
<tr>
<td>Número de factura</td>
<td><sf:input path="numero_factura" type="text" />
<td><sf:errors path="numero_factura" cssclass="error" /></td>
</tr>
<tr>
<td>Producto:</td>
<td><sf:select path="nombreProducto">
<sf:option value="" label="...." />
<sf:options items="${productos}" />
</sf:select> <sf:errors path="nombreProducto" cssclass="error"
cssStyle="color: #ff0000;" /></td>
<td>
<td><sf:input path="cantidadProductos" type="text" />
<sf:errors
path="cantidadProductos" cssclass="error"
cssStyle="color: #ff0000;" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Guardar cambios"></td>
</tr>
</table>
</sf:form>
but still can't add another whole table in order to add a particular product in quantities. I was thinking about using angularjs but I'm new to that technology. I'll be very thankful for your help.
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.
Hi I am getiing the above exception : java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'Projet' available as request attribute. Please find my jsp and controller class.
The code I have is like below.
Controller code:
#Controller
#RequestMapping(value="/directeur")
public class AdminController {
#Autowired
private IAdmin directeur;
#RequestMapping(value="/index")
public String index(Model model)
{
model.addAttribute("Projet",new Projet());
model.addAttribute("Projets",directeur.getAllProjet());
return "Projets";
}
#RequestMapping(value="/saveProjet",method = RequestMethod.POST)
public String saveProjet(Projet p,BindingResult result,Model model) throws IOException
{
if(result.hasErrors())
{
model.addAttribute("Projets",directeur.getAllProjet());
return "Projets";
}
directeur.ajouterProjet(p);
model.addAttribute("Projet",new Projet());
model.addAttribute("Projets",directeur.getAllProjet());
return "Projets";
}
}
Jsp Code:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<div id="formProjet">
<f:form modelAttribute="Projet" action="saveProjet" method="POST"
enctype="multipart/form-data">
<table>
<tr>
<td>ID Projet</td>
<td><f:input path="idProjet" /></td>
<td><f:errors path="idProjet" cssClass="errors"/></td>
</tr>
<tr>
<td>Nom</td>
<td><f:textarea path="nomProjet" /></td>
<td><f:errors path="nomProjet" cssClass="errors"/></td>
</tr>
<tr>
<td>Description du Projet</td>
<td><f:textarea path="description" /></td>
<td><f:errors path="description" cssClass="errors"/></td>
<tr><td><input type="submit" value="enregistrer"/></td></tr>
</table>
</f:form>
</div>
<div id="">
<table>
<tr>
<th>ID</th>
<th>Nom</th>
<th>Description</th>
<th>Photo</th>
</tr>
<c:forEach items="${Projets }" var="proj">
<tr>
<td>${proj.idProjet }</td>
<td>${proj.nomProjet }</td>
<td>${proj.description }</td>
<td></td>
</tr>
</c:forEach>
</table>
</div>
I was working with spring and read about the use of commandName in view(jsp). I have a little trouble working with it can anyone help me how to effectively use it?
i get this error when i use in my jsp page.
SEVERE: Servlet.service() for servlet [dispatcher] in context with path
[/hibernateAnnotaionWithSpring] threw exception [An exception occurred processing JSP
page /WEB-INF/jsp/userForm.jsp at line 17
14: <table>
15: <tr>
16: <td>User Name :</td>
17: <td><form:input path="name" /></td>
18: </tr>
19: <tr>
20: <td>Password :</td>
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for
bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
my code is as follows:-
when i click on submit button it should take me to userForm page
<form action="login.htm">
<table class="hundredPercent headerBackground" cellspacing="0">
<tr>
<td class="textLabel sevenPer">
Email
</td>
<td class="textField sevenPer">
<input type="text" value="" name="username">
</td>
<td class="textLabel sevenPer">
Password
</td>
<td class="textField sevenPer">
<input type="password" value="" name="password">
</td>
<td class="textField">
<input type="submit" value="Enter" name="submit" class="buttonSubmit">
</td>
<td>
</td>
<td class="textLabel">
<a href="list.htm" >Register</a>
</td>
</tr>
</table>
</form>
my controller class
#RequestMapping("/login.htm")
public String login(HttpServletRequest request,
HttpServletResponse response,ModelMap model) throws Exception {
String userName= request.getParameter("username");
String password= request.getParameter("password");
System.out.println("name===="+userName);
return "userForm";
}
finally my resultant jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
</head>
<body>
<form:form action="add.htm" commandName="user" method="POST">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton
path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="India" label="India" />
<form:option value="USA" label="USA" />
<form:option value="UK" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><form:checkbox path="community" value="Spring"
label="Spring" /> <form:checkbox path="community"
value="Hibernate"
label="Hibernate" /> <form:checkbox path="community"
value="Struts"
label="Struts" /></td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
</form:form>
</body>
</html>
Can anyone please help on this?
Thanks in advance
You need to add an empty user to the model.
#RequestMapping("/login.htm")
public String login(HttpServletRequest request,
HttpServletResponse response, ModelMap model) throws Exception {
String userName= request.getParameter("username");
String password= request.getParameter("password");
System.out.println("name===="+userName);
model.addAttribute("user", new User(...)):
return "userForm";
}
in addition you have to write:
<form:form action="add.htm" modelAttribute="user" method="POST">
(modelAttribute instead of commandName)
Anyway your controller is a bit uncommon. Try This:
#RequestMapping(value="/login.htm" method = RequestMethod.GET)
public String loginForm(ModelMap model) throws Exception {
model.addAttribute("user", new User("", "")):
return "userForm";
}
#RequestMapping(value="/login.htm" method = RequestMethod.POST)
public String login(User user) throws Exception {
String userName= user.getUsername();
String password= user.getPassword();
...
}
/** The command class */
public class User{
private String username;
private String password:
Getter and Setter
}