Execute jdbc applet in browser - java

import java.sql.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="A0" width=250 height=200>
</applet>
*/
public class A0 extends Applet implements ActionListener,ItemListener
{
String msg="";
Button view,delete,create,edit,reapp,exit;
TextField M_head;
int x,i,ans=0,flag;
public void init()
{
setLayout(new FlowLayout(FlowLayout.CENTER,50,3));
view = new Button("view");
delete = new Button("delete");
create = new Button("create");
edit = new Button("edit");
reapp = new Button("reapp");
exit= new Button("exit");
M_head = new TextField(15);
add(view);
add(delete);
add(create);
System.out.println("vikram");
add(edit);
add(reapp);
add(exit);
System.out.println("phaneendra");
add(M_head);
view.addActionListener(this);
delete.addActionListener(this);
create.addActionListener(this);
edit.addActionListener(this);
reapp.addActionListener(this);
exit.addActionListener(this);
M_head.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("view"))
{msg ="1";}
if(str.equals("delete"))
{msg ="2";}
if(str.equals("create"))
{msg ="3";}
if(str.equals("edit"))
{msg ="4";}
if(str.equals("reapp"))
{msg ="5";}
if(str.equals("exit"))
{msg ="6";}
if(msg=="3")
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//String filename = "E:/vikram/conn/new/db/north.mdb";
String filename = "./db/north.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
//String url ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\cheminDeMaBaseEtNomdeLaBdd";
database+=filename.trim();
String head = M_head.getText();
String head1 = head.trim();
Connection con = DriverManager.getConnection(database,"","");
Statement doo = con.createStatement();
//String vi ="create table head1 (Reapporder integer, Amount integer)";
String vi="insert into head1 values(1,2);";
boolean i=false;
i=doo.execute(vi);
if(i)
M_head.setText("Failed to insert");
else
M_head.setText("record inserted");
}
catch(Exception err)
{
System.out.println("Error :"+err);
}
}
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,70,200); //No use
g.drawString("ANSWER=",6,200); // No use
}
}
This is A0.txt
grant {
permission java.lang.RuntimePermission
"accessClassInPackage.sun.jdbc.odbc";
permission java.util.PropertyPermission
"file.encoding", "read";
};
A0.html file
<html>
<head>
</head>
<body>
<applet code=A0 width=250 height=200></applet>
</body>
</html>
This code is executed in Appletviewer command, but not in any browser

As commented by others, you really don't want to do this.
Just create a webservice in the server side (which can be a plain vanilla servlet) and make use of java.net.URLConnection in the applet.
Basic Servlet example:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action"); // Or request.getPathInfo() whatever you want.
String result = someDAO.doAction(action);
response.getWriter().write(result);
}
Basic Applet example:
URL url = new URL("http://example.com/databaseservlet?action=someaction");
URLConnection connection = url.openConnection();
InputStream result = connection.getInputStream(); // Important. This actually fires the request!
Be careful with SQL injections however. Do in no way pass raw SQL queries as request parameters or pathinfo and use PreparedStatement all the time in the DAO code.
As response data format you can use a plain vanilla String (as given in example) or a XML string or a JSON string or maybe even a fullworthy Java object with a little help of Serialization.

You can't do JDBC on an Applet for security reasons.
You must write an Enterprise Application (in Java, .NET, Python, PHP) and deploy it to an application server. In that application you can publish some WebServices so your Applet can finally access your database.
Something like this:
APPLET <-> APPLICATION SERVER (HTTP communication) <-> BACKEND (database)
Here is a Web Site explaining some security related Applet stuff.

Related

Server Sent event code not working on jelastic

