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
Related
Im trying to create web app using java and mariadb but i encountered problem when tried to implement mariadb to login. Here my code:
initSql:
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
#WebServlet("/initSql")
public class initSql extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public initSql() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
Connection conn = null;
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
try {
Class.forName("org.mariadb.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/baza_new", "root","root");
System.out.println("db povezana");
}catch(Exception e){
//JOptionPane.showMessageDialog(null, e);
System.out.println("db NIiiJE povezana");
//return null;
}
}
}
LoginDAO:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dao.initSql;
public class LoginDAO {
static Connection con = null;
public static boolean validate(String username, String password, String type) {
boolean status = false;
try {
con = initSql.init();
System.out.println("1");
String query = "select * from users where username=? and password=?";
PreparedStatement pst = con.prepareStatement(query);
//pst.setString(1, type);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
status= rs.next();
con.close();
}catch(Exception e) {System.out.print(e);}
return status;
}
}
and i get markers:
Cannot make static reference to non-static method from type generic servler
Type mistmatch cannot connect from void to Connection
I'm little bit stuck with this problem.Can someone help me with my code?
People seem to be neglecting the more broad-scale issues in your code. There are standards to follow like capitalization etc but overall you have some bigger issues.
You shouldn't be making erroneous instances of initSql as it's an HttpServlet, it just doesn't make sense. You also have static/non-static references to a Connection field when you don't need it. To start with, change initSql#init to return a Connection, and while I normally wouldn't recommend abusing static this way, make the method itself static:
//returns a connection, requires no class instance
public static Connection init(ServletConfig config) { ... }
From there, we can now retrieve a Connection instance by calling this method:
Connection con = initSql.init();
Overall you should have a proper class or design for handling this, but for simple learning this is "okay".
Secondly, you're not quite using ResultSet correctly. #next will determine if there is an available row to point to from the SQL results, and if so it moves the marker to the next row. You would use it in order to check if you can retrieve results:
ResultSet set = /* some sql query */;
String someField;
if (set.next()) {
//gets the value of the column "my_field"
someField = set.getString("my_field");
} else {
//no results!
someField = null;
}
Alternatively, if you were looking for multiple results you can loop over #next
while (set.next()) {
//just one value out of many
String myField = set.getString("my_field");
}
In this use-case it's alright to check if the row exists, but I would personally check against something like user permissions or somesuch. If you relied on code like this for something sensitive you might expose something you don't want to.
Overall, I would work a little more on your logical structure for the code, and maybe go over some of the basics for Java and common coding standards for it (Google and Oracle have good guides for this).
Firstly, your class name initSql should have Capitalized first letter to follow conventions.
Secondly, you should either create an instance/object of InitSql and then call the method init() on that object or make the init() method static.
initSql.init() isn't static, which is not a problem of MariaDB and its connection from Java :) To fix this error you can add static to the mentioned method. But: As there are multiple errors in your code (e.g. assigning the result of a void method to a variable), it will not work then either..
I'm trying to have a servlet to connect and interact with a database. I'm very new at this topic, so there probably are a couple of big issues, but the main problem I'm stuck at is how to get the database URL.
This is the servlet (I'm trying to keep it as light as possible)
import java.io.*;
import java.text.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class qaServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String firstName = request.getParameter("question");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/qaDatabase", "root", "");
//^HOW DO I GET THE RIGHT URL?^
PreparedStatement ps = con.prepareStatement("insert into faq values('1','question','sì');");
int i = ps.executeUpdate();
}
catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
First, it is better to use e2.printStackTrace(); instead of System.out.println(e2); when debugging.
Second, as the exception has shown, the actual problem was missing JAR file with JDBC driver, which has to be either in the WEB-INF/lib folder of your application, or in Tomcat's lib folder.
When developing, don't forget to republish your project after adding the driver's JAR file.
It's 1:37am here so I'm greeting you all a good day.
I've got a problem here and I'm really really new to java. Please have patience on me. :(
I've got a .jar file that I imported to my Libraries in my netbeans project. It's called dbconnect.jar. I want to create a statement in my Fruits.java that will change my stmt statement (from inside dbconnect.jar) to whatever mysql statement i want it to be (specifically, I want to add fruits to my db). Here's my project map:
So inside my dbconnect.jar contains the class Dbconnect. Here are the contents of Dbconnect:
package dbconnect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Dbconnect {
public Connection conn = null;
public Statement stmt = null;
public ResultSet rs = null;
public Dbconnect(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String Host = "jdbc:mysql://localhost/dbname";
String Username = "root" ;
String Password = "";
conn = DriverManager.getConnection(Host, Username, Password);
stmt = conn.createStatement();
}catch(Exception e){
e.printStackTrace();
}
}
}
By the way, I'm using xampp for Apache and Mysql.
So my questions are, how do I call/import this dbconnect.jar of mine so I can use it in Fruits.java (and if possible, am I able to use extends here?) and how do I make it so that I can edit the stmt part in dbconnect.jar using Fruits.java ?
This is currently what's inside the add button from my UI in Fruits.java:
I really need help with this. Thank you so much in advance!
Oh and I'm still a starter. So I hope there will be no advanced codes. Thanks again!
And yes, I'm using JFrame. Here's what it looks like for now.
Since, you have Dbconnect.jar on your classpath you can just say something like this in your Fruit.java class:
Dbconnect db = new Dbconnect();
This will create a new object of Dbconnect class with name db.
In order for you to be able to edit the statement you'll have to create a new method and not just call it in the constructor.
Here is an example:
public void connect(String myStatement) {
/* Do Something */
}
You can then call connect() function on db object you created before.
I want to be able to use my web service to be able to populate a database in MySQL. From the code below, I have connected to the database that I want to populate. How can I use the data that users import on my Web Service to populate MySQL database exchangeInformation. The Web service is working and everything works. I am just looking to be able to use the input of that data from the web service to populate my database in MySQL.
Any help would be greatly appreciated.
Thanks
Code Below:
package org.example.www.newwsdlfile3;
import java.sql.Connection;
import java.sql.DriverManager;
public class JavaMYSQL {
public static void main(String[] args) throws Exception {
getConnection();
}
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/exchangeinformation";
String username = "root";
String password = "admin";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
Use this page to see an example of creating a statement from a connection object and executing a query with it. As to your webservice information, I do not see where you are passing it in. That said you can use some simple string replacement to handle that:
String sql = "INSERT INTO tableName values(':value1', ':value2',':value3', etc)";
sql = sql.replace(":value1", dataFromService);
Something along those lines should get you started.
EDIT FOR CLARITY:
String sql = "INSERT INTO tableName values(':value1', ':value2',':value3', etc)";
String dataFromService = "EDIT";
sql = sql.replace(":value1", dataFromService);
System.out.println(sql);
Would net you an output:
INSERT INTO tableName values('EDIT',':value2','value3', etc)
So I know that this may have come up a few times, but this is actually a little different. I want to authenticate a login from the authentication server. This is my code:
import java.sql.*;
public class TestConnect {
public static void main(String args[]) {
String host = "https://authserver.mojang.com";
String user = "--username--";
String pass = "--password--";
try {
Connection con = DriverManager.getConnection(host, user, pass);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
So the error im getting everytime is the following:
No driver found for https://authserver.mojang.com
A little help would be welcome :)
Read the getConnection method's doc:
http://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String,%20java.util.Properties)
url - a database url of the form jdbc:subprotocol:subname
Your url is not valid.