空指针异常

空指针异常

package com.zqq.web.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zqq.domain.Category;
import com.zqq.service.CategoryService;
import com.zqq.service.impl.CategoryServicelmpl;


@WebServlet("/CategoryServlet")
public class CategoryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//请求路径:loaclhost:8080/shop/CategoryServlet?method=findAll
		String methodName = request.getParameter("method");
		if("findAll".equals(methodName)) {
			//查询所有分类
			findAll(request,response);
		}
		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
//后台分类管理查询所有分类的方法
	private void findAll(HttpServletRequest request, HttpServletResponse response) {
		//接收参数
		//封装数据
		//调用业务层处理数据
		System.out.println("categoryServlet的方法执行了");
		CategoryService categoryService = new CategoryServicelmpl();
		List<Category> list = categoryService.findAll();
		for(Category category:list) {
			System.out.println(category);
		}
		
	}

}



package com.zqq.service.impl;


import java.util.List;


import com.zqq.dao.CategoryDao;

import com.zqq.dao.impl.CategoryDaolmpl;

import com.zqq.domain.Category;

import com.zqq.service.CategoryService;


public class CategoryServicelmpl implements CategoryService {


@Override

public List<Category> findAll() {

//调用CategoryDao的方法

System.out.println("categoryService的方法执行了");

CategoryDao categoryDao = new CategoryDaolmpl();

return categoryDao.findAll();

}


}






package com.zqq.dao.impl;


import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.ArrayList;

import java.util.List;


import com.zqq.dao.CategoryDao;

import com.zqq.domain.Category;

import com.zqq.utils.JDBCUtils;


public class CategoryDaolmpl implements CategoryDao {


@Override

public List<Category> findAll() {

System.out.println("categoryDao的方法执行了");

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

List<Category> list = null;

try {

//获得连接

conn = JDBCUtils.getConnection();

//编写SQL

String sql = "select * from category";

//预编译SQL

pstmt = conn.prepareStatement(sql);

//设置参数

//执行SQL

rs=pstmt.executeQuery();

//处理结果

list = new ArrayList<Category>();

while(rs.next()) {

Category category = new Category();

category.setCid(rs.getInt("cid"));

category.setCname(rs.getString("cname"));

category.setCdesc(rs.getString("cdesc"));

list.add(category);

}

}catch(Exception e){

e.printStackTrace();

}finally {

//释放资源

JDBCUtils.release(rs, pstmt, conn);

}

return null;

}


}



categoryServlet的方法执行了

categoryService的方法执行了

categoryDao的方法执行了

十二月 16, 2019 9:08:52 下午 com.mchange.v2.log.MLog <clinit>

信息: MLog clients using java 1.4+ standard logging.

十二月 16, 2019 9:08:52 下午 com.mchange.v2.c3p0.C3P0Registry banner

信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]

十二月 16, 2019 9:08:53 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager

信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge0z0a74439bf1wz849m|66d503a1, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.cj.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge0z0a74439bf1wz849m|66d503a1, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql:///shop?serverTimezone=Hongkong&useSSL=false&useUnicode=true&characterEncoding=utf-8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]

十二月 16, 2019 9:08:54 下午 org.apache.catalina.core.StandardWrapperValve invoke

严重: 在路径为[/shop]的上下文中,servlet[com.zqq.web.action.CategoryServlet]的Servlet.service()引发异常

java.lang.NullPointerException

at com.zqq.web.action.CategoryServlet.findAll(CategoryServlet.java:46)

at com.zqq.web.action.CategoryServlet.doGet(CategoryServlet.java:27)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)

at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)

at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)

at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:609)

at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)

at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)

at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1506)

at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)

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)


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

3回答
好帮手慕小班 2020-09-21 17:11:08

同学你好,在课程案例中,list集合有进行对应的实例化,比如:

http://img1.sycdn.imooc.com//climg/5f686dfe09ef936b06280733.jpg

同学说的没有new进行实例化,是哪里没有实例化,还麻烦同学具体描述一下。

继续加油  祝:学习愉快~

好帮手慕阿满 2019-12-17 16:26:41

同学你好,在CategoryDaolmpl的findAll()方法中,最后应该返回list,而不是null,如:

http://img1.sycdn.imooc.com//climg/5df891140971d79205790331.jpg

建议同学修改为list再试试。

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

  • 老师 为什么List等于null就会包空指针异常,但是new 一个就不会了呢
    2020-09-20 14:23:08
  • 同学你好,NullPointerException,空指针异常使用null调用方法或属性就会出现该异常。如果返回值为null,当调用这个(为null)的返回值时,就会报出空指针异常的错误。 继续加油 祝:学习愉快~
    2020-09-20 16:15:39
  • 同学你好,补充一下,当使用new关键字,创建一个对象之后,这个对象就不为空,对应就可以调用对应的方法,而不会报出空指针异常。 继续加油 祝:学习愉快~
    2020-09-20 16:19:45
好帮手慕阿满 2019-12-17 10:24:37

同学你好,报错提示是空指针异常,报错的地方是CategoryServlet的findAll()方法的第46行,如:

http://img1.sycdn.imooc.com//climg/5df838da091d005807590194.jpg

这里应该是categoryService.findAll()查询为null,所以报空指针异常。如:

http://img1.sycdn.imooc.com//climg/5df839ab093aaefe07880369.jpg

问一下同学数据库中是没有分类信息吗?建议同学添加两条分类信息再运行试试。

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

  • 提问者 董先生啊 #1
    有分类信息的
    2019-12-17 16:02:35
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师