spring3 jsp页面使用报错,附连接数据库的spring MVC annotation 案例

在写一个使用spring3 的form标签的例子时,一直报错,错误信息为:java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute 。具体信息为:

  1. java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
  2. at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
  3. at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
  4. at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
  5. at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
  6. at org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
  7. at org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
  8. at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
  9. at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
  10. at org.apache.jsp.WEB_002dINF.jsp.register_jsp._jspx_meth_sf_005flabel_005f0(register_jsp.java:255)
  11. at org.apache.jsp.WEB_002dINF.jsp.register_jsp._jspService(register_jsp.java:140)
  12. at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
  13. at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  14. at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
  15. at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
  16. at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
  17. at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  18. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
  19. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
  20. at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
  21. at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
  22. at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
  23. at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
  24. at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
  25. at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
  26. at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
  27. at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
  28. at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
  29. at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
  30. at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
  31. at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
  32. at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  33. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
  34. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
  35. at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
  36. at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
  37. at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
  38. at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
  39. at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
  40. at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
  41. at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
  42. at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
  43. at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
  44. at java.lang.Thread.run(Thread.java:662)

在网上找了好长时间都不是原因所在,一直在想form标签中的modelAttribute是怎么跟project中相应的类联系在一起的,同事说是根据<form:input path="field"/>中的path attribute跟相应类中的field对应起来,由spring像注入一样给每个field赋值。所以一直在JSP页面查找原因,网上找的也都是改JSP页面,结果还是没有解决掉。

错误信息是“对于bean name 'xxxx' 既没有BindingResult也没有普通的目标对象可以用来作为请求属性”。突然想到在进入form表单页面之前,要有一个'xxxx'对象才可以在表单的标签中识别出来,所以在进入该JSP页面之前的Controller类里面相应的方法里面加上一个'xxxx'的对象。解决如下:

  1. return new ModelAndView("register").addObject(new User());

已经验证这样修改之后就不会报错。

例子的结构如图:

spring3 jsp页面使用<form:form modelAttribute="xxxx" action="xxxx">报错,附连接数据库的spring MVC annotation 案例

web.xml 的内容:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  5. id="WebApp_ID" version="2.5">
  6. <display-name>springMVCForm</display-name>
  7. <servlet>
  8. <servlet-name>springMVCForm</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. </servlet>
  11. <servlet-mapping>
  12. <servlet-name>springMVCForm</servlet-name>
  13. <url-pattern>*.do</url-pattern>
  14. </servlet-mapping>
  15. <context-param>
  16. <param-name>contextConfigLocation</param-name>
  17. <param-value>/WEB-INF/springMVCForm-servlet.xml</param-value>
  18. </context-param>
  19. <listener>
  20. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  21. </listener>
  22. <welcome-file-list>
  23. <welcome-file>index.jsp</welcome-file>
  24. </welcome-file-list>
  25. </web-app>

springMVCForm-servlet.xml 的内容:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7. http://www.springframework.org/schema/mvc
  8. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  11. <mvc:annotation-driven />
  12. <context:component-scan base-package="org.spring.wayne" />
  13. <bean id="config"
  14. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  15. <property name="locations">
  16. <list>
  17. <value>classpath:db-config.properties</value>
  18. </list>
  19. </property>
  20. </bean>
  21. <!-- 获取数据源 -->
  22. <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
  23. <property name="driverClassName">
  24. <value>${db.dirverClass}</value>
  25. </property>
  26. <property name="url">
  27. <value>${db.url}</value>
  28. </property>
  29. <property name="username">
  30. <value>${db.username}</value>
  31. </property>
  32. <property name="password">
  33. <value>${db.password}</value>
  34. </property>
  35. </bean>
  36. <bean name="namedParameterJdbcTemplate"
  37. class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
  38. <constructor-arg ref="dataSource" />
  39. </bean>
  40. <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  41. <constructor-arg ref="dataSource" />
  42. </bean>
  43. <bean
  44. class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
  45. <bean
  46. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
  47. <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀,在requestmapping输入的地址后自动调用该类进行视图解析 -->
  48. <bean id="viewResolver"
  49. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  50. <property name="viewClass"
  51. value="org.springframework.web.servlet.view.JstlView" />
  52. <property name="prefix" value="/WEB-INF/jsp/" /><!-- 跳转页面的前缀路径
  53. 如 /web-inf/jsp/ -->
  54. <property name="suffix" value=".jsp"></property><!-- 跳转页面后缀 如 helloWorld.jsp -->
  55. </bean>
  56. </beans>

