1. 程式人生 > >SSM框架—java.lang.NullPointerException,空指標異常處理

SSM框架—java.lang.NullPointerException,空指標異常處理

Servlet.service() for servlet [GoodShop] in context with path [/goshop] threw exception [Request processing failed;
nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException

在測試SSM專案時,一直報空指標異常,明明配置檔案與程式碼都沒有錯,為什麼會這樣呢?

五月 30, 2018 1:17:53 下午 org.apache.catalina
.core.StandardWrapperValve invoke 嚴重: Servlet.service() for servlet [GoodShop] in context with path [/goshop] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at com.xh.goshop.controller.GetRoleController
.handleRequest(GetRoleController.java:35) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework
.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) 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:94) 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:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)

第一次空指標異常出現在Service層,沒有在物件上加上註解@Autowired:

@Service("roleService")
public class RoleService implements IRoleService {

    @Autowired //當時沒有加這個註解,自動裝配Bean
    private RoleMapper roleMapper;

    @Override
    public Role getRoleById(Long id) {
        // TODO Auto-generated method stub
        return roleMapper.getRole(id);
    }

}

第二次空指標異常出現在Controller層,原因是我把它改成測試類了,以至於在model方法中沒有初始化Spring Ioc容器,因此獲取不到bean例項,報空指標異常。

//將Spring IoC容器執行在Junit上,減少開銷
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring-mybatis.xml")
@Controller//標記這個類是通過註解來對映URL
public class GetRoleController {

    //@Resource 
    //private RoleService roleService = null;

    @RequestMapping("/hello")//前端哪個請求對映到這個方法
    public ModelAndView model(HttpServletRequest request, HttpServletResponse response) throws Exception {

//      ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml"); 
//      IRoleService roleService = ctx.getBean("roleService",RoleService.class);
        ModelAndView mv = new ModelAndView();
        Long id = 1L;
        System.out.println("檢測roleService是否為");
        System.out.println(roleService);
        Role role = roleService.getRoleById(id);
        mv.addObject("userinfo", role.getRoleName());
        mv.setViewName("/hello.jsp");       
        return mv;
    }

//  @Test
//  public void test() {
//      System.out.println("檢測roleServices是否為空");
//      System.out.println(roleService);
//      Long id = 1L;
//      Role role = roleService.getRoleById(id);
//      System.out.println(role.getNote());
//  }

}

把上面程式碼中的Test類獨立出來,對比Spring IoC容器初始化的方式,如下:

//將Spring IoC容器執行在Junit上,減少開銷
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring-mybatis.xml")
public class GetRoleController {

    @Resource 
    private RoleService roleService = null;

    @Test
    public void test() {
        System.out.println("檢測roleServices是否為空");
        System.out.println(roleService);
        Long id = 1L;
        Role role = roleService.getRoleById(id);
        System.out.println(role.getNote());
    }

}

總結:空指標異常處理,檢視是否加上註解@Autowired或@Resource,不要把測試用的Spring IoC容器初始化方式混淆。