Is there any way to use websockets in tomcat 6 (business requirement)?
I've been trying using javax.websocket.jar but I can't get it to work
Here's my code:
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echoAnnotation")
public class EchoAnnotation { #OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendText(msg, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
And my web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<description>
Servlet and JSP Examples.
</description>
<display-name>Servlet and JSP Examples</display-name>
<servlet>
<servlet-name>echoAnnotation</servlet-name>
<servlet-class>EchoAnnotation</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>echoAnnotation</servlet-name>
<url-pattern>/echoAnnotation</url-pattern>
</servlet-mapping>
</web-app>
However I cannot make a websocket connection, I get an error message Firefox can't establish a connection to the server at ws://192.168.1.101:8080/prototypes/echoAnnotation and going directly to the page results in HTTP Status 404 - Servlet echoAnnotation is not available
Is this possible? What am I doing wrong?
As I found tomcat 6 doesn't support Java WebSockets. See http://tomcat.apache.org/whichversion.html
Related
I am using tomcat version 10.0.10
This is the error I am getting when I press Submit in my index.html file
Even if I add a constructor the AddServlet is still not instantiating
I have tried to run the same code in tomcat version(apache-tomcat-8.5.61) still facing the same error.
index.html
This is the sevlet code AddServlet.java
package com.sintin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.*;
import java.util.*;
import java.io.*;
public class AddServer extends HttpServlet{
private static final long serialVersionUID = 102831973239L;
public AddServer() {
}
public void service(HttpServletRequest req , HttpServletResponse res) throws
IOException, ServletException {
System.out.println("in the AddServer class");
int x = Integer.parseInt(req.getParameter("num1"));
int y = Integer.parseInt(req.getParameter("num2"));
// String stir="sintnada";
// PrintWriter out = res.getWriter();
// out.println("the result is"+ x+y);
System.out.println("ans="+x+y);
RequestDispatcher rd = req.getRequestDispatcher("class2");
rd.forward(req, res);
}
}
This is the xml file web.xml inside my webapp/web-INF
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>com.sintin.AddServer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>class2</servlet-name>
<servlet-class>com.sintin.Class2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>class2</servlet-name>
<url-pattern>/class2</url-pattern>
</servlet-mapping>
</web-app>
when I was using JDK provided by amazon(Amazon Corretto JDK 11.0.9_12) I faced This issue.
I resolved this issue by installing java(JDK-17.0.1) by oracle and reinstalled eclipse.
I have a Tomcat Server and I'm trying to access the index.html file located in the WEB-INF folder, as shown in the picture below
As seen in the picture, when I open http://localhost:9999/index.html it throws a 404
This is my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="CERTHMaTHiSiSOpenAPI" version="3.1">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>OpenAPI</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
api.ws;api.ws.oper
</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>api.ws.oper.Authorization</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>OpenAPI</servlet-name>
<url-pattern>/api/*</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Is it a problem that it's located under WEB-INF/lib? I tried moving it to WEB-INF with no success.
Edit: This is my Properties > Web Project Settings Tab:
It should be noted that this project has also an API, and under Java Resources > src > ws it has a Conductor.java file with this content:
package ws;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
import ws.util.Config;
#ApplicationPath("/")
public class Conductor extends Application {
#Context ServletContext context;
public static Properties properties = new Properties();
public Conductor() {
super();
BeanConfig beanConfig = new BeanConfig();
BeanConfig beanConfig2 = new BeanConfig();
beanConfig.setVersion("3.1.1");
beanConfig.setSchemes(new String[]{"https","http"});
// beanConfig.setHost("localhost:8080");
beanConfig.setBasePath("/api");
beanConfig.setResourcePackage("ws.lg");
beanConfig.setTitle("LG lib Open API");
beanConfig.setScan(true);
Swagger swaglg = new Swagger();
swaglg = beanConfig.getSwagger();
swaglg.setBasePath("/api/lg");
beanConfig2.setVersion("3.1.1");
beanConfig2.setSchemes(new String[]{"https","http"});
// beanConfig.setHost("localhost:8080");
beanConfig2.setBasePath("/api");
beanConfig2.setResourcePackage("ws.sla");
beanConfig2.setTitle("SLA lib Open API");
beanConfig2.setScan(true);
Swagger swaglg2 = new Swagger();
swaglg2 = beanConfig2.getSwagger();
swaglg2.setBasePath("/api/sla");
createSwaggerJsonFile(beanConfig, "swagger-lg.json");
createSwaggerJsonFile(beanConfig2, "swagger-sla.json");
}
// public static final int REST_PORT = 8080;
#Override
public Set<Class<?>> getClasses(){
readProperties();
Set<Class<?>> resources = new HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources){
resources.add(ws.sla.SLAlibOpenAPI.class);
resources.add(ws.lg.LGlibOpenAPI.class);
resources.add(ws.auth.Authorization.class);
resources.add(ApiListingResource.class);
resources.add(SwaggerSerializers.class);
//to turn off
// resources.add(ws.helpers.MongoModifiersAPI.class);
}
private Properties readProperties() {
String fullPath = context.getRealPath(Config.PROPERTIES_FILE);
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(fullPath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if (inputStream != null) {
try {
properties.load(inputStream);
} catch (IOException e) {
// TODO Add your custom fail-over code here
e.printStackTrace();
}
}else{
System.err.println("Cannot read config file or no config file exists.");
}
return properties;
}
// /*
private static void createSwaggerJsonFile(BeanConfig beanConfig, String filename) {
try (FileWriter fileWriter = new FileWriter(filename)) {
File f = new File(filename);
fileWriter.write(Json.pretty(beanConfig.getSwagger()));
fileWriter.flush();
System.out.println("File " + filename + " successfully created in " + f.getAbsolutePath());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// */
}
You should place your html content inside WebContent folder, not inside web-inf. As it searches the index.html in WebContent and its not there so its showing 404 not found error.
Have a look at this question having similar situation and possible answer
StackOverFlow Question
The solution was to move all the swagger-ui files to a new folder under WebContent (which I called ui), to move the web.xml to WEB-INF and to add a simple servlet-mapping inside web.xml:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/ui/*</url-pattern>
</servlet-mapping>
the problem was that the /api/* url-pattern in the OpenAPI servlet, was consumed by the API.
I had a similar issue. I was confused between html front pages stored in WebContent, and servlets produced by the Java code.
Tomcat searches for .html files in WebContent, as indicated in Context Parameters. The url-parameter of the servlet mapping tells Tomcat where to look for the servlet itself. To me, it's then logical that both locations needs to be different.
My servlet-mapping looks like <url-pattern>/api/*</url-pattern>. My application class contains #Path('/sname'). While keeping WEB-INF/web.xmlas simple as possible, this gives me access to html pages at localhost:8080/ and to servlets at localhost:8080/api/sname.
By default, ROOT war index.html(or welcome-file-list) will be called when you try to access using http://localhost:9999/index.html
If you want to change tomcat default loading page then edit server.xml file and update the following
<Context path="" docBase="new_default_app" />
This is my web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>NewsPortal</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.newsportal</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
There may be something wrong with web.xml but I am not sure.
Here is my web service .
package com.newsportal;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import com.newsportal.utility.ErrorReporting;
#Path("/Authentication")
public class AuthenticationResource {
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.APPLICATION_JSON)
#Path("/login")
public Response login(#FormParam("emailOrPhone") String emailOrPhone,#FormParam("password") String password){
String response ="";
try{
}catch(Exception ex){
ErrorReporting.webServiceError(ex);
}
return Response.ok(response)
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
This is JAX-RS i think here most of the code looks fine .
Here is my jquery I am trying to invoke this login method
var Index = function() {
var handleIndexLoad = function() {
// no authentication at load
}
var handlelogin = function() {
var emailOrPhone='admin#nextolive.com';
var password ='12345';
$.ajax({
method : "POST",
url : "Authentication/login/",
data :'emailOrPhone='+ emailOrPhone +'&password='+password,
}).done(function(response) {
console.log(response);
});
}
return {
// main function to initiate the module
init : function() {
handleIndexLoad();
handlelogin();
}
};
}();
This is index.js file . I think here also things are fine .
To be honest I am new to Java so , i am not really sure if I am following
the right pattern .
Please tell me what i need to do fix it .
Hi I am trying to run a servlet which gets the data from a simple html form and stores in oracle database and displays a message "Data Saved". I am using Eclipse Luna, Tomcat 7.0 and Oracle 11g Express Edition. When I run the the program I get this error.
java.sql.SQLException: Io exception: Got minus one from a read call
during JDBC connection with oracle 11g
Here is my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>StudentManagement</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>StudentRegServlet</servlet-name>
<servlet-class>com.serv.pkg.StudentRegServlet</servlet-class>
<init-param>
<description></description>
<param-name>username</param-name>
<param-value>scott</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>tiger</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StudentRegServlet</servlet-name>
<url-pattern>/stdreg</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>CourseRegServlet</servlet-name>
<servlet-class>com.serv.pkg.CourseRegServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>test</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>test</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CourseRegServlet</servlet-name>
<url-pattern>/coursereg</url-pattern>
</servlet-mapping>
<context-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.OracleDriver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:#localhost:8080:XE</param-value>
</context-param>
</web-app>
My Servlet
package com.serv.pkg;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
/**
* Servlet implementation class CourseRegServlet
*/
#WebServlet("/CourseRegServlet")
public class CourseRegServlet extends GenericServlet {
private Connection conn;
#Override
public void init(ServletConfig config)throws ServletException
{
System.out.println("Executing init method from coursereg.html");
ServletContext sc = config.getServletContext( );
String driver=sc.getInitParameter("driver");
String url=sc.getInitParameter("url");
String username=config.getInitParameter("username");
String password=config.getInitParameter("password");
try {
Class.forName(driver);
System.out.println("driver loaded");
conn=DriverManager.getConnection(url, username, password );
} catch ( Exception e) {
System.out.println("catching from init" +e);
}
}
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
System.out.println("Executing service method from coursereg.html");
int cid = Integer.parseInt(request.getParameter("cid"));
String c_name = request.getParameter("c_name");
int fee = Integer.parseInt(request.getParameter("fee"));
try {
System.out.println("exe1");
PreparedStatement stmt=conn.prepareStatement("insert into course values(?,?,?)");
System.out.println("exe2");
stmt.setInt(1, cid);
stmt.setString(2, c_name);
stmt.setInt(3, fee);
int i = stmt.executeUpdate();
if(i!=0){
System.out.println("course registered");
}else
{
System.out.println("registration failed");
}
} catch ( Exception e) {
System.out.println(e);
}
out.println("Data saved");
}
public void destroy(){
try {
System.out.println("Executing destroy method from coursereg.html");
conn.close();
} catch ( Exception e) {
System.out.println(e);
}
}
}
The default port for the database listener is 1521, not 8080 (which is the default HTTP port, from XML DB); so your URL should be:
<param-value>jdbc:oracle:thin:#localhost:1521:XE</param-value>
If your listener is on a non-standard port then use that instead. Also the :XE part means it'll try to connect with the SID XE. You might prefer to use the service name, which is hopefully also XE, which would be denoted by a slash instead of a colon:
<param-value>jdbc:oracle:thin:#localhost:1521/XE</param-value>
This question already has answers here:
How do I import the javax.servlet / jakarta.servlet API in my Eclipse project?
(16 answers)
Closed 4 years ago.
I was able to make my app works again, following the advices of user2821894, but after trying to call a servlet tomcat 7 stopped working again!!
If i try to delete the code where i call my servlet my web app doesent' work!!
Once i have a problem with a servlet tomcat stops working.
I had problem launching my web project on eclipse. I had problem with Tomcat 7.
So i 'delete' tomcat 7 from eclipse and then i added it again (again tomcat 7).
now i have no problem launching my web project, but i have problem on my servlet.
For example i get error like
WebServlet cannot be resolved to a type
The attribute value is undefined for the annotation type
I added servlet-api 3.0.jar to my project but i still have these problems.
This is the code of my servlet
package Jeans;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import com.sun.java.swing.plaf.windows.TMSchema.Part;
import javax.servlet.http.Part;
#WebServlet("/FileUploadDBServlet ")
//// i got an error here////////////////////////////
#MultipartConfig(maxFileSize = 16177215)
public class FileUploadDBServlet extends HttpServlet {
private String dbURL = "db";
private String dbUser = "dbuser";
private String dbPass = "dbpassword";
String messageMio = "da contorllare";
GestioneDB gestioneDB;
boolean connessione;
Connection conn;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String giorno= request.getParameter("giorno");
String mese= request.getParameter("mese");
String anno= request.getParameter("anno");
String dataFormatoItaliano = giorno + "-" + mese + "-" + anno;
String titolo = request.getParameter("titolo");
String titoletto = request.getParameter("titoletto");
String testoMouse = request.getParameter("testoMouse");
String link = request.getParameter("link");
String data = dataFormatoItaliano;
String testo = request.getParameter("testo");
//// i got an error here////////////////////////////
Part filePart = request.getPart("immaginePrincipale");
String didascaliaImmaginePrincipale = request.getParameter("didascaliaImmaginePrincipale");
InputStream immaginePrincipale = null;
if (filePart != null) {
// obtains input stream of the upload file
immaginePrincipale = filePart.getInputStream();
}
String message = null;
try {
gestioneDB = new GestioneDB();
conn = gestioneDB.cn();
gestioneDB.inserimentoNews(titolo, titoletto, testoMouse, link, testo, data, immaginePrincipale, didascaliaImmaginePrincipale);
String sql = "INSERT INTO allegati_news (allegato,didascalia,tipo,id_news,immagine) values (?,?,?,?,?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "firstName");
statement.setString(2, "lastName");
statement.setInt(3, 1);
statement.setInt(4,1);
if (immaginePrincipale != null) {
statement.setBlob(5, immaginePrincipale);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File salvato nel db";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
request.setAttribute("Message", gestioneDB.getInserimentoNewMessaggio());
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
This is my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Jeans2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>prova</display-name>
<servlet-name>prova</servlet-name>
<servlet-class>Jeans.prova</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>prova</servlet-name>
<url-pattern>/prova</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FileUploadDBServlet</display-name>
<servlet-name>FileUploadDBServlet</servlet-name>
<servlet-class>Jeans.FileUploadDBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadDBServlet</servlet-name>
<url-pattern>/FileUploadDBServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>BlobDisplay</display-name>
<servlet-name>BlobDisplay</servlet-name>
<servlet-class>Jeans.BlobDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BlobDisplay</servlet-name>
<url-pattern>/BlobDisplay</url-pattern>
</servlet-mapping>
</web-app>
Try adding servlet-api.jar instead of servelt-api-3.0 jar.Stop the server. Refresh the project and then start the server and see. I think it should work. Make sure you are adding the servlet-api.jar from tomcat lib folder. Suppose your tomcat is in C:\Tomcat\lib.
In eclipse right click your project-properties-javabuildpath-add external jars and then select the servlet-api.jar from your tomcat folder
Right click on project ---> Properties ---> Java Build Path ---> Add
Library... ---> Server Runtime ---> Apache Tomcat ----> Finish.
A possible reason for this error is using a wrong version of Servlet API. #WebServlet annotation is supported by Servlet 3.0. You must change the version from possibly 2.5 to 3.0. To do this in eclipse, right click your project and open Properties. Select Project Facets from the left menu of the page shown. Then change the version of Dynamic Web Module facet to 3.0.
Another possible reason can be related to your Tomcat version. Tomcat is supporting Servlet 3.0 beggining from version 7.0.