spring HTTP 状态 500 - 请求处理失败;嵌套异常是 java.lang.NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21561845/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:32:31  来源:igfitidea点击:

HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException

springjsp

提问by Sridhat Turupati

I am having difficulties while trying to launch my application, I looked for my mistake for a couple of days but i am stuck somewhere in the code and asking for your assistance... Thanks

我在尝试启动我的应用程序时遇到了困难,我花了几天时间寻找我的错误,但我被困在代码的某个地方并寻求您的帮助......谢谢

Add Customer COntrller :

添加客户控制器:

 package com.witlab.controller;

import com.witlab.services.CustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.witlab.services.CustomerService;
import com.witlab.customer.Customer;
import org.springframework.beans.factory.annotation.Autowired;

@Controller
public class AddCustomerController {

 @Autowired
CustomerService customerservice;

@RequestMapping(value="/AddCustomer", method = RequestMethod.GET)
public String addcustomer(@ModelAttribute Customer customer) {
    return "AddCustomer";
    }

    @RequestMapping(value ="InsertCustomer", method = RequestMethod.POST)
    public String insertCustomer(@ModelAttribute ("customer") Customer customer, ModelMap model)
    {                 System.out.println(customer.getAddress());
        if (customer!=null)
        {
            System.out.println(customer.getName());
            System.out.println(customer.getCity());
            System.out.println(customer.getPhone());
          System.out.println(model.addAttribute("Name", customer.getName()));


       model.addAttribute("Name", customer.getName());
        model.addAttribute("Address", customer.getAddress());
        model.addAttribute("city", customer.getCity());
        model.addAttribute("phone", customer.getPhone());
        model.addAttribute("mobile", customer.getMobile());
            customerservice.createCustomer(customer);
        }
        else
        {
            System.out.print("Error");
        }
        return "AddCustomer";
    }



}

dispatcher-servlet :

调度程序小服务程序:

<context:annotation-config /> 

<context:component-scan base-package="com.witlab.controller" />


<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />



      <bean id="CustomerDAO" class="com.witlab.customer.CustomerJDBCTemplate" />  
      <bean id="customerService" class="com.witlab.services.CustomerServiceImpl" />  
<bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="/WEB-INF/jdbc.properties" /> 

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
</beans>

Customer Service :

客户服务 :

package com.witlab.services;

import com.witlab.customer.Customer;
import java.util.List;

public interface CustomerService {
public void createCustomer(Customer customer);
public Customer getCustomer(double Id);
public List<Customer> getCustomers();
public void deleteCustomer(double Id);
public void updateCustomer(double Id, String Name, String Address, String city, String phone, String mobile);

}

Customer JDBCTemplate :

客户 JDBCTemplate :

package com.witlab.customer;

import java.util.List; 
import javax.sql.DataSource; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.instrument.classloading.jboss.JBossLoadTimeWeaver;
import org.springframework.jdbc.core.JdbcTemplate;

public class CustomerJDBCTemplate implements CustomerDAO{

@Autowired
DataSource dataSource;


private JdbcTemplate jdbcTemplateobj;

public void setDataSource(DataSource dataSource)
{
    this.dataSource = dataSource; 
    this.jdbcTemplateobj = new JdbcTemplate(dataSource);
} 


 public void createCustomer(Customer customer) {
     System.out.print("In Template"+customer.getName());
    String SQL="insert into customer (Name, Address,city, phone, mobile) values (?, ?, ?, ?, ?)";
    jdbcTemplateobj.update(SQL, new Object[]{customer.getName(),     customer.getAddress(),customer.getCity(), customer.getPhone(), customer.getMobile()});
    return;        
}

@Override
public Customer getCustomer(double Id) {
    String SQL="select * from customer where Id=?";
    Customer customer=jdbcTemplateobj.queryForObject(SQL, new Object[]{Id},new CustomerMapper());
    return customer;
}


public List<Customer> getCustomers() {
    String SQL="select * from customer";
    List <Customer> customers=jdbcTemplateobj.query(SQL, new CustomerMapper());
    return  customers;
}

@Override
public void deleteCustomer(double Id) {
    String SQL="delete from customer where Id=?";
    jdbcTemplateobj.update(SQL, Id);
    return;
}


@Override
public void updateCustomer(double Id, String Name, String Address, String city, String phone, String mobile) {
    String SQL = "update customer set String = ?, String = ?, String = ?, String = ?, mobile = ? where Id = ?";
    jdbcTemplateobj.update(SQL, Name, Address, city, phone, mobile, Id);
    return;
}   

}

Error :

错误 :

Feb 05, 2014 12:49:55 AM org.apache.catalina.core.ApplicationContext log
INFO: Destroying Spring FrameworkServlet 'dispatcher'
Feb 05, 2014 12:49:55 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Feb 05, 2014 12:50:36 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Feb 05, 2014 12:50:36 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Feb 05, 2014 12:50:37 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Feb 05, 2014 12:50:55 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/WhizzyBilling] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at com.witlab.customer.CustomerJDBCTemplate.createCustomer(CustomerJDBCTemplate.java:37)
    at com.witlab.services.CustomerServiceImpl.createCustomer(CustomerServiceImpl.java:26)
    at com.witlab.controller.AddCustomerController.insertCustomer(AddCustomerController.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    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.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    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)

回答by Sotirios Delimanolis

You are defining your CustomerJDBCTemplatebean like so

CustomerJDBCTemplate像这样定义你的bean

<bean id="CustomerDAO" class="com.witlab.customer.CustomerJDBCTemplate" />  

In this case, there is no reason for the setDataSourcemethod to be called. As such, the jdbcTemplateObjfield will remain null.

在这种情况下,没有理由setDataSource调用该方法。因此,该jdbcTemplateObj字段将保留null

There are a few ways to fix this.

有几种方法可以解决这个问题。

Option 1: remove the @Autowiredannotation from the dataSourcefield and add a <property>element to the <bean>definition like so

选项 1:@AutowireddataSource字段中删除注释并像这样<property><bean>定义中添加一个元素

<bean id="CustomerDAO" class="com.witlab.customer.CustomerJDBCTemplate" >
    <property name="dataSource" ref="dataSource" />
</bean>  

Spring will invoke your setDataSource(..)method, passing in the dataSourcebean you've defined. This will initialize the jdbcTemplateobjfield.

Spring 将调用您的setDataSource(..)方法,传入dataSource您定义的bean。这将初始化该jdbcTemplateobj字段。

Option 2: Instead of the setDataSource()method, add a @PostConstructmethod

选项2:代替setDataSource()方法,添加@PostConstruct方法

@PostConstruct
public void init() {
    this.jdbcTemplateobj = new JdbcTemplate(dataSource);
}

When Spring is done initializing your bean and injecting any fields, it will invoke this method, initializing the jdbcTemplateobjfield.

当 Spring 完成初始化您的 bean 并注入任何字段时,它将调用此方法,初始化该jdbcTemplateobj字段。

Option 3: Remove the @Autowiredannotation from the field and add it to the setDataSource(..)method.

选项 3:@Autowired从字段中删除注释并将其添加到setDataSource(..)方法中。

回答by developerwjk

Anywhere where a variable could be nullbut shouldn't be, check it before using it. That means, especially, check it before using the dot operator to access methods or member variables. You are already checking this for the variable customerbut not for modelor customerservice.

在变量可能存在null但不应该存在的任何地方,在使用之前检查它。这意味着,特别是,在使用点运算符访问方法或成员变量之前检查它。您已经在检查这个变量customer而不是modelor customerservice