I want to access data after page load, but it doesn't work. It seems not to call the getConnection function in jsp and it doesn't call response Json. I don't know why it doesn't work. What's wrong with my code and how to fix it? Thank you very much.
MyServlet.java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
/**
* Servlet implementation class MyServlet
*/
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ArrayList<Dish> country=new ArrayList<Dish>();
country=SQLConnection.getAllDish();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(country, new TypeToken<List<Dish>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
SQLConnection.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
public class SQLConnection {
// java.sql.Connection connection;
private static Connection connection = null;
static String url, driver, username, password;
public static Connection getConnection() {
if (connection != null)
return connection;
else {
try {
Properties prop = new Properties();
InputStream inputStream = SQLConnection.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
driver = prop.getProperty("driver");
url = prop.getProperty("url");
username = prop.getProperty("user");
password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
public static ArrayList<Dish> getAllDish() {
ArrayList<Dish> arrDish = null;
try {
//Creating a statement object
Statement stmt = connection.createStatement();
//Executing the query and getting the result set
ResultSet rs = stmt.executeQuery("select * from dish");
arrDish = new ArrayList<Dish>();
//Iterating the resultset and printing the 3rd column
while (rs.next()) {
Dish item = new Dish(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDouble(4), rs.getString(5),
rs.getString(6), rs.getString(7), rs.getString(8), rs.getInt(9), rs.getInt(10), rs.getInt(11), rs.getInt(12));
arrDish.add(item);
}
//close the resultset, statement and connection.
rs.close();
stmt.close();
connection.close();
return arrDish;
} catch (SQLException e) {
e.printStackTrace();
}
return arrDish;
}
}
hello.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<html>
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath}/style.css" />
<title><fmt:message key="title" /></title>
</head>
<body bgcolor="#FEDDFF">
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/slider.js"></script>
<script>
$(window).ready(function() {
$.get('MyServlet',function(responseJson) {
if(responseJson!=null){
$("#dishes").find("tr:gt(0)").remove();
var table1 = $("#dishes");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).int(value['dishid']);
rowNew.children().eq(1).int(value['userid']);
rowNew.children().eq(2).text(value['dishName']);
rowNew.children().eq(3).double(value['numberOfPeople']);
rowNew.children().eq(4).text(value['dishImg']);
rowNew.children().eq(5).text(value['ingredient']);
rowNew.children().eq(6).text(value['step']);
rowNew.children().eq(7).text(value['descOfDish']);
rowNew.children().eq(8).int(value['category1']);
rowNew.children().eq(9).int(value['category2']);
rowNew.children().eq(10).int(value['category3']);
rowNew.children().eq(11).int(value['rate']);
rowNew.appendTo(table1);
});
}
});
});
</script>
<div id="tabledish">
<table cellspacing="0" id="dishes">
<tr>
<th scope="col">dishid</th>
<th scope="col">userid</th>
<th scope="col">dishName</th>
<th scope="col">numberOfPeople</th>
<th scope="col">dishImg</th>
<th scope="col">ingredient</th>
<th scope="col">step</th>
<th scope="col">descOfDish</th>
<th scope="col">category1</th>
<th scope="col">category2</th>
<th scope="col">category3</th>
<th scope="col">rate</th>
</tr>
</table>
</div>
</body>
in getAllDish() of SQLConnection
Check and call the getConnection();
try{
if(connection==null)
getConnection();
Statement stmt = connection.createStatement();
...
Related
I've been working on a project with my team for about a week and we still haven't been able to get websockets to work. We're running the whole server on our own machines for testing purposes and we're unsure if it'll be hosted on an HTTPS server in the future.
Using springboot we've been able to make all the basic web-site stuff work like login/registration and more, but websockets don't seem to work.....
Here's the code that we use:
package com.kanbanboard.websocket;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
#ServerEndpoint(
value="/events/{boardid}",
decoders = MessageDecoder.class,
encoders = MessageEncoder.class
)
public class WebSocketServer{
private Session session;
private static final Set<WebSocketServer> socketEndpoint = new CopyOnWriteArraySet<>();
private static final HashMap<String, String> users = new HashMap<>();
#OnOpen
public void onOpen(Session session, #PathParam("boardid") String boardid) throws IOException, EncodeException {
this.session = session;
socketEndpoint.add(this);
users.put(session.getId(), boardid);
Message msg = new Message();
msg.setFrom(boardid);
msg.setContent("Connected!");
broadcast(msg);
}
#OnMessage
public void onMessage(Session session, String message) throws IOException, EncodeException {
Message msg = new Message();
msg.setFrom(users.get(session.getId()));
broadcast(msg);
System.out.println("["+session.getId()+"]: "+message);
}
#OnClose
public void onClose(Session session) throws IOException, EncodeException {
socketEndpoint.remove(this);
Message message = new Message();
message.setFrom(users.get(session.getId()));
message.setContent("Disconnected!");
broadcast(message);
System.out.println("Connection has been with: "+session.getId());
}
#OnError
public void onError(Session session, Throwable throwable) {
System.out.println("Error reached!!!");
System.out.println(throwable);
}
private static void broadcast(Message message)
throws IOException, EncodeException {
socketEndpoint.forEach(endpoint -> {
synchronized (endpoint) {
try {
endpoint.session.getBasicRemote().
sendObject(message);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
});
}
}
The javascript we use on the client side to test the connection:
let ws = new WebSocket("ws://localhost:8080/events/1")
ws.onopen = function(ev) {
console.log("Opened connection")
ws.send("Hello World")
}
What the javascript code returns:
GETws://localhost:8080/events/1
[HTTP/1.1 404 7ms]
Firefox can’t establish a connection to the server at ws://localhost:8080/events/1. debugger eval code:1:9
Yes we've tried it on chrome too...
The thing is, when we use wss:// instead of ws:// we do get an output on intelliJ which looks like this:
java.lang.IllegalArgumentException: Invalid character found in method name [0x160x030x010x020x000x010x000x010xfc0x030x030xce0xea0x97_h0xd30xbe0xe90x080xea#0xf10xben0xdb0xf30x8cc0xd80xe30x890xfaD0xe80x1c0xb80xe80xbf0xa50x8c0xb90xc1 ]. HTTP method names must be tokens
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:419) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:271) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Any help or recommendations greatly appreciated.
Found the solution, you're not getting it.
(Just don't use Websockets and sprinboot together, it's not worth it.)
I have a login page where I authenticate the user via firebase and send the request to a servlet. When I hit the submit button with correct authentications, the firebase authentication works, servlet get called but in browser I see see an error.
First of all, this is my javascript code
function toggleSignIn() {
if (firebase.auth().currentUser) {
alert('existing user');
firebase.auth().signOut();
} else {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().signInWithEmailAndPassword(email, password).then(function (firebaseUser) {
var email = firebase.auth().currentUser.email;
const options = {
method: 'POST',
url: 'LoginValidator',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: `email=${email}`
}
url = 'LoginValidator'
fetch(url, options)
.then(response = > response.json())
.then(data = > console.log(data))
.catch(e = > console.error(e))
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
document.getElementById('quickstart-sign-in').disabled = false;
});
}
document.getElementById('quickstart-sign-in').disabled = true;
}
HTML
<div id="login-box" class="col-md-12">
<div class="form-group">
<input type="text" name="email" id="email" class="form-control login-input" placeholder="username">
</div>
<div class="form-group">
<input class="form-control login-input" type="password" placeholder="Password" id="password" name="password">
<i id="open" class="fa fa-eye fa-2x"></i>
<i id="closed" class="fa fa-eye-slash fa-2x"></i>
</div>
<div class="form-group">
<input type="submit" id="quickstart-sign-in" name="quickstart-sign-in"
class="form-control btn btn-info btn-md login-bt" value="Login" onclick="toggleSignIn()">
</div>
<div class="form-group text-center forgot">
Forgot username / password?
</div>
</div>
Below is my servlet
LoginValidator.java
public class LoginValidator extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String email = request.getParameter("email");
System.out.println("Printing email: "+email);
try {
System.out.println("inside try");
User user = new User();
UserRight userRight = new UserRight();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//Get user
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<User> call = endPoint.getUserByEmail(email);
user = call.execute().body();
System.out.println(user.getName());
//Get user rights
Call<UserRight> userRightCall = endPoint.getUserRightByID(user.getUserRights().getIduserRight());
userRight = userRightCall.execute().body();
System.out.println(userRight.getUserRight());
if(userRight.getUserRight().equals("admin"))
{
response.getWriter().write("{url:LoadSellPendingApprovals}");
}
else
{
response.getWriter().write("{url:index.html}");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The LoginValidator calls LoadSellPendingApprovals, below is its code
public class LoadSellPendingApprovals extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
List<ProductSellAdvertisement> categoryList = new ArrayList<ProductSellAdvertisement>();
try {
System.out.println("INSIDE LoadSellPendingApprovals");
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<List<ProductSellAdvertisement>> call = endPoint.getAllPendingApprovals();
categoryList = call.execute().body();
for (int i = 0; i < categoryList.size(); i++) {
System.out.println(categoryList.get(i).getProduct().getProductName());
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/product-sell-pending-approvals.jsp");
request.setAttribute("approvalList", categoryList);
requestDispatcher.forward(request, response);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is the error I get
SyntaxError: Unexpected token < in JSON at position 0
at (index):71
The line being pointed in my javascript code is this - .then(response => response.json())
The expected behavior is this
User enter credentials
Authenticate the credentials with firebase javascript api
If credentials are correct send them to the LoginValidator servlet where it will further check user`s authenticity.
Then the LoginValidator send the request to LoadSellPendingApprovals where it will execute the following code
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/product-sell-pending-approvals.jsp");
request.setAttribute("approvalList", categoryList);
requestDispatcher.forward(request, response);
In addition to the error I get, I never get forwarded to the JSP page as well. How can I fix this problem?
I am coming from java and mobile background, have no much clue on Javascript technology. Therefor appreciate detailed clear answers.
Your error indicates that the result "body" does not contain JSON but HTML:
Unexpected token < in JSON at position 0
JSON would look like this:
{ key: value }
HTML looks like this:
<html>....</html>
As the error states, the first < (position 0) is the "unexpected token". What ever is reading the body was expecting a {.
One reason for this might be that the request you are sending is redirected to a login page and therefore you get HTML instead of the expected JSON. Or you get an error page which you are trying to pass to your JSON parser.
Unfortunately, with this little information it is hard to tell. You should debug your code and check the response you are getting.
I have a backend java code for websocket.
SessionEndpoint:
#ServerEndpoint("/session")
public class SessionEndpoint {
private static Set<SessionEndpoint> sessionEndpoints = new CopyOnWriteArraySet<>();
#OnMessage
public void onMessage(Session session, String sessionId) {
Map<String, Object> attributes = new HashMap<>();
attributes.put("sessionId", sessionId);
sessionEndpoints.forEach(endpoint -> {
synchronized (endpoint) {
try {
session.getBasicRemote().sendObject(attributes);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
});
}
}
Trying to connect to websocket from javascript, code is given below.
let webSocket = new WebSocket('ws://localhost:9999/session');
webSocket.onopen = () => webSocket.send('hello');
webSocket.onmessage = function(response) {
console.log(response);
};
I get 404 response code while connecting to websocket. How should I connect to webscoket from javascript ?
I want server a pdf file instead of mp3 file please help
private HttpRequestHandler mRequestHandler = new HttpRequestHandler()
{
#Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException
{
try{
File file = new File("/mnt/sdcard/Music/song.mp3");
FileEntity body = new FileEntity(file, "audio/mpeg");
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Disposition","attachment; filename=song.mp3");
response.setEntity(body);
}catch(Exception e)
{
e.printStackTrace();
}
}
};
Change the content type to application/pdf
#Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException
{
try{
File file = new File("/my/path/file.pdf");
FileEntity body = new FileEntity(file, "application/pdf");
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Disposition","attachment; filename=file.pdf");
response.setEntity(body);
}catch(Exception e)
{
e.printStackTrace();
}
}
};
you can check mime types here
I created a sample project using Java and JavaScript. Java is used to create the server part and JavaScript is used for client part. I have used jetty version 9.0.5 to develop javaSE project.
This is my server part:
package com.websocet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
public class WebSocketTest {
public static void main(String[] args) throws Exception {
try{
Server server = new Server(8080);
WebSocketHandler wsHandler = new WebSocketHandler() {
#Override
public void configure(WebSocketServletFactory factory) {
factory.register(MyWebSocketHandler.class);
}
};
server.setHandler(wsHandler);
server.start();
server.join();
}catch(Exception e){
System.out.println("Error "+ e);
}
}
}
This my MyWebSocketHandler class
package com.websocet;
import java.io.IOException;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
public class MyWebSocketHandler {
#OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("Close: statusCode=" + statusCode + ", reason=" + reason);
}
#OnWebSocketError
public void onError(Throwable t) {
System.out.println("Error: " + t.getMessage());
}
#OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("Connect: " + session.getRemoteAddress().getAddress());
try {
session.getRemote().sendString("Hello Webbrowser");
} catch (IOException e) {
System.out.println("Error -----" + e);
e.printStackTrace();
}
}
#OnWebSocketMessage
public void onMessage(String message) {
System.out.println("Message: " + message);
}
}
This is my client part:
console.log("start index.js");
var ws = new WebSocket("ws://localhost:8080/");
ws.onopen = function() {
console.log("Opened!");
ws.send("Hello Server");
};
ws.onmessage = function (evt) {
console.log("Message: " + evt.data);
};
ws.onclose = function() {
console.log("connection Closed...");
};
ws.onerror = function(err) {
console.log("Error"+ err);
};
when I run the server part it works well.
2015-12-11 12:02:31.081:INFO:oejs.Server:main: jetty-9.0.5.v20130815
2015-12-11 12:02:31.141:INFO:oejs.ServerConnector:main: Started ServerConnector#470e2030{HTTP/1.1}{0.0.0.0:8080}
But after I run client part, the server throws below exception.
2015-12-11 12:02:42.055:WARN:oejs.HttpChannel:qtp769287236-18: /
org.eclipse.jetty.websocket.api.InvalidWebSocketException: com.websocet.MyWebSocketHandler does not implement org.eclipse.jetty.websocket.api.WebSocketListener or declare #WebSocket
at org.eclipse.jetty.websocket.common.events.EventDriverFactory.wrap(EventDriverFactory.java:385)
at org.eclipse.jetty.websocket.server.WebSocketServerFactory.acceptWebSocket(WebSocketServerFactory.java:177)
at org.eclipse.jetty.websocket.server.WebSocketHandler.handle(WebSocketHandler.java:90)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:445)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:268)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:601)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:532)
at java.lang.Thread.run(Thread.java:745)
I downloaded jetty-distribution-9.0.5.v20130815 and added it in to eclipse IDE.
I am new to web socket. So please help me to resolve this problem. My goal is getting data from my web browser and passing it into my JavaSE project. If anyone knows to do this please let me know.
I found the answer to my question. I had missed an annotation. It has to be corrected as #WebSocket
#WebSocket
public class MyWebSocketHandler {
......
}