0

我正在尝试使用spring MVC和hibernate将表单数据持久化到数据库但是当调用hibernate session.getSession.save(s)的save方法时它返回NullPointerException。

这是我的 index.jsp 的代码

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Welcome to Spring Web MVC project</title>
</head>

<body>
    <form action="insert.htm">
        <label>  Name:</label><input type="text" name="name"><br>
        <label> Id:</label><input type="text" name="id"><br>
        <input type="submit" value="Enter">
    </form>
</body>
</html>

这是 web.xml 文件

 <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

而我的 dispatcher-servlet.xml 是

<bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"  id="sessionFactory">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
    <list>
        <value>com.model.Student</value>
    </list>
</property>
<property name="hibernateProperties">  
<props>
        <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource"
    p:driverClassName="oracle.jdbc.driver.OracleDriver"
    p:url="jdbc:oracle:thin:@localhost:1521:Xe"
    p:username="hibernate"
    p:password="hibernate"></bean>
   <bean id="hibernatetransactionManager"             class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>                
   </bean>

这是我的模型班学生

package com.model;

import javax.persistence.Id;
import javax.persistence.Entity;


 @Entity
  public class Student {
  @Id    
  private int id;
  private String name;

  public int getId() {
    return id;
 }

 public void setId(int id) {
     this.id = id;
 } 

 public String getName() {
     return name;
 }

 public void setName(String name) {
     this.name = name;
 }

  }

我的控制器是

@Controller
public class MyController {

@Autowired
    private Dao d;
@RequestMapping(value="/insert.htm",method = RequestMethod.GET)
public ModelAndView insert(HttpServletRequest req,Student s)
{
   String name=req.getParameter("name");
    int id=Integer.parseInt(req.getParameter("id"));
    s.setId(id);
    s.setName(name);
   System.out.println(s.getName());
    d.save(s);
    return new ModelAndView("display","Student",s);

}

这是我的道

 @Repository
 public class Dao {
 @Autowired
 private SessionFactory sessionFactory;

 public int save(Student s)
   {

     /*Session s1=sf.openSession();
     s1.beginTransaction();
     int i=(Integer)s1.save(s);
     s1.getTransaction().commit();
     return i;*/
     int i=(Integer)sessionFactory.getCurrentSession().save(s);
     return i;
     }
   }

我在 MyController 中的 d.save(s) 处遇到的异常

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/Spring5]          
threw exception [Request processing failed; nested exception
at com.controller.MyController.insert(MyController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at s   un.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at  org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(Ha ndlerMethodInvoker.java:176)
    at  org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    at  org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
     at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.jav a:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

我是spring mvc的初学者,请帮帮我。我在调用插入时遇到异常我也使用过@Autowired ...

4

3 回答 3

2

除非您发布的堆栈跟踪不准确,否则空引用是您Dao在控制器中的。你确定它的接线正确吗?

于 2013-06-25T13:07:21.913 回答
1

NullPointerException的原因是:您既没有使用@ModelAttribute进行 bean 绑定,也没有创建

Student s = new Student();

如果您不想要@ModelAttribute。您在控制器代码中的参数Student s之前缺少@ModelA rrtibute 。如果使用@ModelAttribute注解进行bean 绑定,则不需要从request 中获取请求参数并填充bean。因此删除以下内容:

String name=req.getParameter("name");
int id=Integer.parseInt(req.getParameter("id"));
s.setId(id); /* Here you are setting a value with a reference wcich points to null */
s.setName(name); /* Here you are setting a value with a reference wcich points to null */

Annotation @ModelAttribute自动将请求参数绑定到应用它的 bean 的匹配属性。

@Controller
public class MyController {

    @Autowired(required = true) 
    private Dao d;
    @RequestMapping(value="/insert.htm",method = RequestMethod.GET)
    public ModelAndView insert(HttpServletRequest req,@ModelAttribute Student s)
    {
        System.out.println(s.getName());
        d.save(s);
        return new ModelAndView("display","Student",s);

    }

编辑:您已经用@Repository注释了 Dao 类。它将创建一个名为dao的单例对象。如果您想要除它之外的任何其他名称,请使用

@Repository(value ="d") 
 public class Dao{

} 

现在您可以像以前一样自动装配实例d

@Autowired (required = true) 
private Dao d;

在您的情况下,自动装配的 Dao 实例为空,因为 spring 无法自动装配名为d的 bean 。因此,您在 null 引用上调用 save 方法。

于 2013-06-25T12:44:49.593 回答
0

@Rahul,您在 Get 方法中绑定数据,但实际上,当您处理表单时,您不应该在 GET 方法中这样做,您应该始终使用 POST 方法,我认为它可能会对您有所帮助:-)

@RequestMapping(value="/insert.htm",method = RequestMethod.POST)
    public ModelAndView insert(HttpServletRequest req,@ModelAttribute Student s)
    {
        System.out.println(s.getName());
        d.save(s);
        return new ModelAndView("display","Student",s);

    }
于 2015-06-18T16:26:41.110 回答