Ajax call fails with Javafx Webview - ajax

Followed this, though Ajax calls from link executes without any errors, having below function in a HTML fails still
$(document).ready(function() {
alert("Ready");
$.ajax({
url: "https://www.google.com/",
type: 'GET',
cache: false,
data: "{'name':'hi'}",
contentType: 'application/json',
dataType: 'json',
async: true,
success: function(res) {
alert('success res-:' + JSON.stringify(res));
},
error: function(res) {
alert('error res-:' + JSON.stringify(res));
}
});
Update Java Code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
public class FXWebViewSO extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX WebView Example");
WebView webView = new WebView();
webView.getEngine().setJavaScriptEnabled(true);
webView.getEngine().setOnAlert(event -> showAlert(event.getData()));
webView.getEngine().setJavaScriptEnabled(true);
JSObject window = (JSObject) webView.getEngine().executeScript("window");
window.setMember("window", null);
// webView.getEngine().load("file://webview.html"); // Fails - HTML having above Ajax function
webView.getEngine().load("http://www.jquerysample.com/#BasicAJAX"); // Works
final Scene scene = new Scene(webView);
primaryStage.setScene(scene);
primaryStage.show();
}
private void showAlert(String message) {
System.out.println(message);
Dialog<Void> alert = new Dialog<>();
alert.getDialogPane().setContentText(message);
alert.getDialogPane().getButtonTypes().add(ButtonType.OK);
alert.showAndWait();
}
}
Note: The same works fine in couple of windows machines and failes from Ubuntu Desktop.
Environment details below
Ubuntu - 1.8.0_151 - Failed (Tried upgrading too still no luck).
Windows7 - 1.8.0_221 - Works

Related

Failed to load resource: the server responded with a status of 404 (Not Found) Angular12 Spring boot

I am new to Sping Boot, rest api and angular12,
I am running my program in vscode to call the back api and i get the error "Failed to load resource: the server responded with a status of 404 (Not Found)"
my codes:
backend controller :
#RestController
#RequestMapping("/evaluationController/")
public class EvaluationController {
#Autowired
private EvaluationRepository evaluationrepository;
//get all evaluationsnotes
#CrossOrigin(origins = "http://localhost:4200/")
#GetMapping("/notes")
public List<EvaluationModel> getAllEvaluations(){
return evaluationrepository.findAll();
}
//post notes
#PostMapping("/notes")
public EvaluationModel createEvaluationNote(#RequestBody EvaluationModel evaluationNote) {
return evaluationrepository.save(evaluationNote);
}
}
My front end angular12 service
#Injectable({
providedIn: 'root'
})
export class EvaluationserviceService {
private baseUrl!: "http://localhost:8080/evaluationController/notes";
constructor(private httpClient: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
getEvaluationNotes():Observable<Evaluationotes[]>{
return this.httpClient.get<Evaluationotes[]>(`${this.baseUrl}`);
}
}
my typescript file
#Component({
selector: 'app-fin-evaluation',
templateUrl: './fin-evaluation.component.html',
styleUrls: ['./fin-evaluation.component.css']
})
export class FinEvaluationComponent implements OnInit {
evaluationNote!: Evaluationotes[];
constructor(private evaluationNoteService: EvaluationserviceService ) { }
ngOnInit(): void {
this.getAllNotes();
}
private getAllNotes(){
this.evaluationNoteService.getEvaluationNotes().subscribe(data=>{
this.evaluationNote = data;
});
}
}
Thank you!
The issue is with the baseUrl, you need to use = (used for initialization) instead of : (used in typescript to define an objects type). Since you are never really initializing the variable with proper url, request is going to some random url like http://localhost:4200/undefined causing 404. You can update the url as follows and try:
private baseUrl = "http://localhost:8080/evaluationController/notes";

Javafx - open login.microsoftonline.com page in webview component

