Communication between jsp and java application - java

My project requirement is to develop a website which interacts with a mysql database and a java application which continuously runs on the server. user is on some remote computer he sends a request to the java application by executing a jsp code on the server, the jsp code waits for the application to send the information back. once the jsp recives the info. it sends a request to database. The is a special type of database built just because of limitations of a database and my project requirements. Please tell me how the request are sent i.e. what part of java will help me do this.
some link that have the same info but not exact Communication between two separate Java desktop applications.
EDIT: my question is.... what should i use in a jsp page such that i will be able to get info. from the application which stores data in a special form of datastructure. For now I dont want to talk to database. I just want to interact with a running application.
for example there is a program on the server which returns sum of two numbers which waits for someone to give it input. now my jsp sends two numbers to the application which adds the two numbers and gives back the sum to the jsp page. now jsp page code can do anything which is not my concern for now.

Database access through the Website is one of the essential components for any web-based development. JDBC, a mechanism that allows Java to talk to databases.
Java Database Connectivity (JDBC) is a standard Application Programming Interface (API) that is used to access databases, irrespective of the application driver and database product. In other words, JDBC presents a uniform interface to databases, however, if you change the database management system and your applications, you only need to change their driver. JDBC provides cross-DBMS connectivity to a wide range of SQL databases, and other tabular data sources, such as spreadsheets or flat files.
Here is the sample example:
import java.sql.*;
class DBQuery1{
public static void main(String args[]) throws SQLException
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch(ClassNotFoundException e){};
Connection cnn;
Statement mystmt;
ResultSet myrs;
String op = "jdbc:odbc:JavaTest";
cnn = DriverManager.getConnection(op,
"Admin", "");
mystmt = cnn.createStatement();
String sql;
sql = "SELECT * FROM SupplierMaster " +
"WHERE SupplierCode IN ( " +
"SELECT SCode " +
"FROM Relation " +
"WHERE PCode IN ( " +
"SELECT ProductCode " +
"FROM ProductMaster " +
"WHERE ProdCatg IN ( " +
"SELECT CatgID " +
"FROM CategoryMaster " +
"WHERE CategoryName = 'Eatables')))";
myrs = mystmt.executeQuery(sql);
System.out.println(" "+"Sup Code" + " " +"Sup Name" + " " + "Sup Address ");
System.out.println("--------------------------------------------------------------------");
String name, add;
int code;
while (myrs.next())
{
code = myrs.getInt("SupplierCode");
name = myrs.getString("SupplierName");
add = myrs.getString("SupplierAddress");
System.out.println(" " + code +" " + name+" " + add);
}
}
}
More information you can find on this link:
http://webserver.ignou.ac.in/virtualcampus/adit/course/cst302/block2/cst302-bl2-u3.htm

Java applications most often communicate with a relational database through the use of a JDBC driver. The driver tells the application how to communicate with a specific database. Each database vendor often provides a driver for their particular database. In your case you will need the MySql Connecter/J driver, which you will include within your project as a jar file.
The JDBC drivers provided by database vendors implement an interface so connecting to different databases is pretty much the same except for a few syntax differences between parameters. There is a ton of information that can be found about how to connect to a database through a Java application.

Related

Why does this SQL-Statement lead to an error?

I am getting quite angry with this, so I seek help from the crowd ;)
What I want to do: We have a Unity learning game which shall implement a login window. The entered credentials are then hashed (the pw is) and sent to the server, who then should check this against a database.
I have the following table:
xy.users_confirms with the following colums:
id username email password hashcode created
Why does my code
String sql = "SELECT " + "xy.users_confirms.password as pwhash, "
+"FROM xy.users_confirms " +"WHERE xy.users_confirms.username = " +"\"userNameToGetHashFor\"";
lead me to the SQLException "Parameter index out of range (1 > number of parameters, which is 0)"
?
Thanks, any input is much appreciated!
Try this:
String parameter = "'"+ strNameToGetHashFor + "'";
String sql = "SELECT " + "xy.users_confirms.password as pwhash, "
+"FROM xy.users_confirms "
+"WHERE xy.users_confirms.username ="+ parameter;
You are using varchar value as a parameter so it's need to be quot like this.'username'. or you can use Stored Procedure.
Personally, I would try getting a working query using the custom query box directly in phpmyadmin. Once you have a working query you can re-write it in java.
And I would try writing the syntax like this into the phpmyadmin query box:
SELECT password as pwhash
FROM xy.users_confirms
WHERE username ='userNameToGetHashFor'
Using the above syntax I don't see anyway your error could persist.
Phpmyadmin screen cap showing custom query box: http://screencast.com/t/9h8anH0Aj
(the 2 empty text boxes in screen cap are just me hiding my database info)
The comma after pwhash is one potential cause:
+ "xy.users_confirms.password as pwhash*!*,*!* "
Depending on the DBMS, you may also need to use single quotes instead of double quotes like this:
+ "'userNameToGetHashFor'";
Also this code is potentially vulnerable to a SQL Injection attack so you may want to make the userNameToGetHashFor a parameter rather than concatenating the string into the SQL statement.

Parallel drop/create on postgres using DBA fails with: ERROR: tuple concurrently updated

