I'm having an application which takes input from a popup dialog.When a user enters a text in the text field of a popup dialog.I need to pass that text to another method ina different class.How can I achieve this. My code is shown below.
viewRoles.jsp
<%#page contentType="text/html" import="com.model.Data" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="bootstrap.css" type="text/css" rel="stylesheet">
<script>
window.onload=function()
{
var el=document.getElementById('btnAddNewRole');
el.onclick=function()
{
var my_text=prompt('Enter text here');
if(my_text){
$.ajax({
url: '/com.model/Data/addRole('+my_text+')',
success: function(my_text){
alert("Inserted")
}, error: function(){
// when got error
}
});
}
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>View Roles</title>
</head>
<body><br><br>
<button id="btnAddNewRole" class="btn btn-info">Add New Role</button>
</body>
</html>
Data.java in com.model package
package com.model;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.hibernate.Session;
#ManagedBean
#SessionScoped
public class Data {
private Roles r;
private HibernateUtil helper;
private Session session;
public void addRole(String roleTitle){
r=new Roles(roleTitle);
session = helper.getSessionFactory().openSession();
session.beginTransaction();
session.save(r);
session.getTransaction().commit();
session.close();
}
Related
HI I am trying the example given in spring.io getting started guide.
it doesn't show any error but I am not getting HTML view
when I open the link http://localhost:8070/testJson in my browser all it shows is a JSON output like this
{"id":1,"content":"Hello World !"}
But I want it to show a proper HTML view, and I can not use #Controller here, I want to show HTML using Jquery javascript, How can I do that?
here is my controller method
#RestController
public class MyRestController {
private final Long counter = 1l;
#GetMapping("/testJson")
public TestJsonDto getTestJson(){
TestJsonDto testJsonDto=new TestJsonDto(counter,
"Hello World !");
return testJsonDto;
}
}
This is my Data class
public class TestJsonDto {
private Long id;
private String content;
public TestJsonDto(Long id, String content) {
this.id = id;
this.content = content;
}
public TestJsonDto() {
}
/*
GETTERS AND SETTERS WILL GO HERE
*/
And Below is my application class
#SpringBootApplication
#EnableJpaRepositories
public class MyjarApplication {
public static void main(String[] args) {
SpringApplication.run(MyjarApplication .class, args);
}
}
My Html file is
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="/my.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
and finally, this is my javascript
$(document).ready(function() {
$.ajax({
url: "http://localhost:8070/testJson"
}).then(function(testJsonDto) {
$('.greeting-id').append(testJsonDto.id);
$('.greeting-content').append(testJsonDto.content);
});
});
my application.properties is here
server.port=8070
Location of my.js is under src/main/resources/static/my.js
If you want to add a front end that can interact with your API you can structure your app like this:
This code setup your application, including static resources, for instance your resource/static/index.html will be render for root path localhost:8090 unless you wire this path in any controller(make sure root is not implicitly/explicitly user in any other #Controller or annotation).
#SpringBootApplication
#EnableJpaRepositories
public class MyjarApplication {
public static void main(String[] args) {
SpringApplication.run(MyjarApplication .class, args);
}
}
So, a simple way to render the HMTL you want is by putting that HTML at resource/static/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="/my.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
and js should be placed at resource/static/my.js:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8070/testJson"
}).then(function(testJsonDto) {
$('.greeting-id').append(testJsonDto.id);
$('.greeting-content').append(testJsonDto.content);
});
});
In your rest controller, path /testJson will be attended by getTestJson():
#RestController
public class MyRestController {
private final Long counter = 1l;
#GetMapping("/testJson")
public TestJsonDto getTestJson(){
TestJsonDto testJsonDto=new TestJsonDto(counter,
"Hello World !");
return testJsonDto;
}
}
So you access localhost:8090 to get the front-end, and thru javascript you access localhost:8090/testJson to get your API.
I'm working on the radio site and for streaming, the Jazler RadioStar 2 program is used which allows constant updating of files that transmit the information which song is currently streaming..
check image
I am specifically interested in how to transfer the title of the song and the name of the author to my homepage..
customexportfile.htm code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Trenutno Slusate!</title>
</head>
<body>
<p>TNowOnAir: <strong>Cher | Believe</strong>
</body>
</html>
or via xml file, NowOnAir.xml
<Schedule System="Jazler">
<Event status="happening" startTime="09:15:30" eventType="song">
<Announcement Display=""/>
<Song title="Believe">
<Artist name="Cher"> </Artist>
<Jazler ID="6379"/>
<PlayLister ID=""/>
<Media runTime="03:34"/>
<Expire Time="09:19:03"/>
</Song>
</Event>
</Schedule>
These files are automatically updated when the song on the stream changes.
Make a text file to the same directory as NowOnAir.xml!
Name it like filename.html
Type the following inside:
<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
</head>
<body onload="refresh()">
<p>Now playing: <span id="art"></span>|<span id="title"></span>
<script>
var interval,time
function refresh(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("art").innerHTML = this.responseXML.getElementByTagName("ARTIST")[0].getAttribute("name");
document.getElementById("title").innerHTML = this.responseXML.getElementByTagName("SONG")[0].getAttribute("title");
time=this.responseXML.getElementByTagName("EXPIRE")[0].getAttribute("Time").split(":")
interval=setInterval(checkTime,1000)
}
};
xhttp.open("GET", "NowOnAir.xml", true);
xhttp.send();
}
}
function checkTime(){
var date=new Date()
if(date.getSeconds()==time[2]&&date.getMinutes()==time[1]&&date.getHours()==time[0]){
clearInterval(interval)
refresh()
}
}
</script>
</body>
</html>
Then try it (you will find it like this: http://serveraddress/path/filename.html)
I hope that this will help you!
Hesitantly, you can try out this code...
N.B.
There are a great many reasons why this might not work (from the outset, or later).
You should certainly test this out in an environment where it will not upset anyone if it doesn't work.
The solution below involves checking for a new song and title every 5 seconds using the Javascript setInterval method. That could well be a wholly inappropriate solution because it will run indefinitely every 5 seconds. Without more information, it's impossible to answer this for you really.
This code is untested.
Anyway, here's a punt at solving this problem:
HTML (homepage):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Trenutno Slusate!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p>NowOnAir:
<strong>
<span id="artistName">Cher</span> |
<span id="songTitle">Believe</span>
</strong>
</p>
<script>
function getNowPlaying() {
const src = "NowOnAir.xml";
$.ajax({
type: 'GET',
url: src,
dataType: xml,
success: function(xml) {
//parse XML
const xmlDoc = $.parseXML( xml );
const $doc = $( xmlDoc );
const $artist = $doc.find( "Artist" ).attr("name").text();
const $song = $doc.find( "Song" ).attr("title").text();
//update homepage
$("#artistName").text($artist);
$("#songTitle").text($song);
},
error: function(e) {
console.log(e);
}
})
}
setInterval( function() {
getNowPlaying();
}, 5000);
</script>
</body>
</html>
If it doesn't work, feel free to comment and I'll try to help.
I'm using cordova/phonegap to make a Android app and trying to call JavaScript funtion from android/native
My main acitvity:-
public class MainActivity extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
loadUrl(Url);
// TODO call javascripte from here
}
}
My index.html page
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8">
function myFun(){
alert("call from the ANDROID");
}
</script>
</head>
<body >
</body>
</html>
I want call JavaScript function from phonegap.
try this code
webView.loadUrl("javascript:myFun()");
im trying to do a button that show a alert in the android phone, but nothing happens, the buttons is propertly rendered(i have jquery, jquery mobile, js in assets folder)
...
getWindow().requestFeature(Window.FEATURE_PROGRESS);
WebView webview = new WebView(this);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
setContentView(webview);
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("file:///android_asset/index.html");
webview.addJavascriptInterface(this,"alerts");
setContentView(webview);
}
public void showAlert() {
AlertDialog alert = new AlertDialog();
AlertDialog.Builder builder = new AlertDialog.Builder(main);
builder.setTitle("Test WORKED?");
builder.setMessage("Yes if you see -_-");
alert = builder.create();
alert.show();
}
the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="file:///android_asset/jquery.mobile-1.4.2.min.css" />
<script src="file:///android_asset/jquery-2.1.0.min.js"></script>
<script src="file:///android_asset/jquery.mobile-1.4.2.min.js"></script>
</head>
<body>
<button type="submit" onclick="javascript:showalert();">ShowAlert</button>
<script>
$(document).ready(function showalert() {
alerts.showAlert();
)};
</script>
</body>
</html>
and other question is: how do i map this kind of jquery button to do something:
<button class="ui-btn ui-btn-inline">Button</button>
your code has script error.
<script>
$(document).ready(function showalert() {
alerts.showAlert();
)}; //<----- replace please .. });
</script>
and then
add annotation ?
#JavascriptInterface
public void showAlert() {
AlertDialog alert = new AlertDialog();
AlertDialog.Builder builder = new AlertDialog.Builder(main);
builder.setTitle("Test WORKED?");
builder.setMessage("Yes if you see -_-");
alert = builder.create();
alert.show();
}
I want to create a button in html and make a call from that button from android through javascript. I have written the following code , which is not working :
I am beginner for android.
public class MainActivity extends Activity {
private static final String PIC_WIDTH = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new JsInterface(), "android");
myWebView.loadUrl("file:///android_asset/www/index.html");
}
public class JsInterface{
public void makeCall()
{
Log.i("Myactivity","inside android makecall");
// Here call any of the public activity methods....
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9611396958"));
startActivity(callIntent);
}
}
}
in javascript :
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body class="bgClass" id="body" ontouchstart="">
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script src="js/myScript.js"></script>
<button id="makeCall" >CALL</button>
<script>
$("#makeCall").click(function(){
console.log("inside click javascript");
console.log(window.android);
android.makeCall();
});
</script>
</body>
</html>
any help??
Make sure your $("#makeCall") method is responding in html.
Then make below changes.It will work.
public class JsInterface{
#JavascriptInterface
public void makeCall()
{
Log.i("Myactivity","inside android makecall");
// Here call any of the public activity methods....
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9611396958"));
startActivity(callIntent);
}
}
This annotation allows exposing methods to JavaScript.
I am answering my own question so that it can help others .:)
Finally solved it :
myWebView.setWebViewClient(new MyAppWebViewClient()); it was missing so javascript was not working . And i must add #JavascriptInterface as Hardik Trivedi suggested above.
It is working fine now.
simply adding webView.getSettings().setJavaScriptEnabled(true); worked for me.
must add #JavascriptInterface too.