• Spring MVC: Neither BindingResult nor plain target object for bean name customerForm


    今天在做Spring MVC练习的时候,使用spring的注解方式来写了一个简单的表单页面,但结果老是报错:"Neither BindingResult nor plain target object for bean name customerForm"。

    在google百度搜了大半天,综合了几个回答才返现是需要为表单添加一个modelAttribute属性,不然spring不知道将数据存放到什么地方去。

    //Customer.java
    package info.iloveec.springtags;
    
    import org.springframework.stereotype.Component;
    
    public class Customer {
    	
    	    //textbox
    		private String userName;
    	 
    		//textarea
    		private String address;
    	 
    		//password
    		private String password;
    		private String confirmPassword;
    	 
    		//checkbox
    		private boolean receiveNewsletter;
    		private String [] favFramework;
    	 
    		//radio button
    		private String favNumber;
    		private String sex;
    	 
    		//dropdown box
    		private String country;
    		private String javaSkills;
    	 
    		//hidden value
    		private String secretValue;
    
    		public String getUserName() {
    			return userName;
    		}
    
    		public void setUserName(String userName) {
    			this.userName = userName;
    		}
    
    		public String getAddress() {
    			return address;
    		}
    
    		public void setAddress(String address) {
    			this.address = address;
    		}
    
    		public String getPassword() {
    			return password;
    		}
    
    		public void setPassword(String password) {
    			this.password = password;
    		}
    
    		public String getConfirmPassword() {
    			return confirmPassword;
    		}
    
    		public void setConfirmPassword(String confirmPassword) {
    			this.confirmPassword = confirmPassword;
    		}
    
    		public boolean isReceiveNewsletter() {
    			return receiveNewsletter;
    		}
    
    		public void setReceiveNewsletter(boolean receiveNewsletter) {
    			this.receiveNewsletter = receiveNewsletter;
    		}
    
    		public String[] getFavFramework() {
    			return favFramework;
    		}
    
    		public void setFavFramework(String[] favFramework) {
    			this.favFramework = favFramework;
    		}
    
    		public String getFavNumber() {
    			return favNumber;
    		}
    
    		public void setFavNumber(String favNumber) {
    			this.favNumber = favNumber;
    		}
    
    		public String getSex() {
    			return sex;
    		}
    
    		public void setSex(String sex) {
    			this.sex = sex;
    		}
    
    		public String getCountry() {
    			return country;
    		}
    
    		public void setCountry(String country) {
    			this.country = country;
    		}
    
    		public String getJavaSkills() {
    			return javaSkills;
    		}
    
    		public void setJavaSkills(String javaSkills) {
    			this.javaSkills = javaSkills;
    		}
    
    		public String getSecretValue() {
    			return secretValue;
    		}
    
    		public void setSecretValue(String secretValue) {
    			this.secretValue = secretValue;
    		}
    		
    		
    }
    
    
    //CustomerController.java
    
    package info.iloveec.springtags;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.validation.BindException;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.Errors;
    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.bind.support.SessionStatus;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.SimpleFormController;
    
    @Controller
    @RequestMapping("/customer.html")
    public class CustomerController {
    	
    	private CustomerValidator customerValidator;
    	
    	@Autowired
    	public CustomerController(CustomerValidator customerValidator) {
    		this.customerValidator = customerValidator;
    	}
    
    	@RequestMapping(method = RequestMethod.GET)
    	public String initForm(ModelMap model)
    	{
    		Customer customer = new Customer();
    		customer.setFavFramework(new String[]{"Spring MVC"});
    		customer.setSex("M");
    		customer.setJavaSkills("Hibernate");
    		customer.setSecretValue("I'm hidden value");
    		model.addAttribute("customer", customer);
    		return "CustomerForm";
    	}
    	
    	@RequestMapping(method=RequestMethod.POST)
    	public String processSubmit(@ModelAttribute("customer") Customer customer, BindingResult result, SessionStatus status)
       {
    		customerValidator.validate(customer, result);
    		if(result.hasErrors()) {
    			return "CustomerForm";
    		}else {
    			status.setComplete();
    			return "CustomerSuccess";
    		}
    	}
    
    
    				@ModelAttribute("webFrameworkList")
    				public List<String> populateWebFrameworkList(){
    				List<String> webFrameworkList = new ArrayList<String>();
    				webFrameworkList.add("Spring MVC");
    				webFrameworkList.add("Struts 1");
    				webFrameworkList.add("Struts 2");
    				webFrameworkList.add("JSF");
    				webFrameworkList.add("Apache Wicket");
    				
    				return webFrameworkList;
    				}
    				
    				//Data referencing for number radiobuttons
    				@ModelAttribute("numberList")
    				public List<String> populate(){
    				List<String> numberList = new ArrayList<String>();
    				numberList.add("Number 1");
    				numberList.add("Number 2");
    				numberList.add("Number 3");
    				numberList.add("Number 4");
    				numberList.add("Number 5");
    				return numberList;
    				}
    				
    				@ModelAttribute("javaSkillsList")
    				public Map<String,String> populateJavaSkillList() {
    			 
    					//Data referencing for java skills list box
    					Map<String,String> javaSkill = new LinkedHashMap<String,String>();
    					javaSkill.put("Hibernate", "Hibernate");
    					javaSkill.put("Spring", "Spring");
    					javaSkill.put("Apache Wicket", "Apache Wicket");
    					javaSkill.put("Struts", "Struts");
    			 
    					return javaSkill;
    				}
    				
    				@ModelAttribute("countryList")
    				public Map<String,String> populateCountryList() {
    			 
    					//Data referencing for java skills list box
    					Map<String,String> country = new LinkedHashMap<String,String>();
    					country.put("US", "United Stated");
    					country.put("CHINA", "China");
    					country.put("SG", "Singapore");
    					country.put("MY", "Malaysia");
    			 
    					return country;
    				}
    	
    	
    	
    }
    //CustomerSuccess.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'hello.jsp' starting page</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
    
      </head>
      
      <body>
        <h2>Spring's form tags example</h2>
     
    	<table>
    		<tr>
    			<td>UserName :</td>
    			<td>${customer.userName}</td>
    		</tr>
    		<tr>
    			<td>Address :</td>
    			<td>${customer.address}</td>
    		</tr>
    		<tr>
    			<td>Password :</td>
    			<td>${customer.password}</td>
    		</tr>
    		<tr>
    			<td>Confirm Password :</td>
    			<td>${customer.confirmPassword}</td>
    		</tr>
    		<tr>
    			<td>Receive Newsletter :</td>
    			<td>${customer.receiveNewsletter}</td>
    		</tr>
    		<tr>
    			<td>Favourite Web Frameworks :</td>
    			<td><c:forEach items="${customer.favFramework}" var="current">
    				   [<c:out value="${current}" />]
    				</c:forEach>
    			</td>
    		</tr>
    		<tr>
    			<td>Sex :</td>
    			<td>${customer.sex}</td>
    		</tr>
    		<tr>
    			<td>Favourite Number :</td>
    			<td>${customer.favNumber}</td>
    		</tr>
    		<tr>
    		<td>Java Skills :</td>
    		<td>${customer.javaSkills}</td>
    		</tr>
    		<tr>
    			<td>Hidden Value :</td>
    			<td>${customer.secretValue}</td>
    		</tr>
    		<tr>
    			<td>Hidden Value :</td>
    			<td>${customer.secretValue}</td>
    		</tr>
    	</table>
      </body>
    </html>
    
    //CustomerForm.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
    	<style type="text/css">
    		.error {
    			color: #ff0000;
    		}
    		 
    		.errorblock {
    			color: #000;
    			background-color: #ffEEEE;
    			border: 3px solid #ff0000;
    			padding: 8px;
    			margin: 16px;
    		}
    	</style>
        <base href="<%=basePath%>">
        
        <title>My JSP 'hello.jsp' starting page</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
    
      </head>
      
      <body>
    <h2>Spring's form tags example</h2>
     
    	<form:form method="POST" commandName="customerForm" modelAttribute="customer">
    		<form:errors path="*" cssClass="errorblock" element="div" />
    		<table>
    			<tr>
    				<td>UserName :</td>
    				<td><form:input path="userName" />
    				</td>
    				<td><form:errors path="userName" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Address :</td>
    				<td><form:textarea path="address" />
    				</td>
    				<td><form:errors path="address" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Password :</td>
    				<td><form:password path="password" />
    				</td>
    				<td><form:errors path="password" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Confirm Password :</td>
    				<td><form:password path="confirmPassword" />
    				</td>
    				<td><form:errors path="confirmPassword" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Subscribe to newsletter? :</td>
    				<td><form:checkbox path="receiveNewsletter" />
    				</td>
    				<td><form:errors path="receiveNewsletter" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Favourite Web Frameworks :</td>
    				<td><form:checkboxes items="${webFrameworkList}"
    					path="favFramework" /></td>
    				<td><form:errors path="favFramework" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Sex :</td>
    				<td><form:radiobutton path="sex" value="M" />Male 
                                           <form:radiobutton path="sex" value="F" />Female</td>
    				<td><form:errors path="sex" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Choose a number :</td>
    				<td><form:radiobuttons path="favNumber" items="${numberList}" />
    				</td>
    				<td><form:errors path="favNumber" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Country :</td>
    				<td><form:select path="country">
    					   <form:option value="NONE" label="--- Select ---" />
    					   <form:options items="${countryList}" />
    					</form:select></td>
    				<td><form:errors path="country" cssClass="error" />
    				</td>
    			</tr>
    			<tr>
    				<td>Java Skills :</td>
    				<td><form:select path="javaSkills" items="${javaSkillsList}"
    					multiple="true" /></td>
    				<td><form:errors path="javaSkills" cssClass="error" />
    				</td>
    			</tr>
    			<form:hidden path="secretValue" value="hidden value"/>
    			<tr>
    				<td colspan="3"><input type="submit" /></td>
    			</tr>
    		</table>
    	</form:form>
      </body>
    </html>
    //mvc-dispatcher-servlet.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="
            http://www.springframework.org/schema/beans     
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
     
    	<context:component-scan base-package="info.iloveec.*" />
    	
    	<bean class="info.iloveec.springtags.CustomerValidator" />
    
        
        <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    	    <property name="basename" value="info/iloveec/springtags/customer" />
        </bean>
     
    	<bean
    		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="prefix">
    			<value>/WEB-INF/pages/</value>
    		</property>
    		<property name="suffix">
    			<value>.jsp</value>
    		</property>
    	</bean>
     
    </beans>
    //web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0" 
    	xmlns="http://java.sun.com/xml/ns/javaee" 
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
     
    	<display-name>Spring MVC Application</display-name>
     
    	<servlet>
    		<servlet-name>mvc-dispatcher</servlet-name>
    		<servlet-class>
                           org.springframework.web.servlet.DispatcherServlet
                    </servlet-class>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
     
    	<servlet-mapping>
    		<servlet-name>mvc-dispatcher</servlet-name>
    		<url-pattern>/</url-pattern>
    	</servlet-mapping>
     
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    	</context-param>
     
    	<listener>
    		<listener-class>
                          org.springframework.web.context.ContextLoaderListener
            </listener-class>
    	</listener>
     
    </web-app>

      

  • 相关阅读:
    并查集
    树状数组及二维树状数组
    maven工程编译成jar包
    The Salt Master has rejected this minion's public key!
    salt-minion dead but pid file exists 正确解决方法
    mysql 查找表的auto_increment和修改
    fastjson --JSONObject 和JSONArray 转换
    git 获取当前版本的commitid
    fastjson 使用笔记
    spring IOC 注解@Resource
  • 原文地址:https://www.cnblogs.com/JavaTechLover/p/2557970.html
Copyright © 2020-2023  润新知