问题描述

当项目从2.7.x的springboot升级到3.0.x的时候,遇到一个问题“java: 程序包javax.servlet.http不存在” 。这可能是一些包的精简变化导致的。错误信息如下:

 错误代码段

package com.softdev.system.generator.config;

import com.softdev.system.generator.entity.ReturnT;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhengkai.blog.csdn.net
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ReturnT defaultExceptionHandler(HttpServletRequest req, Exception e) {
        e.printStackTrace();
        return ReturnT.error("代码生成失败:"+e.getMessage());
    }

}

解决方案 

Maven Repository: jakarta.servlet » jakarta.servlet-api » 6.0.0 (mvnrepository.com)

增加一下依赖即可。

		<dependency>
			<groupId>jakarta.servlet</groupId>
			<artifactId>jakarta.servlet-api</artifactId>
			<version>6.0.0</version>
			<scope>provided</scope>
		</dependency>

修改后代码如下(请注意引用部分)

package com.softdev.system.generator.config;

import com.softdev.system.generator.entity.ReturnT;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @author zhengkai.blog.csdn.net
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ReturnT defaultExceptionHandler(HttpServletRequest req, Exception e) {
        e.printStackTrace();
        return ReturnT.error("代码生成失败:"+e.getMessage());
    }

}

附录

其实很多教程仍然指向旧版的

Java Servlet is the foundation web specification in the Java Enterprise Platform. Developers can build web applications using the Servlet API to interact with the request/response workflow.

Maven Repository: javax.servlet » javax.servlet-api (mvnrepository.com)

但是新版的话已经叫Jakarta Servlet,来自Eclipse基金会,

Maven Repository: jakarta.servlet » jakarta.servlet-api » 6.0.0 (mvnrepository.com)

据说,racle在19年把javax捐给eclipse基金会,但不允许使用javax的命名空间,所以eclipse才继续发展成现在的javaee标准Jakarta,Jakarta 8与javaee 8只是换了个命名空间,jakarta9才是新的发展,spring6与spring boot3会采用Jakarta作为新的命名空间。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