I have problem with opening login.microsoftonline.com page in webview component from javafx. I have simply code that should open this page without any trouble:
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
var url = "https://login.microsoftonline.com/";
webEngine.load(url);
VBox root = new VBox();
root.getChildren().add(webView);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
webEngine.getLoadWorker().stateProperty().addListener((obs, oldValue, newValue) -> {
System.out.println(webEngine.getLocation());
});
When I try to execute this code on machine with windows operating system I receive blank page:
When I execute the same code on macbook, site is opening:
I'm using java 10 and really no idea what's wrong. Does anybody have the same issue? Any idea how to solve this problem? maybe there is other component instead of webview that I can use to do my stuff?
This is not the solution to your problem but may lead you in the right direction. It seems that the site body is loaded using script. That script depends on other scripts I am guessing. It appears none of the other scripts are loading.
import com.sun.javafx.webkit.WebConsoleListener;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
*
* #author blj0011
*/
public class JavaFXApplication281 extends Application
{
#Override
public void start(Stage primaryStage)
{
try {
TrustManager trm = new X509TrustManager()
{
#Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
#Override
public void checkClientTrusted(X509Certificate[] certs, String authType)
{
}
#Override
public void checkServerTrusted(X509Certificate[] certs, String authType)
{
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{trm}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
WebConsoleListener.setDefaultListener(new WebConsoleListener()
{
#Override
public void messageAdded(WebView webView, String message, int lineNumber, String sourceId)
{
System.out.println("Console: [" + sourceId + ":" + lineNumber + "] " + message);
}
});
webEngine.setJavaScriptEnabled(true);
String url = "https://login.microsoftonline.com/";//"https://login.microsoftonline.com/jsdisabled";//
webEngine.load(url);
webEngine.getLoadWorker().stateProperty().addListener((obs, oldValue, newValue) -> {
System.out.println(newValue);
String html = (String) webEngine.executeScript("document.documentElement.outerHTML");
System.out.println(html);
});
webEngine.setOnError((event) -> {
System.out.println(event.getMessage());
});
// webEngine.getLoadWorker().exceptionProperty().addListener((obs, oldExc, newExc) -> {
// if (newExc != null) {
// newExc.printStackTrace();
// }
// });
StackPane root = new StackPane();
root.getChildren().add(webView);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
catch (KeyManagementException ex) {
ex.printStackTrace();
}
catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
Output:
Console: [null:0] Cannot load stylesheet https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/converged.v2.login.min_jumzhgrnvlj7lwxqltrteq2.css. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Cannot load stylesheet https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/converged.v2.login.min_jumzhgrnvlj7lwxqltrteq2.css. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Cannot load stylesheet https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/converged.v2.login.min_jumzhgrnvlj7lwxqltrteq2.css. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Failed to load external resource ['https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/converged.v2.login.min_jumzhgrnvlj7lwxqltrteq2.css']
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/oldconvergedlogin_pcore.min_lwozjqawrstmtzsn2yunha2.js. Failed integrity metadata check.
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/convergedloginpaginatedstrings-en.min_uzcugprrg6vz0z16am4meq2.js. Failed integrity metadata check.
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/oldconvergedlogin_pcore.min_lwozjqawrstmtzsn2yunha2.js. Failed integrity metadata check.
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/convergedloginpaginatedstrings-en.min_uzcugprrg6vz0z16am4meq2.js. Failed integrity metadata check.
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/oldconvergedlogin_pcore.min_lwozjqawrstmtzsn2yunha2.js. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Failed to load external resource ['https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/oldconvergedlogin_pcore.min_lwozjqawrstmtzsn2yunha2.js']
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/convergedloginpaginatedstrings-en.min_uzcugprrg6vz0z16am4meq2.js. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Failed to load external resource ['https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/convergedloginpaginatedstrings-en.min_uzcugprrg6vz0z16am4meq2.js']
The above will also show you the HTML that was loaded. It is too long to add.
Some code from here to help troubleshoot the problem.
I do not have Java 10. I used Java 8.
I found out that web view is using webkit engine for mac os/ linux os and IE engine for windows machines. WebView on mac os is working fine but there is problem on windows machines. When I was investigating this issue I find out that there is problem in this IE engine. I have access to few machines with different version of IE 11 installed on. On machines with update version 11.0.85 I wasn't able to open this site, but when I tried on machine with update version 11.0.90 the problem doesn't exist anymore. So if someone is using Windows OS please try to update IE version maybe it will solve problem.
Had the same issue and I think I found the critical point: external script/link integrity fails.
This is not a platform browser issue, JavaFX (OpenJFK) relies on an embedded webkit engine.
The regression happened between version 40 and version 172 on windows JDK 8.
It's working fine with Oracle JDK 9.0.4
It's not working with Oracle JDK 11
More details at:
https://github.com/mguessan/davmail/issues/12
Issue similar to: Javafx - open login.microsoftonline.com page in webview component
=> Updated answer: implemented to override Microsoft form content and disable integrity check. This is not a fix of the webkit bug, just a workaround
try {
URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
#Override
public URLStreamHandler createURLStreamHandler(String protocol) {
if ("https".equals(protocol)) {
return new sun.net.www.protocol.https.Handler() {
#Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
System.out.println("openConnection " + url);
if (url.toExternalForm().endsWith("/common/handlers/watson")) {
System.out.println("Failed: form calls watson");
}
final HttpsURLConnectionImpl httpsURLConnection = (HttpsURLConnectionImpl) super.openConnection(url, proxy);
if ("login.microsoftonline.com".equals(url.getHost())
&& "/common/oauth2/authorize".equals(url.getPath())) {
return new URLConnection(url) {
#Override
public void connect() throws IOException {
httpsURLConnection.connect();
}
public InputStream getInputStream() throws IOException {
byte[] content = readFully(httpsURLConnection.getInputStream());
String contentAsString = new String(content, "UTF-8");
System.out.println(contentAsString);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(contentAsString.replaceAll("integrity", "integrity.disabled").getBytes("UTF-8"));
return new ByteArrayInputStream(baos.toByteArray());
}
public OutputStream getOutputStream() throws IOException {
return httpsURLConnection.getOutputStream();
}
};
} else {
return httpsURLConnection;
}
}
};
}
return null;
}
});
} catch (Throwable t) {
System.out.println("Unable to register custom protocol handler");
}

OpenShift: Cannot Connect to WebSocket with Alias (bug)

I have a Java Spring Web application which uses WebSockets. An HTML file connects to the WebSocket using the uri:
var wsUri = "wss://" + document.location.hostname + ":8443" + "/serverendpoint";
Here is my serverendpoint.java code that creates the WebSocket:
package com.myapp.spring.web.controller;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.web.socket.server.standard.SpringConfigurator;
#ServerEndpoint(value="/serverendpoint", configurator = SpringConfigurator.class)
public class serverendpoint {
#OnOpen
public void handleOpen () {
System.out.println("JAVA: Client is now connected...");
}
#OnMessage
public String handleMessage (Session session, String message) throws IOException {
if (message.equals("ping")) {
// return "pong"
session.getBasicRemote().sendText("pong");
}
else if (message.equals("close")) {
handleClose();
return null;
}
System.out.println("JAVA: Received from client: "+ message);
MyClass mc = new MyClass(message);
String res = mc.action();
session.getBasicRemote().sendText(res);
return res;
}
#OnClose
public void handleClose() {
System.out.println("JAVA: Client is now disconnected...");
}
#OnError
public void handleError (Throwable t) {
t.printStackTrace();
}
}
When I connect to the websocket using the http://myapp-myproject.rhcloud.com/mt URL, the WebSocket connects. However, when I set up an alias to the http://myapp-myproject.rhcloud.com, which is called https://someurl.com/mt, the websocket doesn't connect. Why is this? I get the following error message in Google Chrome:
Furthermore, the websocket uses a wss connection at port 8443. This is a secure request equivalent to https. Therefore, how can it work with the http://myapp-myproject.rhcloud.com/mt URL which is an http URL, and why is it not connecting with the alias?
Thank you so much for your help!

Swing apllication with embedded JavaFX WebView won't play html5 video only sound

In my Swing application I needed support for rendering html. So I embedded a JavaFX WebView in my Swing application. Now on some html pages I use the new html5 -Tag to play a video. This works perfectly on Windows and Linux. But on MacOS I only hear the sound and see a black video frame and the time track in the bottom.
Here is an SSCCE I got from github. I just changed the url to one that contains a html5 video-tag example. Would be great, if you MacOS users could try it and tell me if the same happens on you computer. And of course any idea to fix this is appreciated.
SSCCE:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.sun.javafx.application.PlatformImpl;
/**
* SwingFXWebView
*/
public class JavaFXTest extends JPanel
{
private Stage stage;
private WebView browser;
private JFXPanel jfxPanel;
private JButton swingButton;
private WebEngine webEngine;
private Object geo;
public JavaFXTest()
{
this.initComponents();
}
public static void main(final String... args)
{
// Run this later:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
final JFrame frame = new JFrame();
frame.getContentPane().add(new JavaFXTest());
frame.setMinimumSize(new Dimension(640, 480));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
private void initComponents()
{
this.jfxPanel = new JFXPanel();
this.createScene();
this.setLayout(new BorderLayout());
this.add(this.jfxPanel, BorderLayout.CENTER);
this.swingButton = new JButton();
this.swingButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(final ActionEvent e)
{
Platform.runLater(new Runnable()
{
#Override
public void run()
{
JavaFXTest.this.webEngine.reload();
}
});
}
});
this.swingButton.setText("Reload");
this.add(this.swingButton, BorderLayout.SOUTH);
}
/**
* createScene Note: Key is that Scene needs to be created and run on
* "FX user thread" NOT on the AWT-EventQueue Thread
*/
private void createScene()
{
PlatformImpl.startup(new Runnable()
{
#Override
public void run()
{
JavaFXTest.this.stage = new Stage();
JavaFXTest.this.stage.setTitle("Hello Java FX");
JavaFXTest.this.stage.setResizable(true);
final Group root = new Group();
final Scene scene = new Scene(root, 80, 20);
JavaFXTest.this.stage.setScene(scene);
// Set up the embedded browser:
JavaFXTest.this.browser = new WebView();
JavaFXTest.this.webEngine = JavaFXTest.this.browser.getEngine();
JavaFXTest.this.webEngine.load("http://camendesign.com/code/video_for_everybody/test.html");
final ObservableList<Node> children = root.getChildren();
children.add(JavaFXTest.this.browser);
JavaFXTest.this.jfxPanel.setScene(scene);
}
});
}
}
Here is a semi-answer, which might help:
The oracle website states:"At this time, Online Installation and Java Update features are not available for 64-bit architectures"
For me this caused lots of problems, because Java seems up to date, but actually isn't. On some machines I could solve the actual issue by just manually updating the Java 64bit VM. On Mac however, the video still isn't playing, only sound.
The 64bit/32bit issue gets even worse, since a double click on a jar might start it in the 64bit JVM, but via console it is started in 32bit JVM. So if you do a "java -version" in console, the output might be "1.7.0 u45 32-bit", but as soon as you start the jar via double click it is started in an outdated 64bit JVM.
So if you ever run in an JavaFX issue (especially with UnsatisfiedLinkError) and you have a 64bit computer, just install the latest 64bit java and hope that it solves the problem.

Websocket - httpSession returns null

I would like to make the connection between a websocket handshake \ session to a HttpSession object.
I've used the following handshake modification:
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator
{
#Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,
HandshakeResponse response)
{
HttpSession httpSession = (HttpSession)request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
As mentioned in this post:
Accessing HttpSession from HttpServletRequest in a Web Socket #ServerEndpoint
Now,
For some reason on the hand shake, the (HttpSession)request.getHttpSession() returns null all the time.
here is my client side code:
<!DOCTYPE html>
<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div>
<input type="submit" value="Start" onclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket =
new WebSocket('ws://localhost:8080/com-byteslounge-websockets/websocket');
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
document.getElementById('messages').innerHTML
+= '<br />' + event.data;
}
function onOpen(event) {
document.getElementById('messages').innerHTML
= 'Connection established';
}
function onError(event) {
alert(event.data);
}
function start() {
webSocket.send('hello');
return false;
}
</script>
</body>
</html>
Any ideas why no session is created ?
Thanks
This is intended behaviour, but I agree it might be confusing. From the HandshakeRequest.getHttpSession javadoc:
/**
* Return a reference to the HttpSession that the web socket handshake that
* started this conversation was part of, if the implementation
* is part of a Java EE web container.
*
* #return the http session or {#code null} if either the websocket
* implementation is not part of a Java EE web container, or there is
* no HttpSession associated with the opening handshake request.
*/
Problem is, that HttpSession was not yet created for your client connection and WebSocket API implementation just asks whether there is something created and if not, it does not create it. What you need to do is call httpServletRequest.getSession() sometime before WebSocket impl filter is invoked (doFilter(...) is called).
This can be achieved for example by calling mentioned method in ServletRequestListener#requestInitalized or in different filter, etc..
Here is an impl for Pavel Bucek's Answer, after adding it, i got my session
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
#WebListener
public class RequestListener implements ServletRequestListener {
#Override
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
#Override
public void requestInitialized(ServletRequestEvent sre) {
((HttpServletRequest) sre.getServletRequest()).getSession();
}
}
Building on #pavel-bucek 's answer, I wrote a simple HttpSessionInitializerFilter servlet filter.
Just download the jar from the "Releases" page and save it anywhere in the classpath, then add the following snippet to your web.xml descriptor (modify the url-pattern as needed):
<filter>
<filter-name>HttpSessionInitializerFilter</filter-name>
<filter-class>net.twentyonesolutions.servlet.filter.HttpSessionInitializerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpSessionInitializerFilter</filter-name>
<url-pattern>/ws/*</url-pattern>
</filter-mapping>
first: create a new class
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
#WebListener
public class RequestListener implements ServletRequestListener {
#Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
}
#Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
((HttpServletRequest)servletRequestEvent.getServletRequest()).getSession();
}
}
and then add the "ServletComponentScan" annotation on the App main:
#SpringBootApplication
#ServletComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Resources