Java servlet [dispatcher] 的 Servlet.service() 在路径为 [/***] 的上下文中抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54062210/
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
Servlet.service() for servlet [dispatcher] in context with path [/***] threw exception
提问by Nishi Bansal
I am getting below error while creating spring maven rest webservice. When trying to call DAO class with bean name defined in application_config.xml, getting NullPointerException
我在创建 spring maven rest webservice 时遇到错误。尝试使用 application_config.xml 中定义的 bean 名称调用 DAO 类时,获取 NullPointerException
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/riceAppService] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.ganeshTrading.riceAppService.controller.UserController.getAllUsers(UserController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Here, is my code
这是我的代码
UserController.java
用户控制器.java
@RestController
public class UserController {
private JdbcUserDAO jdbcUserDAO;
public JdbcUserDAO getJdbcUserDAO() {
return jdbcUserDAO;
}
public void setJdbcUserDAO(JdbcUserDAO jdbcUserDAO) {
this.jdbcUserDAO = jdbcUserDAO;
}
@RequestMapping("/")
@ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
@RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
UserDAO.java
UserDAO.java
public interface UserDAO {
public List<User> getAllUsers();
}
JdbcUserDAO.java
JdbcUserDAO.java
public class JdbcUserDAO implements UserDAO {
DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public List<User> getAllUsers() {
String sql = "select * from customer";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
System.out.println("getJdbcTemplate() "+jdbcTemplate);
List<User> userList = jdbcTemplate.query(sql, new UserMapper());
return userList;
}
}
servlet-context.xml
servlet-context.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:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<import resource="classpath:application_config.xml" />
<context:component-scan base-package="com.ganeshTrading.riceAppService" />
</beans>
application_config.xml
应用程序配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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-4.3.xsd">
<bean id="jdbcUserDAO" class="com.ganeshTrading.riceAppService.dao.impl.JdbcUserDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ganeshricetrading"></property>
<property name="username" value="root"></property>
<property name="password" value="sql"></property>
</bean>
</beans>
web.xml
网页.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns="xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="xmlns.jcp.org/xml/ns/javaee xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
ApplicationConfiguration.java
应用程序配置文件
@ComponentScan(basePackages = {"com.ganeshTrading.riceAppService"})
@Configuration
@EnableWebMvc
public class ApplicationConfiguration {
}
Please advise what is wrong in my code. Thanks in advance.
请告知我的代码有什么问题。提前致谢。
采纳答案by Justin Albano
Although you have defined the jdbcUserDAO
bean, you have not wired it into the UserController
class. This causes a NullPointerException
because the jdbcUserDAO
field is null
, which results in the exception when jdbcUserDAO.getAllUsers()
is called. To solve this, annotate the jdbcUserDAO
setter in the UserController
with @Autowired
, as in:
尽管您已经定义了jdbcUserDAO
bean,但您还没有将它连接到UserController
类中。这会导致 aNullPointerException
因为该jdbcUserDAO
字段是null
,这会导致jdbcUserDAO.getAllUsers()
调用时出现异常。要解决此问题,请jdbcUserDAO
在UserController
with 中对setter 进行注释@Autowired
,如下所示:
@RestController
public class UserController {
private JdbcUserDAO jdbcUserDAO;
public JdbcUserDAO getJdbcUserDAO() {
return jdbcUserDAO;
}
@Autowired
public void setJdbcUserDAO(JdbcUserDAO jdbcUserDAO) {
this.jdbcUserDAO = jdbcUserDAO;
}
@RequestMapping("/")
@ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
@RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
The @Autowired
annotation tells Spring that a bean that matches the interface of the parameter for the setter (in this case, JdbcUserDAO
) should be injected into the setter, which results in the jdbcUserDAO
field being set to your JdbcUserDAO
bean defined in application_config.xml
.
该@Autowired
注解告诉 SpringJdbcUserDAO
应将与 setter 的参数接口(在本例中为)匹配的 bean注入 setter,这会导致该jdbcUserDAO
字段被设置为 中JdbcUserDAO
定义的bean application_config.xml
。
You could also simplify your UserController
and annotate the field (removing the getter and setter):
您还可以简化您UserController
的字段并对其进行注释(删除 getter 和 setter):
@RestController
public class UserController {
@Autowired
private JdbcUserDAO jdbcUserDAO;
@RequestMapping("/")
@ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
@RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
For more information, see Guide to Spring @Autowired.
有关更多信息,请参阅Spring @Autowired 指南。
It also looks like your application_config.xml
is not being included in Spring's application context. To include this XML file, change your ApplicationConfiguration
class to resemble the following:
看起来您application_config.xml
还没有包含在 Spring 的应用程序上下文中。要包含此 XML 文件,请将您的ApplicationConfiguration
类更改为如下所示:
@ComponentScan(basePackages = {"com.ganeshTrading.riceAppService"})
@Configuration
@EnableWebMvc
@ImportResource("classpath:/path/to/application_config.xml")
public class ApplicationConfiguration {
}
Note that classpath:/path/to/application_config.xml
is an example and the actual location of your application_config.xml
file should be used instead.
请注意,这classpath:/path/to/application_config.xml
是一个示例,application_config.xml
应改为使用文件的实际位置。