AJAX call to Jersey WebService doesn't work - java

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 },....

Related

Cannot call Play Framework static method from view

I have server and I should make request on button pressed also I have to call this method and when it is works I should parse json but my doesn't see controller method only main method is available
How to call
<input type="submit" onclick="#routes.Login.resp()" value="LOGIN" >
because it is not worrking Cannot resolve symbol
GET /login controllers.Login.main()
My controller:
package controllers;
import play.libs.F;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.Result;
public class Login extends Controller {
public static Result main() {
return ok(views.html.login.render());
}
public static F.Promise<Result> resp() {
String feedUrl="http://validate.jsontest.com/?json=%7B%22key%22:%22value%22%7D";
final F.Promise<Result> resultPromise = WS.url(feedUrl).get().flatMap(
new F.Function<WS.Response, F.Promise<Result>>() {
public F.Promise<Result> apply(WS.Response response) {
return WS.url(response.asJson().findPath("empty").asText()).get().map(
new F.Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("size" + response.asJson().findPath("count").asInt());
}
}
);
}
}
);
return resultPromise;
}
}
view:
<!--
Author: W3layouts
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/stylelogin.css")">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfonts-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:600italic,400,300,600,700' rel='stylesheet' type='text/css'>
<!--//webfonts-->
</head>
<body>
<!-----start-main---->
<div class="main">
<div class="login-form">
<h1>Member Login</h1>
<div class="head">
<img src="#routes.Assets.at("images/user.png")" alt=""/>
</div>
<form>
<input type="text" class="text" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'USERNAME';}" >
<input type="password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}">
<div class="submit">
<input type="submit" onclick="#routes.Login.main()" value="LOGIN" >
</div>
</form>
</div>
<!--//End-login-form-->
<!-----start-copyright---->
<!-----//end-copyright---->
</div>
<!-----//end-main---->
</body>
</html>
I am not sure if I also parse json properly,how to make proper GET,POST requests and parse it
As far as I know with the onclick attribute you always call a function in your JavaScript. If you want to specify an URL you need to put it into your form tag with an action attribute like <form action="#routes.Login.main()">.
The default for the HTML form tag is to send a GET. If you want to send a POST you have to specify it via an additional method="post" like <form action="#routes.Login.main()" method="post">. But then you have to change your routing too: POST /login controllers.Login.main(). If you want to post login data I'd strongly recommend to use POST because with GET your data including the password turns up in the query string of your URL.
Additionally your #routes.Login.main() method just returns the login view return ok(views.html.login.render());. Instead it should evaluate the form data you are sending.

$.getJSON not retrieving data from Struts 2 Action Class to JSP Page

I want to retrieve fields from Struts2 Action class in my jsp page.
My JavaScript code of JSP is able to trigger it's action class, but not showing set field value from action class to jsp page on calling the Id of supposed element through JavaScript.
My console is showing everything fine. I have gone through various examples & don't know why I run into same problem all time. I'm not able to figure out the exact problem.
Here is my code:
In new.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<!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>getJSON example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<s:select label="Category" id="category" name="category" list="{'Select','Animal','Bird'}"></s:select><br/>
<s:textfield label="Field1" id="field1" name="field1" ></s:textfield>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#category',function(){
var JScategory=$(this).val();
$.getJSON("getfield",
{category:JScategory},
function(data){
$('#field1').html(field);
});
}
);
});
</script>
</body>
</html>
In struts.xml:
<package name="jsonpack" namespace="/" extends="json-default">
<action name="getfield" class="com.mobile.TestDropDown">
<result type="json" name="success"></result>
</action>
</package>
Action Class:
package com.mobile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.db.AdDAO;
import com.opensymphony.xwork2.ActionSupport;
public class TestDropDown extends ActionSupport{
private String category;
private String field;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
#Override
public String execute() throws Exception {
System.out.println("cat:"+category);
if(category.equals("Animal")){
field="Tiger";
}else if(category.equals("Bird")){
field="Eagle";
}
return SUCCESS;
}
}
I don't see where you are initializing your field JS variable in the line:
$('#field1').html(field);
What is the value of field here?
The value from the category you should get as
var JScategory=$("#category").val();
and use
$.getJSON("<s:url namespace='/' action='getfield'/>", { category: JScategory })
.done(function(json) {
console.log( "JSON Data: " + json );
$("#field1").val(json.field);
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
Every thing is ok just Use this
$('#field1').val(data.field);
Instead of
$('#field1').html(field);
Because the json returned with url
http://localhost:8083/yourProjectName/getfield?category=Bird is
{"category":"Bird","field":"Eagle"}
So to get Eagle in textbox we access variable data.field
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#category',function(){
var JScategory=$(this).val();
$.getJSON("getfield",
{category:JScategory},
function(data){
$('#field1').val(data.field);
});
}
);
});
</script>
Also let us know if you get any error or it is not working.
it return json Object,so,you should do following steps,it works fine.
json Object contains key and value,so to need to iterate the your data.then set into your field.
function(data) {
//it is Json Data
$.each(data,function(key,value){
$('#field1').val(value);
});
});
Are you missing your action suffix ? The default is .action
Try
$.getJSON("getfield.action",
{category:JScategory},
function(data){
$('#field1').html(field);
});