We have N number of separate processes that can kick at the same time which all talk to the same postgres database. These "processes" are jdbc code which drop a user/schema and then recreate user/schema. We do this by connecting as a DBA user which is used across all processes. Each user/schema is unique so it's not as if all processes are attempting to drop the same. With that said 1 process will always succeed while the rest fail with:
ERROR: tuple concurrently updated
We are dropping with the following code:
String postgresRevokeUser = "REVOKE ALL ON DATABASE " + postgresDB + " FROM " + this.getUsername();
String postgresDropSchema = "DROP SCHEMA IF EXISTS " + this.getSchema() + " CASCADE";
String postgresDropUser = "DROP USER IF EXISTS " + this.getUsername();
connection = getDbaConnection();
connection.setAutoCommit(false);
statement = connection.createStatement();
statement.addBatch(postgresRevokeUser);
statement.addBatch(postgresDropSchema);
statement.addBatch(postgresDropUser);
statement.executeBatch();
connection.commit();
I can easily imagine what the issue is just don't know how to get around it (without putting in some synchronization between processes but that will be a fair amount of work). Any help would be great.

Java Update Sql statement error

I am trying to update a Db2 database using Java and the following code:
String sSqlString = "UPDATE P6DEVCDB00.P6OSTAPF SET STATVAL = '" + sStatVal + "' WHERE OPIID = '" + sOperationsitemid + "' AND CONGRPC = '" + sConfigGrpCode + "'";
// Do your select on a Db table.
//statement = con.createStatement();
statement = con.prepareStatement(sSqlString);
int RowsAffected = statement.executeUpdate();
con.commit();
System.out.println(RowsAffected);
I then get the following error :
DB2 SQL Error: SQLCODE=-7008, SQLSTATE=55019, SQLERRMC=P6OSTAPF ;
P6DEVCDB00;3, DRIVER=3.58.81
I have printed out the sql that it's going to run :
UPDATE P6DEVCDB00.P6OSTAPF SET STATVAL = 'ON'
WHERE OPIID = 'B20120707000681531' AND CONGRPC = 'STKLSTSTAT
When I run this sql directly with a SQLUI tool it works and the record gets updated...
Your problem is that you're attempting to use transactions over tables that are not 'journaled' - that is, setup for transactions.
Ideally, you should set up all tables (that will be run under a transaction) as journaled, specifically to test that property; regardless of being able to simulate failures, you need to make sure that your code can handle being under transactions.
Also, depending on your situation, you may not need to explicitly manage transactions. If you're using a framework like Spring, they can usually manage transactions for you, although this will usually mean that you still need journaling on your iSeries tables.
If you're just trying to test basic code behavior, look into using an in-memory database, such as HSQLDB (can emulate some LUW DB2 behavior, but not library lists, unfortunately) - this will absolve you of the need to have a connection to your box, and to set up journaling.

Database driver for Microsoft JET Database Engine

I'm currently looking to write an importer in my Java program to import data from a file which contains a JET database, but so far searching for a JDBC driver for this format (or just another Java library which can read from it) has proved fruitless.
Does anyone know if such a driver exists, or if not what (platform independent) alternatives might be available?
I actually have been importing CSV files into Access database using JDBC and jetEngine query like this
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to a MS Access DB you have on your machine
String filename = "C:/Automation_Tools/Databases/Data.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= fileName.trim() + ";DriverID=22;READONLY=false}";
// add on to the end now we can get the connection from the DriverManager
con = DriverManager.getConnection( database ,"","");
and then using query like this
String sql = "INSERT INTO " + accessTableName + " SELECT * FROM [Text;HDR=YES;TextDelimiter=\";Has Quotes=TrueFMT=Delimited(,);DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
//Import/create table
String sql = "SELECT * INTO " + accessTableName + " FROM [Text;HDR=YES;TextDelimiter=\";FMT=Delimited(,);DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
`
I am just now researching this myself and am going to try out UCanAccess. According to the main page it says that it is
an open source Java JDBC Driver implementation which allows Java developers and jdbc client programs (e.g., DBeaver, NetBeans, SQLeo, Open Office Base, Libre Office Base, Squirrell) to read/write Microsoft Access database.
Because it is a pure java implementation it run in both Windows and non-Windows Operative Systems(e.g., linux/unix). No ODBC needed.
You can use the built in JDBC ODBC bridge driver.
Use a connection string like: jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=database.mdb.
This is not platform independend. The Jet engine (or ACE) has to be installed. Sometimes there are problems with encoding and Memo fields.
There is an alternative: http://www.hxtt.com/access.html
They claim platform independence but I didn't try it myself.

java servlets : passing url variable values with spaces

I'm building a simple java Servlet which passes categories using a URL variable into another Servlet.
For example, in the following code
ResultSet rs = qw.DBquery("select distinct manufacturer from Products order by manufacturer asc");
try {
while (rs.next()) {
table+= "<tr><td><a href=\"getItems?manufacturer="
+ rs.getString("Manufacturer") + "\">"
+ rs.getString("Manufacturer") + "</a></td></tr>\n";
}
}
its output includes:
Adobe
Adobe Acrobat
IBM
IBM - Workstations
IF I click on one, the link gets to the URL as:
http://localhost/getItems?getItems?manufacturer=Adobe%20Acrobat
However, when I get the manufacturer variable and its value
String manufacturer = request.getParameter( "manufacturer" );
ResultSet rs1 = qw.DBquery("select * from products where Manufacturer like '"
+ manufacturer + "'");
the query output fails and doesn't produce anything if there are spaces in the value of manufacturer. Any ideas or workarounds on how to convert this back? Do I need to do some kind of urldecode?
thanks in advance
The encoding of space in a URL as %20 is correct, and the web application container takes care of URL decoding.
String manufacturer = request.getParameter( "manufacturer" );
The String manufacturer in your program should therefore contain 'Adobe Acrobat' (with a space). Can you verify that (by logging it to somewhere)?
"select * from products where Manufacturer like '"+ manufacturer + "'"
Also, please use bind variables.
Directly interpolating query parameters (without any validation, too!) into SQL leaves you totally open to SQL injection attacks. It is bad for performance, too.
"select * from products where Manufacturer like ? "

Categories