在 spring mvc 中获取 java.lang.NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17297379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting java.lang.NullPointerException in spring mvc
提问by Rahul Bussa
I am trying to persist form data to database using spring MVC and hibernate but when calling the save method of hibernate session.getSession.save(s) it is returning NullPointerException.
我正在尝试使用 spring MVC 和 hibernate 将表单数据持久化到数据库,但是当调用 hibernate session.getSession.save(s) 的 save 方法时,它返回 NullPointerException。
Here is the code of my index.jsp
这是我的 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>
And here is the web.xml file
这是 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>
And my dispatcher-servlet.xml is
我的 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>
and here is my model class Student
这是我的模范班学生
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;
}
}
And my controller is
我的控制器是
@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);
}
Here is my 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;
}
}
The Exception i am getting at d.save(s) in MyController
我在 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)
I am begginer to spring mvc please help me out . i am getting Exception while calling insert i have used @Autowired also...
我是 spring mvc 的初学者,请帮帮我。我在调用插入时遇到异常我也使用了@Autowired...
回答by Tom G
Unless the stacktrace you have posted is not accurate, then the null reference is your Dao
in the controller. Are you sure it is being wired in correctly?
除非您发布的堆栈跟踪不准确,否则空引用是您Dao
在控制器中的。你确定它接线正确吗?
回答by Vaibhav Raj
The reason for NullPointerExceptionis: neither you are using @ModelAttributefor bean binding, nor you have created
NullPointerException的原因是:您既没有使用@ModelAttribute进行 bean 绑定,也没有创建
Student s = new Student();
in case if you don't want @ModelAttribute. You You are missing @ModelA rrtibutebefore the parameter Student sin the your controller code. If you use @ModelAttributeannotation for bean binding, you don't need to get the request parameters from request and populate the bean. Therefore remove the following:
如果你不想要@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 */
The Annotation @ModelAttributeautomatically binds request parameters to the matching properties of the bean on which it is applied.
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);
}
Edit: you have annotated the class Dao with @Repository. It will create a singleton object with name dao. If you want any other name except it, then use
编辑:您已经使用@Repository注释了 Dao 类。它将创建一个名为dao的单例对象。如果您想要除它之外的任何其他名称,请使用
@Repository(value ="d")
public class Dao{
}
Now you can autowire the instance das you were doing
现在您可以像之前一样自动装配实例d
@Autowired (required = true)
private Dao d;
In your case the autowired Dao instance is null because spring is unable to autowire a bean named d. Therefore, you are invoking the save method on null reference.
在您的情况下,自动装配的 Dao 实例为空,因为 spring 无法自动装配名为d的 bean 。因此,您正在对空引用调用 save 方法。
回答by Darshan
@Rahul, you are binding the data in Get Method but actually you should not do that in the GET method when you are dealing with the form you should always Use POST method i think it might help you :-)
@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);
}