我试图使用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);
}
这是我的Dao
@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)
我打电话给春天的mvc请帮帮我。
我在调用插入时遇到异常,我也使用了@Autowired ......
答案 0 :(得分:2)
除非您发布的堆栈跟踪不准确,否则空引用是控制器中的Dao
。你确定它正确连线吗?
答案 1 :(得分:1)
NullPointerException 的原因是:既没有使用 @ModelAttribute 进行bean绑定,也没有创建
Student s = new Student();
如果您不想要 @ModelAttribute 。 您 您在控制器代码中的参数 Student s 之前缺少 @ModelA rrtibute 。如果对bean绑定使用 @ModelAttribute 注释,则不需要从请求中获取请求参数并填充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实例为null,因为spring无法自动装配名为 d 的bean。因此,您在null引用上调用save方法。
答案 2 :(得分:0)
@Rahul,你在Get Method中绑定数据,但实际上你不应该在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);
}