How to access web service from a stand alone html file? - java

i'm new in a web service. i'm trying to make a simple web service REST on java for a simple login application.. here's my code:
Server side:
package com.testingws.webservices;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/login/{username}/{password}/{datetime}")
public class webServicesClass {
#GET // this method process GET request from client
#Produces("application/json") // sends JSON
public String getJson( #PathParam("username") String username, #PathParam("password") String password) { // empno represents the empno sent from client
if (username.equalsIgnoreCase("admin") && password.equalsIgnoreCase("admin")){
return "{'loginstatus':'success'}";
}
else{
return "{'loginstatus':'failed'}";
}
} // end of
}
Client side :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Client Login</title>
<script type="text/javascript">
function loginProcess(){
var tempUser = document.getElementById("loginUsername");
var tempPass = document.getElementById("loginPassword");
var dateTime = new Date();
var url = "http://localhost:8181/TestWSProject/authentication/login/" + tempUser.value + "/" + tempPass.value + "/" + dateTime.toUTCString();
var xmlhttp = new XMLHttpRequest(); //#slaks: i put it here
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if ( xmlhttp.status == 200) {
var det = eval( "(" + xmlhttp.responseText + ")");
//alert(det.loginstatus);
if(det.loginstatus=="success")
{
setCookie("login", "yes", 1);
window.location="main.html";
}
else
{
alert("incorrect username or password");
}
}
else
alert("Error ->" + xmlhttp.status + xmlhttp.responseText);
}
}
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var loginStatus=getCookie("login");
//alert(loginStatus);
if (loginStatus=="yes")
{
//alert("Masuk pengecekan")
window.location="main.html";
}
}
</script>
</head>
<body onload="checkCookie()">
<h2>LOGIN FORM</h2>
<BR>
Username : <input type="text" id="loginUsername"/>
<BR>
Password : <input type="password" id="loginPassword"/>
<BR>
<input type="button" value="Login" onclick="loginProcess()"/>
</body>
</html>
when i access my client from webContent url (http://localhost/TestWSProject/index.html) that service works perfectly, but if i access my client from stand alone HTML file (file:///D:/+Prog/webservice/TestWSProject/WebContent/index.html) it give me xmlHTTPStatus = 0 and that service is not works.. any solution for this problem?? really thanks..

Some browsers have security restrictions which restrict files from performing certain actions if they are being accessed directly from the file system.
This could be what is causing the error.

Related

Tomcat 9 and websocket. Got a 404 error. What is wrong in my code?

I'm t rying to make my the first simple client-servet application with web socket and tomcat 9 server. I found this example in the enternet. I had the next error:
(index):17 WebSocket connection to 'ws://localhost:8080/JavaWebSocket/ws' failed:
Error during WebSocket handshake: Unexpected response code: 404"
it's this line:
var webSocket = new WebSocket("ws://localhost:8080/JavaWebSocket/ws")"
I thought the initialisation should be
var webSocket = new WebSocket("ws://localhost:8080/[nameOfTheClassWithWebSocket]/ws");
But it doesn't work too :( I tried everything :( I can't solve this problem :(
Java code and Jsp file with project scheme are bellow.
Java code:
package socket;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/ws")
public class WebSocketServerExample {
#OnOpen
public void onOpen(){
System.out.println("Open Connection ...");
}
#OnClose
public void onClose(){
System.out.println("Close Connection ...");
}
#OnMessage
public String onMessage(String message){
System.out.println("Message from the client: " + message);
String echoMsg = "Echo from the server : " + message;
return echoMsg;
}
#OnError
public void onError(Throwable e){
e.printStackTrace();
}
}
jsp file:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</title>
</head>
<body>
<form>
<input id="message" type="text">
<input onclick="wsSendMessage();" value="Echo" type="button">
<input onclick="wsCloseConnection();" value="Disconnect" type="button">
</form>
<br>
<textarea id="echoText" rows="5" cols="30"></textarea>
<script type="text/javascript">
var webSocket = new WebSocket("ws://localhost:8080/JavaWebSocket/ws");
var echoText = document.getElementById("echoText");
echoText.value = "";
var message = document.getElementById("message");
webSocket.onopen = function(message){ wsOpen(message);};
webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ console.log(message);};
webSocket.onerror = function(message){ console.log(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Message sended to the server : " + message.value + "\n";
message.value = "";
}
function wsCloseConnection(){
webSocket.close();
}
function wsGetMessage(message){
echoText.value += "Message received from to the server : " + message.data + "\n";
}
function wsClose(message){
echoText.value += "Disconnect ... \n";
}
function wserror(message){
echoText.value += "Error ... \n";
}
</script>
</body>
</html>
Scheme of the Project
Your url will be
var webSocket = new WebSocket("ws://localhost:[port]/appcontext/ws")"

How to debug web service application in eclipse?

I am learning Java EE technologies. Is there a way I can use Eclipse debugger to step through the code and see how it works step by step? For instance, this is a simple html5 + restful service.
Is there any way I can debug from the index.html java script, and step through the code little by little in Eclipse? That would be the best way to study this stuff.
Thanks a lot.
/**
* A simple CDI service which is able to say hello to someone
*
* #author Pete Muir
*
*/
public class HelloService {
String createHelloMessage(String name) {
return "Hello " + name + "!";
}
}
#Path("/")
public class HelloWorld {
#Inject
HelloService helloService;
#POST
#Path("/json/{name}")
#Produces("application/json")
public String getHelloWorldJSON(#PathParam("name") String name) {
System.out.println("name: " + name);
return "{\"result\":\"" + helloService.createHelloMessage(name) + "\"}";
}
/** A simple rest service saying hello */
#POST
#Path("/xml/{name}")
#Produces("application/xml")
public String getHelloWorldXML(#PathParam("name") String name) {
System.out.println("name: " + name);
return "<xml><result>" + helloService.createHelloMessage(name) + "</result></xml>";
}
}
Then, the front end html 5 + java script.
<html>
<head>
<title>HTML5 + REST Hello World</title>
<link rel="stylesheet" href="css/styles.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
$( '#sayHello' ).click( function( event ) {
event.preventDefault();
var result = $( '#result' ),
name = $.trim( $( '#name' ).val() );
result.removeClass( 'invalid' );
if( !name || !name.length ) {
result.addClass( 'invalid' ).text( 'A name is required!' );
return;
}
//console.log("clicked: " + name);
$.ajax( 'hello/json/' + name, {
dataType:'json',
data:{},
type:'POST',
success:function ( data ) {
//console.log("success: " + data.result);
$( '#result' ).text( data.result );
}
})
.error( function() {
//console.log("error");
});
});
}); // (document).ready
</script>
</head>
<body>
HTML5 + REST Hello World<br>
<form name="theForm">
<fieldset>
<label for="name" id="name_label">Name</label>
<input name="name" id="name" type="text" required placeholder="Your Name"/>
<input type="submit" id="sayHello" value="Say Hello"/><span id="result"></span>
</fieldset>
</form>
Usually for any html/css/javascript code, I debug using the Chrome Browser's built in Dev Tool. You can also install plugins for Eclipse that will allow you to step through Javascript.
https://www.youtube.com/watch?v=_uzSw_fb7NQ
http://www.eclipse.org/webtools/jsdt/debug/
The Rhino Debugger has been around for many years.
As for stepping in through the Web Service, you can write test classes and/or set breakpoints in eclipse.
This tutorial will help.... http://wso2.com/library/tutorials/debug-your-axis2-web-service-3-steps-using-eclipse/