db-config.properties的内容:

  1. db.url= jdbc:mysql://localhost:3306/springmvcdb?useUnicode=true&characterEncoding=utf8
  2. db.username=root
  3. db.password=
  4. db.dirverClass= com.mysql.jdbc.Driver

UserDao.class的内容:

  1. package org.spring.wayne.dao;
  2. import org.spring.wayne.dao.basic.BasicDao;
  3. @Repository
  4. public class UserDao extends BasicDao {
  5. public void addUser(User user) {
  6. String SQL = "INSERT INTO TBL_USER(USERNAME ,PASSWORD) VALUES('" + user.getUserName() + "' ,'"
  7. + user.getPassword() + "')";
  8. getJdbcTemplate().execute(SQL);
  9. }
  10. }

BasicDao.class的内容:

  1. package org.spring.wayne.dao.basic;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. public class BasicDao {
  4. @Autowired
  5. private JdbcTemplate jdbcTemplate;
  6. @Autowired
  7. private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
  8. public JdbcTemplate getJdbcTemplate() {
  9. return jdbcTemplate;
  10. }
  11. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  12. this.jdbcTemplate = jdbcTemplate;
  13. }
  14. public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
  15. return namedParameterJdbcTemplate;
  16. }
  17. public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
  18. this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
  19. }
  20. }

UserService.class的内容:

  1. package org.spring.wayne.service;
  2. import org.spring.wayne.web.form.User;
  3. public interface UserService {
  4. public void addUser(User user);
  5. }

UserServiceImpl.class的内容:

  1. package org.spring.wayne.service.impl;
  2. import org.spring.wayne.dao.UserDao;
  3. @Service
  4. public class UserServiceImpl implements UserService {
  5. @Autowired
  6. private UserDao userDao;
  7. @Override
  8. public void addUser(User user) {
  9. userDao.addUser(user);
  10. }
  11. }

RegController.class的内容:

  1. package org.spring.wayne.web.controller;
  2. import javax.validation.Valid;
  3. @Controller
  4. public class RegController {
  5. @Autowired
  6. private UserService userService;
  7. @RequestMapping("/register.do")
  8. public String handler(@ModelAttribute("user") @Valid User user, BindingResult result, Model model) {
  9. if (!result.hasErrors()) {
  10. model.addAttribute("userName", user.getUserName());
  11. model.addAttribute("password", user.getPassword());
  12. userService.addUser(user);
  13. return "welcome";
  14. } else
  15. return "register";
  16. }
  17. }

WelcomeController.class的内容:

  1. package org.spring.wayne.controller;
  2. import org.spring.wayne.web.form.User;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.servlet.ModelAndView;
  6. @Controller
  7. public class WelcomeController {
  8. @RequestMapping("/welcome.do")
  9. public ModelAndView handler() {
  10. return new ModelAndView("register").addObject(new User());
  11. }
  12. }

User.class的内容:

  1. package org.spring.wayne.web.form;
  2. import javax.validation.constraints.NotNull;
  3. import javax.validation.constraints.Size;
  4. import org.hibernate.validator.constraints.NotEmpty;
  5. public class User {
  6. private String errors;
  7. @NotNull
  8. @NotEmpty(message = "This cannot be null")
  9. @Size(min = 4, max = 6, message = "length is wrong")
  10. private String userName;
  11. @NotNull
  12. @NotEmpty
  13. @Size(min = 6, max = 10)
  14. private String password;
  15. public String getUserName() {
  16. return userName;
  17. }
  18. public void setUserName(String userName) {
  19. this.userName = userName;
  20. }
  21. public String getPassword() {
  22. return password;
  23. }
  24. public void setPassword(String password) {
  25. this.password = password;
  26. }
  27. public String getErrors() {
  28. return errors;
  29. }
  30. public void setErrors(String errors) {
  31. this.errors = errors;
  32. }
  33. }

