问题描述:
SpringBoot在操作Session时产生异常报错:No primary or single unique constructor found for interface javax.servlet.http.HttpSession。
源码:
@GetMapping("/s1")
public Result session1(HttpSession session){
log.info("HttpSession-s1: {}", session.hashCode());
session.setAttribute("loginUser", "tom"); //往session中存储数据
return Result.success();
}
其中原本是直接从黑马程序员提供的代码复制粘贴进来的 import javax.servlet.http.HttpSession类,如下(错误演示):
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
错误截图
错误原因:
开始为了解决HttpServletResponse等方法爆红问题,就在pom.xml中注入了javax.servlet-api依赖,虽然爆红解决,但是会出现上述问题,原因就是HttpServletResponse实际上是一个接口,不能直接实例化,所以在使用Spring等框架时,确保HttpServletResponse是通过方法参数注入的,而不是作为一个bean来注入。
解决方法:
检查pom.xml文件中是否注入javax.servlet-api依赖,如果有,将此依赖注释掉;把原本javax.servlet 类全部删除,利用springboot3自动导入import jakarta.servlet包;