I'm trying to set up a WebSocketServlet in Jetty.
I've set up a servlet according to this guide, and implemented the WebSocket according to this one. However, when I run gradle jettyRun
and attempt to open a connection (using this) to ws://localhost:8080/myProjectName/echo
), I get java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getServletContext()
(full stacktrace)
I see that this method was only introduced in servlet 3.0 - however, since I'm using servlet-api:3.1.0
, I believe I should have that method?
I'm reasonably sure that the routing in my WEB-INF/web.xml
is correct, since when I try to hit another url (ws://localhost:8080/myProjectName/echo123
, for instance), I don't get error output on the terminal.
Files:
build.gradle:
apply plugin: 'java'
apply plugin : 'jetty'
sourceCompatibility = 1.5
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
compile 'javax.servlet:javax.servlet-api:3.1.0'
compile 'org.eclipse.jetty:jetty-server:9.3.2.v20150730'
compile 'org.eclipse.jetty.websocket:websocket-servlet:9.0.0.M3'
compile 'org.eclipse.jetty.aggregate:jetty-all:9.1.3.v20140225'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
src/main/webapp/WEB-INF/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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
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">
<servlet>
<servlet-name>EchoServlet</servlet-name>
<servlet-class>org.scubbo.myprojectname.EchoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EchoServlet</servlet-name>
<url-pattern>/echo</url-pattern>
</servlet-mapping>
</web-app>
src/main/java/org/scubbo/myprojectname/EchoServlet.java
package org.scubbo.myprojectname;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.scubbo.myprojectname.sockets.EchoSocket;
public class EchoServlet extends WebSocketServlet {
@Override
public void configure(WebSocketServletFactory factory) {
factory.getPolicy().setIdleTimeout(10000);
factory.register(EchoSocket.class);
}
src/main/java/org/scubbo/myprojectname/sockets/EchoSocket.java
package org.scubbo.myprojectname.sockets;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
@WebSocket
public class EchoSocket {
@OnWebSocketMessage
public void onText(Session session, String message) {
if (session.isOpen()) {
System.out.printf("Echoing back message [%s]%n", message);
session.getRemote().sendString(message, null);
}
}
}