一、问题描述:
action获取的前台参数调用函数传到service层使用会提示NullpointException错误。
代码如下所示:出错代码为A、B行。
//Action
public class OrderAction extends ActionSupport implements ModelDriven<Order>{
private Integer pageNumber;
private String id;
....(省略set/get)
public String refresh() throws Exception{
pass(pageNumber, id);
}
}
//Service
public Integer pass(Integer pageNumber, String id){
Integer index = (pageNumber-1)*5; //A
if(id.equals("test")){ //B
System.out.println("done");
}
}
二、error log:
java.lang.NullPointerException com.xnyc.service.impl.OrderServiceImpl.getPageBeanOfAll(OrderServiceImpl.java:118) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)………………
三、出错原因分析及解决方法
A行:之所以出错NullPointException,是因为Integer在运算和赋值时,会自动拆箱,如果该Integer为null,调用自动拆箱的intValue()函数时就会报NullPointException。
解决方法:将Action和Service中的pageNumber的类型变为int就不会报错了。
B行:id也会可能为null,故调用equals()方法时也会报错。
解决方法:加个if进行是否为null的判断。
三、本质原因
本质原因,应该是与Spring机制有关,之后有时间研究一下。