Optional int parameter ‘time’ is present but cannot be translated into a null value due to being decla
今天在操作redis的时候报了这个错:Optional int parameter ‘time’ is present but cannot be translated into a null value due to being decla
这句话意思:参数time存在,但是无法将其转为为null
查看了下原因,time这个字段是用来记录设置多久时间过期的,
我在service层设置的是Long 类型, 我在Controller 层设置的是long类型,前后设置的不一样,猜测前后需要设置一致,
于是我就将Contoller 设置为了Long类型,于是就通过了。
但是我在接受前台传送过来的参数时,使用Long接收, 在Service层使用long 同样没有报错。
之后我更改为前后都使用long,然后就报错了。
想了下springmvc在接受参数的时候,如果不存在,那么会将这个值设置为null,如果你用基本数据类型,
那么怎么给其赋值为空呢?
总结:大家以后在springmvc接受参数的时候,尽量不要使用基本数据类型,当然你一定要使用的话,可以把defaultValue加上,这样就不会报这个错误了。
注意:就算你加上required=false, 一样也是不行的。
@RequestParam注解的使用
RequestParam来映射请求参数
required表示是否必须,默认为true
defaultValue请求参数的默认值
ex:
@RequestMapping(value = “/testRequestParam”)
public String testRequestParam(@RequestParam(value=”username”)String un,@RequestParam(value = “age”,required = false,defaultValue = “0”) int age){
System.out.println(“testRequestParam,username:”+un+”,age,”+age);
return “success”;
}
例:
@RestController
public class SubjectiveQuestionCountController {
@Autowired
private FindAllQuestionScoreService2 findAllQuestionScoreService2;
//根据学生id,学科id,试题类型查找试题
@RequestMapping(value="/student2",method = RequestMethod.GET)
public List<SubjectiveQuestion> getSubjectiveQuestionCount(int studentid,String subject,int question_typeid){
//List<SubjectiveQuestion>sqlist=findAllQuestionScoreService2.findAllQuestionScoreByStudentId2(studentid,subject,question_typeid);
List<SubjectiveQuestion>sqlist=findAllQuestionScoreService2.findAllQuestionScoreByStudentId2(4585,"数学",1);
return sqlist;
}
}
解决方法:
@RestController
public class SubjectiveQuestionCountController {
@Autowired
private FindAllQuestionScoreService2 findAllQuestionScoreService2;
//根据学生id,学科id,试题类型查找试题
@RequestMapping(value="/student2",method = RequestMethod.GET)
public List<SubjectiveQuestion> getSubjectiveQuestionCount(@RequestParam(value ="studentid",required = false,defaultValue = "0") int studentid, String subject,@RequestParam(value ="question_typeid",required = false,defaultValue = "0") int question_typeid{
//List<SubjectiveQuestion>sqlist=findAllQuestionScoreService2.findAllQuestionScoreByStudentId2(studentid,subject,question_typeid);
List<SubjectiveQuestion>sqlist=findAllQuestionScoreService2.findAllQuestionScoreByStudentId2(4585,"数学",1);
return sqlist;
}
}