Error during WebSocket handshake

I am trying to follow the instructions given in this tutorial and create a sample application in Netbeans. I have reached till the testing part. When I run the application in chrome it says
WebSocket connection to
'ws://localhost:8080/WhiteboardApp/whiteboardendpoint' failed: Error
during WebSocket handshake: Unexpected response code: 404
index.html
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Collaborative Whiteboard App</h1>
<div id="output"></div>
<script type="text/javascript" src="websocket.js"></script>
</body>
</html>
websocket.js
var wsUri = "ws://" + document.location.host + document.location.pathname + "whiteboardendpoint";
var websocket = new WebSocket(wsUri);
websocket.onerror = function(evt) { onError(evt) };
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
// For testing purposes
var output = document.getElementById("output");
websocket.onopen = function(evt) { onOpen(evt) };
function writeToScreen(message) {
output.innerHTML += message + "<br>";
}
function onOpen(evt) {
writeToScreen("Connected to " + wsUri);
}
// End test functions
MyWhiteboard.java
package org.myapps.whiteboardapp;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/whiteboardendpoint ")
public class MyWhiteboard {
private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
#OnMessage
public String onMessage(String message) {
return null;
}
#OnOpen
public void onOpen (Session peer) {
peers.add(peer);
}
#OnClose
public void onClose (Session peer) {
peers.remove(peer);
}
}
Where have I gone wrong ? How can I solve this problem ?
You have an invalid server annotation
Fix this
#ServerEndpoint("/whiteboardendpoint ")
To
#ServerEndpoint("/whiteboardendpoint") /* removed space */
The way you have it defined currently, you could probably just change your javascript wsUri definition to ...
var wsUri = "ws://" + document.location.host + document.location.pathname +
"whiteboardendpoint%20";
var websocket = new WebSocket(wsUri);
and have it work. (just added a URI encoded space)