I am learning Server Sent events in java and for that I am using a simple example. I am using Windows 7, Java 1.7, Tomcat 7, Eclipse Indigo. I have created a servlet (SseServer.java), the code for this servlet is as follows:
package sse;
import java.io.IOException; <br/>
import java.io.PrintWriter;<br/>
import java.util.Date;<br/>
import javax.servlet.ServletException;<br/>
import javax.servlet.annotation.WebServlet;<br/>
import javax.servlet.http.HttpServlet;<br/>
import javax.servlet.http.HttpServletRequest;<br/>
import javax.servlet.http.HttpServletResponse;<br/>
#WebServlet("/SseServer")<br/>
public class SseServer extends HttpServlet {<br/>
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Besides "text/event-stream;", Chrome also needs charset, otherwise
// does not work
// "text/event-stream;charset=UTF-8"
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
PrintWriter out = response.getWriter();
while (true) {
out.print("id: " + "ServerTime" + "\n");
out.print("data: " + new Date().toLocaleString() + "\n\n");
out.flush();
// out.close(); //Do not close the writer!
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
And I am displaying the results in an html, SSE.html, the code for this is as shown below:
<!DOCTYPE html>
<html>
<body>
<h1>Current Server Time : </h1>
<div id="ServerTime"></div>
<script>
if (typeof (EventSource) !== "undefined") {
var source = new EventSource("http://localhost:8080/SSE/SseServer");
// http://eastern1.j.layershift.co.uk
//var source = new EventSource("http://eastern1.j.layershift.co.uk/SSE/SseServer");
source.onmessage = function(event) {
document.getElementById("ServerTime").innerHTML += event.data
+ "<br><br>";
};
} else {
document.getElementById("ServerTime").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
When I run this code locally after every one second I am able to see the current time. I have also checked it on several browsers like chrome, firefox etc.
Since this code is working fine I decided to deploy this on cloud so I chose Jelastic.com. I created a war file and deployed it on Jelastic and tried running my sample application. But when I run the application from cloud, I can only see
Current Server Time :
I do not see the time. Can someone please tell me why this is happening? Is there something I need to change in my code? If yes then can someone please advice what it should be? Or should I change some other file/settings in eclipse while creating a war file?
Any help is much appreciated.
You had used absolute link, It's a bad practice. Try to use relative link.
Your mistake was that link not corresponding to path on server
var source = new EventSource("/SseServer");

Create a connection to SQL Server DB inside Servlet request Thows "java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver"

Create a connection to SQL from a Java file with main() class defined works fine but calling the method inside a doPost() in Java Servlet throwing Error as
java.lang.ClassNotFoundException:com.microsoft.sqlserver.jdbc.SQLServerDriver
Working Code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connect{
public static void main(String[] args) throws Exception
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost;databaseName=UserDB";
Connection con = DriverManager.getConnection(url,"sa","XXXXXXX");
String query =" SELECT * FROM Login";
Statement myStatement = null;
myStatement = con.createStatement();
ResultSet result = myStatement.executeQuery(query);
while(result.next()){
System.out.println("User name = " + result.getString("userID"));
System.out.println("User password = " + result.getString("userPassword"));
}
}
}
Now Working Code inside Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName= request.getParameter("username");
String password= request.getParameter("password");
try {
if( **new DbQuery().isValidLogin(userName, password)**)
{
response.getWriter().println("Welcome " +userName);
}
else{
response.getWriter().println("Please Enter a valid User name and Password");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In the above code new DbQuery().isValidLogin(userName, password) creates a DB connection and the Class used as
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
On hitting the above line ........ ERROR
please help.
You need to put sqljdbc jar in your application server. For example if you are using tomcat server, go to the directory where you have installed the tomcat, open the LIB directory and make sure you have sqljdbc jar exists over there.
I got the same error while deploying the similar application in Tomcat Server. Put the relevant jdbc jar in the lib folder of Tomcat. It should work fine.

HTTP Callback in Java

I'm trying to write some code to handle the process of an HTTP callback in Java.
I have very little knowledge of Java and was hopping you could lend me a hand or point me in the right way.
I want to call the script from a page that will listen for a POST from other machine with some parameters and their values.
I then want the script to save them somewhere (a file or a database).
Any help would be really appreciated.
For further clarification, I want to create a servlet on a specific URL to handle a HTML post from another machine and receive all parameters and their values and insert them into a database for example.
Another edit, got to this code so far:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class CallbackServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
String instId=req.getParameterValues("instId")[0];
String cartId=req.getParameterValues("cartId")[0];
String desc=req.getParameterValues("desc")[0];
String cost=req.getParameterValues("cost")[0];
String amount=req.getParameterValues("amount")[0];
String currency=req.getParameterValues("currency")[0];
String name=req.getParameterValues("name")[0];
String transId=req.getParameterValues("transId")[0];
String transStatus=req.getParameterValues("transStatus")[0];
String transTime=req.getParameterValues("transTime")[0];
String cardType=req.getParameterValues("cardType")[0];
Connection conn = null;
Statement stmt = null;
PrintWriter out=res.getWriter();
try
{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "root", "root");
stmt = conn.createStatement();
int i=stmt.executeUpdate("insert into orderdetails values('"+transId+"','"+instId+"','"+cartId+"','"+desc+"'"+cost+"','"+amount+"','"+currency+"','"+name+"','"+transStatus+"','"+transTime+"','"+cardType+")");
if(i>0)
out.println("Inserted Successfully");
else
out.println("Insert Unsuccessful");
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
}
I can't test it atm unfortunately. Could you guys take a look at it and point out any mistakes/improvements?
Cheers
Probably easiest way for this would be to use Servlet api with some Java application server (tomcat, jetty, ...).Look at http://www3.ntu.edu.sg/home/ehchua/programming/java/javaservlets.html

Swing application to applet

I have made a basic swing application to input data into MySQL server. It is for some reason not accessing the driver to connect to the database. Here is the code. Thanks in advance for all the answers
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class Action extends JApplet {
public void init() {
}
public Action() {
JButton button = new JButton("Click here");
button.addActionListener(new EventHandler());
add(button);
}
}
public class EventHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/testgui";
Connection con= DriverManager.getConnection(url,"root", null);
String str = JOptionPane.showInputDialog(null,"Enter type");
String abc = JOptionPane.showInputDialog(null,"Enter number");
Statement st= con.createStatement();
st.executeUpdate("insert into tb1 values (null,'"+str+"',"+abc+")");
}
catch(Exception e1){
e1.printStackTrace();
}
}
}
please read What Applets Can and Cannot Do
Unsigned applets cannot perform the following operations:
They cannot access client resources such as the local filesystem, executable files, system clipboard, and printers.
They cannot connect to or retrieve resources from any third party server (any server other than the server it originated from).
They cannot load native libraries.
They cannot change the SecurityManager.
They cannot create a ClassLoader.
They cannot read certain system properties. See System Properties for a list of forbidden system properties.
maybe simple and possible way is look at Java Web Start, completed by #Andrew Thompson

