无法解决以下错误,尝试了不同的解决方案,但仍然遇到同样的错误,请帮忙。我看过很多类似的帖子,但没有什么对我有用。所以我将使用我的代码示例再次发布它。我是Spring MVC的新手,并尝试制作一个简单的表单来将产品添加到数据库中。但是我得到了"无论是BindingResult还是纯粹的目标对象都没有豆子名称'产品'可用作请求属性"一次又一次。下面是控制器和jsp文件:
Controller:
package com.me.secretsanta.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.me.secretsanta.dao.ProductDAO;
import com.me.secretsanta.pojo.Product;
import com.me.secretsanta.validator.ProductValidator;
@Controller
@RequestMapping(value="/addProduct.htm")
public class AddProductController {
@Autowired
@Qualifier("productDAO")
ProductDAO pdao;
@Autowired
@Qualifier("productValidator")
ProductValidator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(method=RequestMethod.GET)
public ModelAndView addProductPage() {
return new ModelAndView("admin-dashboard", "product", new Product());
}
@RequestMapping(method=RequestMethod.POST)
public ModelAndView saveProduct(@ModelAttribute("product") Product product, BindingResult result) throws Exception {
String modelObject=null;
Map<String, Object> map = new HashMap<String,Object>();
validator.validate(product, result);
if(result.hasErrors()) {
return new ModelAndView("admin-dashboard", "product", product);
}
Boolean saved = pdao.addProduct(product);
int count = 1;
map.put("msgtyp", "add");
if(saved) {
map.put("msgfor", "success");
map.put("rowcount", count);}
else {
map.put("msgfor", "error");
map.put("msg", "Could not save movie");
}
return new ModelAndView("resultsView", "map", map);
}
}
_______________________________________________________________________________
JSP:
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@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>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<h1>Please enter the details below :</h1>
<p>
<form:form action="${contextPath}/addProduct.htm" commandName="product" method="post">
Product Name Title :   <form:input path="name"/><form:errors path="name"/>
<br>
Product Code :   <form:input path="code"/><form:errors path="code"/>
<br>
Product Quantity :   <form:input path="quantity"/><form:errors path="quantity"/>
<br>
Product Price :   <form:input path="price"/><form:errors path="price"/>
<br>
<input type="submit" value="Add Product">
</form:form>
</p>
</body>
</html>
________________________________________________________________________________
Error:
HTTP Status 500 – Internal Server Error
--------------------------------------------------------------------------------
Type Exception Report
Message java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'product' available as request attribute
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'product' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:565)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'product' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:178)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:164)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:151)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:142)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:126)
org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:421)
org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
org.apache.jsp.WEB_002dINF.views.admin_002ddashboard_jsp._jspx_meth_form_005finput_005f0(admin_002ddashboard_jsp.java:374)
org.apache.jsp.WEB_002dINF.views.admin_002ddashboard_jsp._jspService(admin_002ddashboard_jsp.java:166)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
--------------------------------------------------------------------------------
Product Validator:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.me.secretsanta.validator;
import com.me.secretsanta.pojo.Product;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
*
* @author Sanchit
*/
public class ProductValidator implements Validator{
@Override
public boolean supports(Class type) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
return type.equals(Movie.class);
}
@Override
public void validate(Object o, Errors errors) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "emty-name", "Name cannot be empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "emty-code", "Code cannot be empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "quantity", "emty-quantity", "Quantitycannot be empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "emty-price", "Price cannot be empty");
}
}
----------------------------------------------------------------------------
ProductDAO:
package com.me.secretsanta.dao;
import com.me.secretsanta.pojo.Movie;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class ProductDAO {
private static final SessionFactory sf = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
public ProductDAO() {
}
public Boolean addProduct(Product mv) throws Exception{
try {
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(mv);
tx.commit();
session.close();
return true;
} catch (Exception ex) {
System.out.println("Cannot save object" + ex.getMessage());
return false;
}
}
public List<Product> searchProduct(String keyword, String choice) throws Exception{
List<Product> productList = new ArrayList<Product>();
// Product product;
String select_query= "from Product where "+choice+"= :"+choice;
// String select_query= "from Product where name= :name";
try {
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Query q=session.createQuery(select_query);
q.setString(choice,keyword);
productList = q.list();
tx.commit();
session.close();
} catch (Exception ex) {
System.out.println("Cannot retrieve data " + ex.getMessage());
}
return productList;
}
}