Is there somehow that I can invoke Java running on a server from a web browser? I would like:
User navigates to URL in a browser
User fills in input boxes (text)
User presses submit button
Input fields are sent as parameters to java that is executing on the server
A new html page is displayed that was generated by the java running on the server.
What is the standard way to do this, or something similar to this.
I think with PHP this would be relatively simple. I think that you would just pass arguments after the URL like this: www.mysite.com/folder?arguments.
Yes, this is possible (and is extremely common). Two of the most common ways are Java Servlets (where responses are generated purely via Java code) and Java Server Pages (where server logic is intermingled within HTML, similar to ASP or PHP).
There are countless ways to serve HTML from Java but virtually all of them rely on java servlets and java server pages (JSPs) which are Java's specification for handling web requests.
The absolute bare minimum to get going:
Install Java EE SDK ensuring to also install Netbeans and Glassfish.
Launch Netbeans and create a "Java Web" / "Web Application" project
Enter a project name, e.g. MyWebApp
In the Server and Settings screen, you need to Add... your server so do so. Point to the file location of your Glassfish server and enter the admin name and password
Ignore the framework stuff and Finish
NetBeans will generate a sample app and you can click straightaway on Run Main Project. It will deploy your app to Glassfish and load http://localhost:8080/MyWebApp/ from your default browser
Important things to note:
A file called web.xml tells the host server some basics about your web app. This file can contain a lot of other stuff but the default is some boiler plate. The most interesting part says <welcome-file>index.jsp</welcome-file> which means when you load http://localhost:8080/MyWebApp/ it will default to load index.jsp.
The index.jsp is what gets loaded if you don't specify a page to the server. If you look at index.jsp it's just HTML with some JSP markup.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Creating new JSPs is as simple as writing HTML. Netbeans has a wizard to create a simple JSP.
You can embed chunks of Java into a .jsp easily and step in and out of Java / HTML with the <% %> notation such as
<%
for (int i = 0; i < 10; i++) {
%>
Hello <%=i%>
<% } %>
Glassfish is just one possible app server. As long as you write compliant code it should functional with only minimal or zero modifications on any other implementation of Java Servlet / JSP spec. e.g. Jetty, Tomcat, oc4j, JBoss, WebSphere etc.
This is just the tip of the iceberg. You can make things as simple or complex as you like.
Once you know the basics then it's up to you how deep you go. More advanced topics would be:
Taglibraries - these can remove a lot of java clutter and are considered more correct
Expressions - using expressions inside JSP pages to reduce the need for messy <%= notation
Custom servlets let you move model / business stuff into a Java class and leave the .jsp to just presentational
MVC web frameworks like Struts, Spring etc.
Security & filtering
It's a massive subject but it's fairly easy to do something quick and dirty.
As a followup to Mark Peters answer, you need a java web server like Tomcat or GlassFish in order to use servlets or jsps. There are a lot of great frameworks for Java that help you abstract away from the original servlet classes, but I'll let you look those up and decided if you even need them for something this simple.
If you want to pass arguments in a URL, then easier approach is Axis
You can display result with javascript on your page.
If you want to pass arguments in a URL, then easier approach is Axis
My school has an apache server that we are required to use. I was not allowed to install tomcat. I ended up invoking my server side Java using PHP. Not the most beautiful solution but it works.
Related
I try from a long time ago to launch Java applets in browser (they are simple games). For a long time it say out-of-date Java version (now have the latest version 8 update 45), even after I install the latest before 2 min. NVM, I hope I fixed it. Now it say a lot of different errors: runtime exception or AccessControlExeption for ex.
I am running this programs in Eclipse and I tried them, so they work. Maybe I have a problem with HTML code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="canvas-id" ></canvas>
</body>
<applet width="600" height="170" code="theLightRoute.class"></script>
</applet>
</html>
First: your HTML code is not valid, remove the </script> closing tag inside your <applet/> section. Even if some browsers can accept it, I don't think you can expect to have a valid result with an invalid tag definition.
Second: the <applet/> tag support can vary regarding the browser (see http://www.w3schools.com/tags/tag_applet.asp). You should try with <object/> instead (see http://www.w3schools.com/tags/tag_object.asp)
Third: you cannot expect anymore that any modern web browser will support a java applet, whatever the tag you use. Indeed, most of them have dropped or disabled by default the browser-side support of any java applet for security reasons. For example for Chrome 42, the java support is totally dropped: http://www.infoq.com/news/2015/04/chrome-42-npapi. For Firefox or safari it should be enabled manually https://support.mozilla.org/en-US/kb/how-allow-java-trusted-sites).
Actually, there is no good reason to create some java applet anymore, it's a totally deprecated and obsolete technology (https://softwareengineering.stackexchange.com/questions/154537/do-java-applets-have-any-place-on-the-web-today).
Try to learn HTML5 for game programming instead :-) Many courses exist and can help you, and many HTML5 game engine are available (http://html5gameengine.com/). And it is cross-platform, mobile included!
Have just finished programming my first Java Applet. How can I share this with my friends without them using eclipse on my computer?
I have 12 classes in eclipse. I have seen some examples of people using HTML to embed their applet in a website, but
A) I have only found examples with only one class.
B) I tried following this method: http://www.oxfordmathcenter.com/drupal7/node/37
but when I click on the html file, it just opens the html code in my browser, not the applet.
This is the HTML file that I made
<html>
<head>
<title>
World Cup Game
</title>
</head>
<body>
<h2>World Cup Game</h2>
<applet
codebase=“https://www.dropbox.com/s/lcojvh8tm2mukzn”
archive = “WorldCup.jar”
width = 800 height = 600>
</applet>
</body>
</html>
I don't mind whether I share it embedded on a web page or if I send them an executable jar file or whatever, but does anyone know how I can share my hard work!? Thanks :)
(Apparently executable jar file isn't an option with applets though...)
Of course it is an option:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>My Applet Page</html>
</head>
<body>
<applet code="ClassFile.class" archive="YourJar.jar" width="400px" height="400px">
Java is not installed on your machine or your browser does not allowed Java Applet to run<br /><br />Get the latest Java technology at http://www.java.com/
</applet>
</body>
</html>
But I would not use that. Servlets are much better idea. Applets are client side thing if you do something that do not have to be processed on back-end why not but I did not see any applets for couple of years...
If you dont see your applet then probably you have public static void main(String[] args) instead of public void init() that also could make you problems
The basic Problem about applets are that they need jvm oriented browsers to run.
due to this reason applets(java) failed. today servlets are considered. you would need eclipse or any jvm for your browser to run..
I know that we can call Java from JavaScript and vice-versa, but I'm wondering myself about when take that power and use it in a healthy way. I'm talking about real world applications, not "hello world".
As many developers usually I'm developing java and javascript but I not have the enough experience for know when mix those guys is a good idea.
Please if there is some developer who can share his knowlege about how has constructed real world applications using this mix would be great :).
Apologies, I failed to convey my doubt in a worthwhile way, so, Did you hear about Narshorm?, for instance you could call Javascript code from a Java Class, but I dont see a business case in which those capabilities increase the worth to my server side applications.
This is a nashorn hello world, in this application there is a Java Main which "eval" the content of a .js file calling the functions inside the .js file.
My mainly doubt is when this power would be really useful
In web application development (which is the usual scenario where Java and JavaScript interact):
there are 2 places where you can make the server and client side languages interact with each other:
At rendering time, this is, when generating the HTML output to the user.
At runtime, this is, when the HTML has been generated and it is at client side (e.g. browser client).
For the first case, let's say we have a Servlet that adds an attribute to the request and forward to a new (JSP) view. This is an example of the servlet:
#WebServlet("/hello")
public class HelloServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
// Prepare messages.
request.setAttribute("name", name);
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
Then in your view (hello.jsp file inside WEB-INF folder), you have a code like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Servlet Hello World</title>
<script>
function changeName(var newName) {
document.getElementById('divName').innerHtml = 'Hello ' + newName;
}
window.onload = function () {
changeName('${name}');
}
</script>
</head>
<body>
<div id="divName">
</div>
<form id="name" action="hello">
Change name to: <input type="text" name="name" />
<br />
<input type="text" value="Change the name" />
</form>
</body>
</html>
By using this approach, we can communicate Java generates variables (NEVER SCRIPTLETS) directly to JavaScript when rendering the view. So we can access to Java page, request, session and context attributes only when creating the HTML that is going to the client.
Note that if you want to re-execute this Java code, you should fire a new request to the server in order to execute the Java code. This is where ajax come handy.
Ajax lets you communicate with the server side asynchronously, the server will prepare a response for your request, and then in client side you will define how to use it. For this purpose, it is better to use a common format for the communication. The most preferred format nowadays is JSON. Ajax interactions to servlet is widely covered here: How to use Servlets and Ajax? (no need to reinvent the wheel in this post).
In standalone or mobile applications:
Java will run on the client machine. Note that here Java can execute JavaScript code through a JavaScript engine like Rhino or nashorn. This is useful when you have lot of functionalities already written in javascript (like an external library) and do not want to migrate all the code to Java. You can just use ScriptEngineManager and StringEngine classes to execute the code in JavaScript in your Java application. A real-world example of using JavaScript in a Java application is Pentaho Kettle, written in Java, that allows applying transformations to your code through JavaScript scripts.
More info on Nashorn:
Oracle Nashorn: A Next-Generation JavaScript Engine for the JVM
Javascript is a client-side scripting language. This is used to interact with what a user can see and do on a website (html) For instance, you can use javascript to make something happen when you click on a button, or hover over a menu item.
Java is a server-side language. This is compiled code which runs on a server and the user generally has no idea of what happens here. A good real world application of using server-side code (Java in your case) is for database queries and updates.
For example, if you have a web page that asks a user to register for an account, there might be a form with a text box for username and password. When the user clicks "register" this information is to be stored in the database.
In this, your javascript will have code that is executed when the button is pressed which captures this data. It then sends this to the server with an HTTP Post (ajax is often used to send this) The server gets this data and executes the Java code you write to insert this into the database.
A very simple website which does not need to store user data may not need any server side code at all, but in most real world scenarios, there is some server code working alongside your html and javascript
One common place for these technologies to be used together is AJAX. The server side web services might be written in Java and the client side Javascript calls web services.
It's worth pointing out that Java and Javascript are actually completely different languages. The web services could be written in any language.
I have already provided GWT's i18n feature for java, UI Binder and trying to provide i18n with pure, none-hosted in java HTML file.
After reading "Declarative Layout with UiBinder" I implement some code, but it didn't work:
<html xmlns:ui="urn:ui:com.google.gwt.uibinder">
<ui:with field='i18n' type='//.exampleConstants'/>
<head>
<title>Title of none-hosted HTML file and i18n part: <ui:text from='{i18n.title}'/></title>
</head>
<body>
...
</body>
</html>
The solution with id's (described on same page: https://developers.google.com/web-toolkit/doc/latest/tutorial/i18n/) which will be pick-upped by RootPanel, smth like:
RootPanel.get("appTitle").add(new Label(constants.stockWatcher()));
Didn't work too, because my HTML file isn't bundled with Java.
How to do i18n in HTML files?
Well, you'd have a Catch-22 here: the HTML file couldn't know which text to use until the JavaScript compiled out of your Java code is loaded, which is done by the page, so after it's loaded.
You have to use standard Java web app techniques to internationalize your HTML page, e.g. make it a JSP, and detect the preferred language out of the Accept-Languages request header. If you do that, then generate the appropriate <meta name="gwt:property" content="locale=XX"> so the GWT app bootstrap (the .nocache.js file) won't have to guess it too, which could result in the GWT app running in a different locale than the one the HTML was generated with.
I am doing a project in c++ where I need to embed a java applet/java program.( like we usually see on webpages). I was wondering what is the easiest way to do this. Right now, I am using Qt designer. Thanks.
If you use QWebPage in your application you can load a url that has the JApplet embedded.
Edit:
You may not have JRE installed on the target machine if it's not loading the applet. If you do something like below it should spit out a message if something goes wrong with Java. This is just an untested example to give you the basic idea of what I meant.
An example webpage:
<html>
<head>
<title>Java Applet</title>
</head>
<body>
<applet code="YourApplet.class" width=400 height=400>Java not supported or not installed</applet>
</body>
</html>
Save this as MyPageName.html
A simplistic example of using this in Qt:
// the QWebView has a QWebFrame and QWebPage to make it easy
QWebView* webView = new QWebView(parentWidget); // MainWindow or whatever as parent
webView->load(QUrl("MyPageName.html")); // local page or valid URL
webView->show();
Hope that helps a bit more
In version 4.8 of Qt, java applets are not supported.