AJAX call to Jersey WebService doesn't work

I'm trying out AJAX for the first time. I'm using a Jersey Web Service as what gets called. But my call always executes the error part. Help! please
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Jquery Basic</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#submit1").click(function() {
alert("click");
var username = $("#textbox").val;
$("#para1").text(username);
$.ajax({
type: 'POST',
url: '/FirstProject/src/Resource/resource/welcome',
data: username,
success: function(){alert("Login Success!")},
error: function(){alert("Login Failure!")}
});
alert("ajax passed");
});
});
</script>
</head>
<body>
<a id="body1">JQuery Test Page</a><br>
<div id="heading"><a>Enter Your Details</a></div>
<div>
<div id="heading1"><a>UserName:</a></div>
<div><input id="textbox" type="text"/></div>
<button id="submit1">Submit</button>
</div>
<div><p id="para1"></p></div>
</body>
</html>
WebService is as follows
package Resource;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import POJO.passwordPojo;
import POJO.usernamePojo;
public class resource {
#POST
#Path("welcome")
public String welcomeFunction(#FormParam("username") String username)
{
setUserNameData(username);
return "success";
}
usernamePojo userName = new usernamePojo();
passwordPojo password = new passwordPojo();
public void setUserNameData(String userNameData)
{
userName.setUserName(userNameData.toString());
printuserName();
}
public void setpasswordData(String passwordData)
{
password.setPassword(passwordData.toString());
printPassword();
}
public void printuserName()
{
System.out.println("UserName:"+userName.getUserName());
}
public void printPassword()
{
System.out.println("Password"+password.getPassword());
}
}
Blast!! I know most of my question is code!! Bloody post it already!
Think data needs to be an array.
var usernameVal = $("#textbox").val;
$.ajax({
type: 'POST',
url: '/FirstProject/src/Resource/resource/welcome',
data: { username : usernameVal }
send data as json with index like {"username":username } in ajax data like
....,data: {"username":username },....

how to user javascript to call action

I have a login form in my jsp file that is referring to a javascript function using onclick function,
The javascript function is supposed to to call an action method to do the authorization process and return the results.
Result can be a message of error (user name is wrong) or (username or password is wrong) or a success message (return "SUCCESS") to get to new page,
any time that it calls the action the alert(xmlHttp.status) shows that it receives "undefined"
it is calling a correct action but its problem is on receiving the response.
how should I define the struts.xml? maybe the problem is caused by it.
<s:submit onclick="auth(this.form)" />
xmlhttp.open("get","Login.action?usrname="+usr+"&pass="+psw,false);
xmlhttp.send();
You need to do like this (Struts2, JSON, Ajax)
struts.xml
<package name="default" extends="json-default">
<action name="ValidateUserName" class="com.controller.JSONUserAction">
<result type="json"></result>
</action>
</package>
Controller Class Code JSONUserAction.java (in your case Login.java)
package com.controller;
import com.opensymphony.xwork2.ActionSupport;
public class JSONUserAction extends ActionSupport {
private String username;
private String result;
// all struts logic here
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String execute() {
if(username.equalsIgnoreCase("admin")) {
result = "VALID";
} else {
result = "INVALID";
}
System.out.println("username : " + username + "======== result :" + result);
return ActionSupport.SUCCESS;
}
}
login.jsp code
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<script type="text/javascript">
var http;
if(window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
function AuthenticateUser() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
http.open("POST", "ValidateUserName.action", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.onreadystatechange = ValidUser;
http.send("username="+username +"&password="+password);
}
function ValidUser() {
if(http.readyState == 4 && http.status == 200) {
var jsonOP = eval ("(" + http.responseText + ")");
var result = jsonOP.result;
document.getElementById("message").innerHTML = result;
if(result == "VALID") {
//redirect to welcome page
}
}
}
</script>
</head>
<body>
<s:form action="Welcome">
<div id="message"></div>
<s:textfield name="username" label="Username" id="username" />
<s:password name="password" label="Password" id="password"/>
<s:submit id="login" onClick="AuthenticateUser();"/>
</s:form>
</body>
</html>

Categories