Malformed URL when connecting applet to servlet

I'm trying to access a servlet from a java applet and set the servlet's response in the applet's text field.
I'm using tomcat 7.0 and my jre/jdk are fully updated.
The servlet runs fine (correct output in the browser) when invoked from the browser as localhost:8080/hello/hello?query=select * from airports
(where airports is the name of the database)
However when i run the applet in appletviewer, i get a Malformed URL exception thrown..
Code for Applet:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
/*
<applet code="lab101" width=500 height=270>
</applet>
*/
public class lab101 extends Applet implements ActionListener{
TextArea t;
Panel p,q,r;
CheckboxGroup c;
Checkbox ins,dis,del,update; //Checkboxes are included just for testing purposes.
TextField f;
Label l1;
Button b;
public void init(){
setLayout(new FlowLayout());
b=new Button("Run");
l1=new Label("Query:");
c=new CheckboxGroup();
t=new TextArea("",10,50);
p=new Panel();
q=new Panel();
r=new Panel();
p.add(t);
ins=new Checkbox("Insert",c,false);
dis=new Checkbox("Display",c,true);
del=new Checkbox("Delete",c,false);
update=new Checkbox("Update",c,false);
f=new TextField(50);
q.add(ins);
q.add(dis);
q.add(del);
q.add(update);
r.add(l1);
r.add(f);
r.add(b);
b.addActionListener(this);
add(p);
add(q);
add(r);
try{
URL url=new URL("127.0.0.1:8080/hello/hello?query=select * from airports");
URLConnection servletconnection=url.openConnection();
servletconnection.setDoInput(true);
InputStream in=servletconnection.getInputStream();
String s="";
int ch;
loop:while(1>0){
ch=in.read();
if(ch==-1) break loop;
else s+=(char)ch;
}
t.setText(s);
}//try close
catch(MalformedURLException e){
t.setText("Malformed URL Exception occured.");}
catch(IOException e){
t.setText("IO exception occured");}
}
public void actionPerformed(ActionEvent ae){
}
public void start(){
}
public void paint(Graphics g){
}
}//class ends
Code for servlet:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.sql.*;
public class hello extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
String query=request.getParameter("query");
Connection link=null;
Statement statement=null;
ResultSet results=null;
try{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/test";
link=DriverManager.getConnection(url,"postgres","hooligan");
out.println("Successful connection");
}
catch(ClassNotFoundException e){
out.println("Unable to load driver");
}
catch(SQLException e){
out.println("Cannot connect to database");
}
try{
statement=link.createStatement();
//String select="select * from airports";
results=statement.executeQuery(query);
}
catch(SQLException e){
out.println("Cannot execute query");
e.printStackTrace();
}
try{
out.println();
while(results.next()){
out.println("Name: " + results.getString(1));
out.println("Location: " + results.getString(2));
//System.out.println("Account no: " + results.getInt(3));
System.out.println();}
}
catch(SQLException e){
out.println("Error retrieving data");
}
try{
link.close();}
catch(SQLException e){
out.println("Unable to disconnect");}
out.close();
out.flush();
}}
Any thoughts?
P.S. i also noticed that if i use localhost instead of 127.0.0.1 i get a Security Exception thrown (Probably because the applet is unsigned?)
There are 2 (actually 3) problems:
First, an applet is only allowed to fire HTTP requests on the exact URL base as where the applet is been served from. You can obtain it by Applet#getCodeBase() which needs to be used as follows:
URL url = new URL(getCodeBase(), "hello?query=select * from airports");
URLConnection connection = url.openConnection();
// ...
Second, your query string contains illegal characters for use in URLs (space, asterisk). You need to use URLEncoder#encode() to URL-encode the query string.
String query = URLEncoder.encode("select * from airports", "UTF-8");
URL url = new URL(getCodeBase(), "hello?query=" + query);
URLConnection connection = url.openConnection();
// ...
You also need to ensure that you open the HTML/JSP page with the applet in the browser on the same base URL as where the servlet runs. E.g. http://localhost:8080/hello/pagewithapplet.html and thus not from commandline or by an appletviewer or something. The applet really needs to be served from the same webserver as where the servlet runs.
Unrelated to the concrete problem as stated in the question, your third problem is that sending a plain SQL statement as request parameter is a very bad idea. What if a hacker decompiles your applet and figures how the applet-servlet communication is done and then modifies the SQL statement into something else, such as delete from airports?
Do not do the SQL in the applet, do it in the servlet only and let the applet send specific commands only, such as hello?query=list_airports (which is actually still open for further optimization, think of a REST webservice, but that's left up to you as an exercise).
URL url=new URL("127.0.0.1:8080/hello/hello?query=select * from airports")
is not a valid URL.

Categories

Resources