File browse on Android App

I want to create an Android app. There will be a form which will allow users to choose files using html tag. There will also be a submit button on the form, onclick of which the chosen file should get copied from the Android device to a location on the server.
Right now the form is on an html page and I have been using phonegap for the development.
As of now, I have created a plugin which reads the file from sdcard folder and using a jsch library I am uploading the files on the sftp server.
While researching, I found that many people are using the following method:
The form details are posted to the server and using a php script the file content are read using $_FILES (but I do not want to follow this approach)
I need a way, so that when the user chooses the file using browse option this file name will be picked up when the form is posted.
for e.g below is the code for MainActivity.java file
package com.example.filepicker;
import java.io.IOException;
import java.net.URI;
import org.apache.cordova.DroidGap;
import org.apache.http.client.methods.HttpGet;
import android.util.Log;
import android.view.Display;
import android.webkit.WebSettings.RenderPriority;
import android.view.WindowManager;
import android.content.Context;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
public class MainActivity extends /* Activity */DroidGap {
private Object request;
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
appView.addJavascriptInterface(this, "MainActivity");
super.loadUrl("file:///android_asset/www/index.html");
}
public void onFormSubmit() {
//this method is to be invoked when the user clicks form submit button
Log.i("Custom Function Called", "Custom Function Called");
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>XXXX | INDEX</title>
<script type="text/javascript" charset="utf-8" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/toast.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.magnific-popup.min.js"></script>
<script type="text/javascript" src="js/jquery.mCustomScrollbar.concat.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/FileUploadPlugin.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css" >
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/media-query.css" />
<link rel="stylesheet" type="text/css" href="css/magnific-popup.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mCustomScrollbar.css" />
<script type="text/javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
alert('device is ready');
var fileupload1 = new FileUploadPlugin();
var ipaddress = "xxxxxxx";
var userId ="xxx";
var password = "xxx";
/*cordova.exec(onFileSystemSuccess, fail, "FileUploadPlugin", "echo",
[ipaddress,userId,password]); */
/*cordova.exec(onFileSystemSuccess, fail, "FileUploadPlugin", "display",
["DEF"]); */
/* callNewActivity();*/
alert('after execution is called');
}
function onFileSystemSuccess(result) {
alert('on success'+result);
// alert('msg'+msg);
// alert('on status'+status);
console.log('this is success');
/* console.log(result); */
/* console.log(fileSystem.name);
console.log(fileSystem.root.name);*/
}
function fail(error) {
alert('on failure'+error);
console.log('this is error');
alert('err code'+evt.target.error.code);
/* console.log(evt.target.error.code);
*/
}
function onFormSubmit() {
window.MainActivity.onFormSubmit();
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>Attach File</h1>
</div>
<div data-role="content">
<form id="file-attachment-form" action="http://PutYourServerURL">
<div data-role="fieldcontain">
<label for="data">Put some text:</label>
<input name="data" type="text" id="data"/>
</div>
<div data-role="fieldcontain">
<label for="attachment">Attachment:</label>
<input type="file" name="attachment" id="attachment"/>
</div>
<input type="submit" value="Submit"/>
</form>
</div>
<script>
$('#file-attachment-form').submit(function () {
formData = new FormData($(this)[0]);
alert('new '+formData);
/*console.log(formData);*/
/* $.ajax({
type:'POST',
url:$('#file-attachment-form').attr('action'),
data:formData,
contentType: false,
processData: false,
error:function (jqXHR, textStatus, errorThrown) {
alert('Failed to upload file')
},
success:function () {
alert('File uploaded')
}
})*/
/*alert('formData = '+formData);*/
onFormSubmit();
});
</script>
</div>
</body>
</html>
e.g MainActivity.java file will have a function called "onFormSubmit" this function should be able to read the files parameter.
I would like to know if this is a possible method. If not then any pointer/suggestions will be helpful.
Thanks in Advance.

Pass string from .JSP form to .Java class and execute main argument

Here is my index.jsp
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="ContentLoader" class="com.content.ContentLoader" scope="session"/>
<jsp:setProperty name="ContentLoader" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Content Loader</title>
</head>
<body>
<h1>Content API: Loader</h1>
<a>Select a CSV file from your computer.<br>
Enter the API key and secret for your account<br>
Click submit when you are ready to load the products!! <br>
</a>
<br>
<form action="index.jsp" method="GET">
API Key: <input type="text" name="api_key">
<br>
API Secret: <input type="text" name="api_secret" />
<br>
Choose CSV File: <input type="file" name="csv_file" />
<br>
<input type="submit" value="Submit To Content API" />
</form>
<br>
This is feedback from the program<br>
**strong text**
You entered<BR>
Name: <%= ContentLoader.getApi_key() %><BR>
Email: <%= ContentLoader.getApi_secret() %><BR>
Age: <%= ContentLoader.getCsv_file() %><BR>
</body>
</html>
When I hit the submit button, I want to pass the 3 strings to the Java application.
(key, secret, and the contents of my csv)
Right now I get "The requested resource is not available" error (HTTP Status 404)
Here is my ContentLoader.java
package com.content;
public class ContentLoader {
private String api_key = "testKey2";
private String api_secret= "testSecret";
private String csv_file = "testFileString";
public ContentLoader() {
// TODO Auto-generated constructor stub
}
public void setApi_key(String api_key) {
this.api_key = api_key;
}
public void setApi_secret(String api_secret) {
this.api_secret = api_secret;
}
public void setCsv_file(String csv_file) {
this.csv_file = csv_file;
}
public String getApi_key() {
return api_key;
}
public String getApi_secret() {
return api_secret;
}
public String getCsv_file() {
return csv_file;
}
}
The ContentLoader.java above is supposed to send and receive strings from the JSP form. When the submit button is hit, I need the 3 strings to pass to Application.java, and the main argument needs to be executed. Right now this is not happening, and I don't understand why. Thanks!!!!
This is my Application.java
import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Application implements ServletContextListener{
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Tomcat just started");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("Tomcat just stopped");
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("hi!! Your program is executing");
/**
//Null Credentials
String apiKey = "000";
String apiSecret = "000";
}
}
Web applications doesn't work like that, and Servlet don't need a main method to work, actually it doesn't know how to use it, instead of that you can use http request from your java application (main methode) to call a jsp file that returns 3 paramteres (in xml format or json) and you can pick those parametres and use them in your application as you want.

play framework 2.0 json - receiving null JsonNode object

I'm getting a null JsonNode object in the following code. There's something wrong with the client javascript. If I run a curl command with a POST request, I get the correct response. If I run the same in the below mentioned Javascript - I get a null for the JsonNode object. Here's the code
Application.java
package controllers;
import org.codehaus.jackson.JsonNode;
import play.Routes;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
public class Application extends Controller {
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result receiveData() {
response().setContentType("application/json");
JsonNode json = request().body().asJson();
if(json == null) {
return badRequest("Expecting Json data");
} else {
String name = json.findPath("name").getTextValue();
if(name == null) {
return badRequest("Missing parameter [name]");
} else {
return ok("Hello " + name);
}
}
}
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("jsRoutes",
// Routes
controllers.routes.javascript.Application.receiveData()
)
);
}
}
Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
POST /receiveData controllers.Application.receiveData()
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
main.scala.html
#(title: String)(content: Html)
#import helper._
#import controllers.routes.javascript._
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/bootstrap.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script type="text/javascript" src="#routes.Application.javascriptRoutes"></script>
<script src="#routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/bootstrap.js")" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/message.js")" type="text/javascript"></script>
</head>
<body>
<div class="container">
<div class = "row">
<div class = "span12">
<input type = "text" id = "inputValue" value="getData"></input>
<button class = "approveButton btn btn-primary">Approve </button>
</div>
</div>
</div>
</body>
</html>
message.js
$(document).ready(function(){
$('.approveButton'). click(function(){
var value = $('#inputValue').val();
var jsonToSend = {};
jsonToSend.name = value;
var outputData = JSON.stringify(jsonToSend);
jsRoutes.controllers.Application.receiveData().ajax({
data:outputData,
contentType:'application/json',
success: function(data) {
console.log(data);
},
error: function() {
alert("Error!");
}
});
});
});
Here's the output of the curl command:
curl --header "Content-type:application/json" --request POST --data '{"name":"abx"}' http://localhost:9000/receiveData
Hello abx
Can someone please help in identifying whats wrong in the javascript file.
The expected result of the ajax call is a json object. In this case if you want to response with a plain text add dataType: 'text' to the request:
jsRoutes.controllers.Application.receiveData().ajax({
data:outputData,
dataType: 'text',
contentType:'application/json',
success: function(data) {
console.log(data);
},
error: function() {
alert("Error!");
}
});
Maybe a stupid question but what does you make think, that ajax call will be POST instead of GET ? Have you tried replacing POST by GET ?

Categories