Difference between javax.servlet-api.jar vs servlet-api.jar

只谈情不闲聊 提交于 2019-12-18 14:08:06

问题


In my maven repository under groupId javax.servlet i have these two separate artifacts for servlets. I am confused which one should i use to build a simple servlet application? What's the difference between these two artifacts?


回答1:


javax.servlet-api version 3.0.1 has annotation folder which contains different annotation classes where servlet-api version 2.5 or below (i.e version 2.4) does not contain annotation.

Annotation represents the metadata. If you use annotation, deployment descriptor i.e. web.xml is not required. For example if you use annotation like @WebServlet("/hello") in your servlet file then you don't need to mention servlet mapping in web.xml file.

Some of useful Annotations are:

@HandlesTypes
@HttpConstraint 
@HttpMethodConstraint
@MultipartConfig
@ServletSecurity
@WebFilter
@WebInitParam
@WebListener
@WebServlet



回答2:


You need to add

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
</dependency>

to your project. The version you need may differ - it depends on your servlet container, e.g. Tomcat.

<scope>provided</scope> because you don't need it in runtime, it's already in your servlet container.




回答3:


Go with javax.servlet-api.jar , Many developers mistakenly include servlet-api.jar in their WEB-INF/lib folder. This no longer causes an exception because Tomcat and other app servers will recognize it as a problem when deploying the JAR file. However, it does cause the container to ignore any JAR file that contains the javax/servlet/Servlet.class.




回答4:


If you have to deploy on an ancient application server version that doesn't support the servlet 3.0 spec (hopefully unlikely), stick with the old servlet-api.

With the 3.0 spec, they moved it over to javax.servlet-api. See: https://javaee.github.io/servlet-spec/

Now, with the move of Java EE from Oracle to the Eclipse Foundation (Jakarta EE), the spec has again moved. If at all possible you may want to consider using the new group and artifact if you want to stay up-to-date: jakarta.servlet:jakarta.servlet-api

https://github.com/eclipse-ee4j/servlet-api




回答5:


For those using gradle...

If I declare my dependency using compileOnly as below

compileOnly "javax.servlet:javax.servlet-api:3.1.0"

then I get a compilation error:

error: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletRequest;
                         ^

If I use providedCompile as below the build is successful.

providedCompile "javax.servlet:javax.servlet-api:3.1.0"

To use providedCompile dependencies you need to use the war plugin.

apply plugin: 'war'


来源:https://stackoverflow.com/questions/34349047/difference-between-javax-servlet-api-jar-vs-servlet-api-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!