index.jsp的内容:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme() + "://"
  6. + request.getServerName() + ":" + request.getServerPort()
  7. + path + "/";
  8. %>
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  10. <html>
  11. <head>
  12. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  13. <title>The Index Page</title>
  14. </head>
  15. <body>
  16. <h3>
  17. <a href="<%=basePath %>welcome.do">Click here to start</a>
  18. </h3>
  19. </body>
  20. </html>

register.jsp的内容:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>The Register Page</title>
  9. <script type="text/javascript">
  10. function doSubmit() {
  11. var sf = document.getElementById("sf");
  12. sf.submit();
  13. }
  14. </script>
  15. <style type="text/css">
  16. .errors {
  17. font-size: 12px;
  18. color: red;
  19. }
  20. </style>
  21. </head>
  22. <body>
  23. <sf:form id="sf" method="POST" modelAttribute="user"
  24. action="register.do">
  25. <sf:errors path="errors" />
  26. <fieldset>
  27. <legend>Register</legend>
  28. <table cellspacing="0">
  29. <tr>
  30. <td><sf:label path="userName">UserName:</sf:label>
  31. </td>
  32. <td><sf:input path="userName" />
  33. </td>
  34. <td><sf:errors path="userName" class="errors" />
  35. </td>
  36. </tr>
  37. <tr>
  38. <td><sf:label path="password">Password:</sf:label>
  39. </td>
  40. <td><sf:password path="password" />
  41. </td>
  42. <td><sf:errors path="password" class="errors" />
  43. </td>
  44. </tr>
  45. <tr>
  46. <td colspan="2"><input type="button" value="Submit"
  47. onClick="doSubmit()">
  48. </td>
  49. </tr>
  50. </table>
  51. </fieldset>
  52. </sf:form>
  53. </body>
  54. </html>

welcome.jsp的内容:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>The Welcome Page</title>
  8. </head>
  9. <body>
  10. Welcome, ${userName }, your password is ${password }!
  11. <br>
  12. <h3>This item has been inserted into the table !</h3>
  13. </body>
  14. </html>

用到的jar包包括spring3中的dist目录下的所有jar包,validation-api,hibernate-validator,slf4j-api,slf4j-log4j,log4j,commons-logging,tomcat-dbcp,mysql-connector-java-5.1.12-bin包。

运行截图如下:

运行project后的界面:

spring3 jsp页面使用<form:form modelAttribute="xxxx" action="xxxx">报错,附连接数据库的spring MVC annotation 案例

点击page中的链接后如图所示:

spring3 jsp页面使用<form:form modelAttribute="xxxx" action="xxxx">报错,附连接数据库的spring MVC annotation 案例

当UserName和Password为空时提示错误信息:

spring3 jsp页面使用<form:form modelAttribute="xxxx" action="xxxx">报错,附连接数据库的spring MVC annotation 案例

输入符合要求的UserName和Password跳转到下一个页面:

spring3 jsp页面使用<form:form modelAttribute="xxxx" action="xxxx">报错,附连接数据库的spring MVC annotation 案例

现在查询数据库可以看到一条记录:

spring3 jsp页面使用<form:form modelAttribute="xxxx" action="xxxx">报错,附连接数据库的spring MVC annotation 案例

该Spring MVC JUnit测试实例请点击(Spring MVC JUnit Test测试实例 附:读取WEB-INF下配置文件的方法

上一篇:Java学习笔记 jar包获取当前路径


下一篇:Linux 网络监控工具 ss